Error invalid combination of opcode and operands nasm

I am new to NASM. I am getting the error: invalid combination of opcode and operands on the first line below mov si,bl ;si contains address of number string mov cx,7 ;once for eac...

I am new to NASM. I am getting the error:

invalid combination of opcode and operands

on the first line below

mov     si,bl   ;si contains address of number string
mov     cx,7    ;once for each line
jmp     print_num ;print the number
loop    line_loop ;decrement cx, repeat if cx<>0
int     20h

msanford's user avatar

msanford

11.6k10 gold badges67 silver badges92 bronze badges

asked Apr 19, 2018 at 18:50

Sam M's user avatar

0

si is a 16 bit register while bl is a 8 bit register. You can only use mov instructions when the operands are both in same bits.

As a solution to your problem, use bx instead of bl

mov si,bx

It is because Intel 8086 processor uses 16 bit addressing instead of 8 bit.

By the way, you can use esi and ebx when programming 32 bit applications.

answered Apr 22, 2018 at 22:16

TravorLZH's user avatar

TravorLZHTravorLZH

3121 silver badge9 bronze badges

Topic: Error Message: invalid combination of opcode  (Read 11730 times)

James Dunlap

I get the error message «invalid combination of opcode and operands» for the lines marked below:

mov     byte_83DB7, al ;ERROR
                 or      ah, ah
                 jnz     short loc_1B005
                 cmp     byte word_83DB4, 3 ;ERROR
                 jb      short loc_1AFF6
                 cmp     al, 22h ; ‘»‘
                 jnb     short loc_1AFFA
                 cmp     al, 20h ; ‘ ‘
                 jb      short loc_1AFF6
                 mov     al, 5
                 jmp     short loc_1AFFC

Can anyone tell me why?  Both of the addresses used are in the data segment, which is being pointed to by DS.  I am using «bits 16» as this is a DOS program.  The funny memory locations are due to the fact that this is output from a disassembler.  I am working on a project where I need to figure out the format of some files used by an old game, but they are encoded.

If I change them to indirect like,
                  mov [byte_83DB7], al
then it assembles, but as I understand assembly (and I am a HUGE beginner, other than on the C64 years ago), the [] changes the address into a kind of pointer, so it looks up the contents of the address, then uses that as the location of where to store AL.  Am I way off?

Thanks for any help.


Logged


Off by «one level»… or used to Masm syntax…

An unadorned symbol, in Nasm syntax, means an «immediate». In Masm terms, «offset». You want the square brackets:

mov [byte_83db7], al

In asm, there is no «look up the contents of the address and use that as an address» («dereferencing a pointer»). We have to do that explicitly:

foo db 42
fooptr dd foo ; (dw for 16-bit code)

mov eax, [fooptr]
mov al, [eax]

In Masm, either:

mov myvar, al

or:

mov [myvar], al

are acceptable — and generate exactly the same code. In Nasm, only the second is acceptable. If we see:

mov eax, something

we need to know if it’s Masm or Nasm — and if it’s Masm, how «something» is declared:

something equ 42

would move the immediate number 42 into eax. If it’s:

something dd 0

it moves the *contents» of «something» (0) into eax.  To get the address, you’d need «offset something».

In Nasm, «mov eax, something» is always an immediate — address/offset or other. «Contents» always wants «[]». And *all* of the address goes inside the brackets. Your disassembler may produce something like «es:[foo]» or «es:foo[8]» — in Nasmese, «[es:foo + 8]»…

Hope that helps…

Best,
Frank


Logged


James Dunlap

Thank you.

That most definitely helps.  I am using NASM, and this helps to explain what is happening.


Logged


nobody

> funny memory locations are due to the fact that this is output from a disassembler

A FAULTY disassembler …

Use NDISASM or DISTORM ;-)


Logged


Ни fasm, ни NASM, ни Yasm не будут ругаться на mov [sym],al в данном случае, т.к. размер операнда ясен из формы инструкции.

Даже если написать mov [sym],ax, то NASM и Yasm ругаться не будут, т.к. они не привязывают метки к размеру данных. Более того, метки необязательно указывать с двоеточием, т.е. можно вполне написать вот так: label mov al,bl, и всё будет работать.
Соответственно, mov [sym],12 уже не прокатит, нужно указывать тип: mov byte [sym],12

А вот у fasm привязка к типу (размеру) есть, и на mov [sym],ax он будет ругаться из-за несоответствия типов, т.к. переменная sym объявлена как байтовая (если написать sym rb 1), тут нужно писать mov word [sym],ax, если что. Однако если объявить переменную через двоеточие sym: rb 1, то эта метка не привяжется к типу, и mov [sym],ax будет скомпилено нормально (fasm).
Соответственно, mov [sym],12 будет прекрасно работать (если только НЕ объявлять метку через двоеточие).

Кстати, resb (resw, resd…) лучше объявлять в секции .bss (section .bss), иначе NASM/Yasm запишет туда 0 (в файл), о чём выдаст warning.

Bogopo

To answer your question, Can a regular expression turn into assembly?, we need to understand 2 concepts a priori:regular expressionassemblyRegular expressionI am not based on modern regular expressions with look-behindatomic grouping and retrovisors; I am focusing on the most regular mathematically speaking part. The possibility of including these features in regex deconfigure the finite automaton, as they require the presence of some memory.By the way, the presence of retrovisors implies that it solves context-sensitive problems, two lower levels in the https://pt.stackoverflow.com/a/180961/64969 .A regular expression is a scheme to write a regular grammar in a single line. It can also be seen as a very compact way to mount a memoryless state machine, with unidirectional reading on the tape.Regular grammarA regular grammar is obtained through a grammar that only has regular productions. A production is called regular if it is from a non-terminal to one of the following targets:empty stringother non-terminala single terminala pair: terminal and non-terminalSee more https://pt.stackoverflow.com/a/215974/64969 which grammar to build grammars. See https://pt.stackoverflow.com/a/210716/64969 that talks about formal languages with intense affection, especially the initial parts.From a regular grammar, we can mount a directed graph that represents it, where the vertices are non-terminals (with possible exception the acceptance vertex) and the edges represent a grammatical production. Take the following grammar as an example, with q0 for the initial symbol and 0,1 as being the terminals:q0 -> 1 q1
q1 -> 0 q2
q2 -> 1 q5
q2 -> 1 q3
q3 -> 0 q3
q3 -> 1 q3
q3 -> 0 q4
q4 -> 1 q5
q5 -> 0 q6
q6 -> 1 q7
q7 -> 0 q8
It can be interpreted as the following graph: Image source: A word p is recognized by the finite automaton if it is possible, using its states and the two transaction rules described above, for in one of the accepting states without any other letter being consumed.Note that the automatons do not need to be deterministic; by the way, the existence of ambda transactions itself requires that the automaton is non-deterministic. However, there is an algorithm that transforms any non-deterministic finite automaton into a deterministic finite automaton.The automaton described above is non-deterministic: take the word 1010, in which state will she stop? The options are: q6, q4 and q3.Note that in a finite automaton, walking a path on a graph implies:make decisionsenter loopThe decision to leave a state x any depends only on himself and the next letter available in the word; any set of previous letters and transactions that result in the same state, then become idempotent.There is a useful concept in finite automaton which is called Well. When a character is not expected by the automaton, the following is the Well. When regular expression is of type belongs to the word, and not the word must be identical to the expression, Well has a hermbda transaction for the initial state. Note: all states so implicit transactions for the Well with all other alphabet letters not described in your transactions. Due to this, the well is usually ignored from the drawing.Regular languageA regular language is the set of words recognized by a grammar (or an automaton) that describes it. In this context, grammar (or automaton) can be considered generative. In this context, instead of consuming the input word, transactions are triggered by generating terminals until it comes to an end and has a new word of language. I speak more about languages and words https://pt.stackoverflow.com/a/210716/64969 . (Automatos can also be generative, behaving similarly to one https://pt.wikipedia.org/wiki/Cadeias_de_Markov ).Regular expression, returnRegular expression, then, is a scheme to describe a regular language. It is easy to understand through the graph of grammar how to build a regular expression.In general, the main operators of regular expression are:Star of Kleene * used to represent loops that occur within the graphSelection | used to represent diverse paths that can be tracked from a common originGrouping () used to demonstrate a number of transactions that were firedList [], used to equal a multi-colored transaction, such as q3->q3Escape , force the next character to have literal meaning, losing its powers as meta-characterIn view of these training rules, we can transform the non-deterministic automaton without licking into the following regular expression:10(1|1[01]*01)010
More modern regular expressions have won other more modern operators such as optional ? and Kleene cross +, but these operators are easily transformed into previous operators.Compiling regular expressions with context-free grammarsRegular expressions cannot be identified by regular expressions. This is because, in its most basic definition, regular expressions suffer self-igning. More about this https://pt.stackoverflow.com/a/210716/64969 .A quick demonstration of the self-igning of regular expressions:11100(0101(11111[01][01]*[01]00000)*00)*11100
The general grammar for a regular expression is (in BNF-symile notation):S -> EXP
EXP -> EXP . EXP
EXP -> NQEXP
EXP -> NQEXP . QUANT
QUANT -> ‘*’
NQEXP -> ‘(‘ . EXP . ‘)’
NQEXP -> ‘[‘ . LETRAS_LISTA . ‘]’
NQEXP -> » . qualquer caracter
NQEXP -> LETRA
LETRAS_LISTA -> ‘]’ . LETRAS_LISTA2
LETRAS_LISTA -> LETRAS_LISTA2
LETRAS_LISTA2 -> todas as outras, exceto ‘]’
LETRA -> qualquer caracter não especial
Note:S of startEXP of expressionNQEXP of quantified expressionQUANT of quantifiedAssemblyFrom the tag /questions/tagged/assembly :Generally, a mnemonic is a symbolic name for a single instruction in executable machine language (an operating code), and there is at least one opcode mnemonic set for each machine language instruction. Each instruction typically consists of an operation code operation and zero or more operands. Most instructions refer to a unique value, or a pair of values. Operators can be immediate (coded value in the instruction itself), records specified in the instruction or implicit, or data addresses located elsewhere in the storage. This is determined by the underlying processor architecture: the assembler only reflects how this architecture works.Normally, these operators perform the following computations:load memory value in registrarwrite in memory value of the registeredlogical operations with operators and constantsarithmetic operations with operators and constantsoperations bitwise with operators and constantsflow of operationsIt is important to note that the logical/environmental operations/bitwise are fixed biting for https://pt.stackoverflow.com/a/237026/64969 .Pointer disreferral operations is an operation of charging memory value to a registrar.Implementation of a programmeAssembly is made in a deterministic manner, each execution being planned (directly or indirectly) by the programmer. The same dataset is executed, step by step, by the processor.The only option of non-determinism that I can find for non-quantum processors is processing depends on random data of uncontrollable origin (I’m not talking about random() of languages as /questions/tagged/c or /questions/tagged/java but of variables that come from outside the computer; random() is deterministic for past seed, while usually seed is dependent on system time). Still, this behavior may well be simulated as an oracle function, the behavior of the system (ignoring the inner functioning of the oracle) becomes deterministic.Assembly for RegexHow to set an assembly for regular expressions? Well, assembly depends on a set of instructions that are followed deterministicly. Simply carrying what is written in regex without further translations for a machine language will not make it deterministic.An alternative, therefore, would transform the regular expression into a finite automaton and then transform it into a deterministic finite automaton. Commonly, this is implemented as a multiple deviation for each state and each state attempts a multiple deviation to the relevant letters. States with unforeseen transactions would fall into the well. Meta-character implementation . and the denied list rests on multiple deviations too.The automaton of the examples can be described by the following regular non-deterministic language grammar:q0 -> 1 q1
q1 -> 0 q2
q2 -> 1 q_{5,3}
q_{5_3} -> 1 q3
q3 -> 0 q_{3_4}
q_{3_4} -> 0 q3
q3 -> 1 q3
q_{5_3} -> 0 q_{6_3_4}
q_{3_4} -> 1 q_{5_3}
q_{6_3_4} -> 0 q3
q_{6_3_4} -> 1 q_{7_5_3}
q_{7_5_3} -> 1 q3
q_{7_5_3} -> 0 q_{8_6_3_4}
q_{8_6_3_4} -> 0 q_{3_4}
q_{8_6_3_4} -> 1 q_{7_5_3}
What results in the following graph (with q0 the incial state and q_{8_6_3_4} the only state of acceptance): Demo that is non-ambiguous and deterministic:check all the emerging edges of a given vertex; all of them have different shooting conditions for whatever;There are no transitions-lambda.Therefore, it is non-ambiguous and deterministic.To represent in atomic units, the following transactions could turn an assembly more or less as follows:defines the table of states with labels; if the automaton is in the state q_{5_3}, it will go to the label content q_{5_3} with a deviation;the step contained in início is a deviation to the correct label; this can be done by elaborating a vector of labels relating each position to a label; in this case, the deviation would be:# sejam os trechos começados por «#» comentários até o final da linha
# sejam «reg_a», «reg_b», «reg_c» registradores de propósito geral
# seja «reg_est» o registrador específico para guardar o estado do autômato
# seja strings começadas com «$» constantes
# seja a operação «set a, b» a operação que seta em «a» o valor de «b»
# seja «add y, x, a» a operação que salva em «y» o valor da soma de «x» e «a»
# seja «[a]» o acesso ao local de memória apontado por «a», portanto retornando o conteúdo apontado pelo ponteiro «a»
# seja «jmp a» a operação de salto incondicional para a posição «a» da pilha de execução
# seja «label a» o rótulo chamado «a», usado para futura referência de desvios incondicionais
# seja «<a>» a referência ao rótulo «a»
label inicio:
set reg_a, $pos_vetor_rotulos
add reg_b, reg_a, reg_est
set reg_a, [reg_b]
jmp reg_est
for each state block end, there is an unconditional deviation to the início;for each affirmative finite transition fired, has a condition changing the state to the vertex at the end of the edge of the transition fired; if accepted in any of these conditions, jump to the end of the block;for the transition above, if you have not jumped to the end of the block, the next state will be the Well;# exemplo para o estado q_{5_3}
seja «reg_c» o registrador que contém o caracter sendo consumido da palavra
seja «jneq dest, v1, v2» o salto condicionado para «dest» caso «v1» e «v2» sejam não iguais
label q_{5_3}:
jneq <q_{5_3}1>, reg_c, ‘0’
set reg_est, <q{6_3_4}>
jmp <fim_q_{5_3}>
label q_{5_3}1:
jneq <q{5_3}2>, reg_c, ‘1’
set reg_est, <q_3>
jmp <fim_q{5_3}>
label q_{5_3}2:
set reg_est, <poço>
label fim_q{5_3}:
jmp <inicio>
for each element of the denied list transition, has a conditional with jump to Well;for coring transitions (usually called the meta-character . or the valid content on a linked list), has the jump determined to the next state of that transition.With that, we would have an assembly-symile code of regular expressions.ConclusionUsing the limitations of a mounting languageload memory value in registrarwrite in memory value of the registeredlogical operations with operators and constantsarithmetic operations with operators and constantsbitwise operations with operators and constantsflow of operationsthe representative code of a regular expression would be very extensive and unreadable. For debugging purposes, it would be better to transform into non-deterministic finite amino acid and show in which state is the recognition of the past pattern.Graphically, it is very interesting to check the current state of the processing highlighted in the AFD, as well as it would also be interesting to follow in the last word to find the standard which the position being recognized at that time. It would also be interesting to map the state of the deterministic automaton to its equivalent positions in the regular expression.

  • Summary

  • Files

  • Reviews

  • Support

  • Mailing Lists

  • Tickets ▾

    • Feature Requests
    • Bugs
    • Patches
  • News

  • Discussion

  • Code

Menu

NASM macro parser suxx


Created:

2008-03-10

Updated:

2013-06-04

  • Nobody/Anonymous

    OK, here’s my problem: I’ve a macro and I always get «error: invalid combination of opcode and operands». What the f* is wrong in nasm?!? (My code couldn’t be wrong, because nasm compiles it without a fass if it’s not in a macro). And, how can I make nasm to print more specific error messages?!? I only got the line number of the macrocall, how can I get the line inside a multiline macro?!?

    Here’s my code (does not work):

    %assign        exceptionmask        (event | event.hwexception << 2)
    %macro        exceptionhandler    2
    kernel_ex%1:
    %if %2
            pop            ebx
    %else
            mov            ebx, 0
    %endif
            pushad
            movzx            eax, %1
            shl            eax, 4
            add            eax, exceptionmask
            jmp            kernel_syscall
    %endmacro

            exceptionhandler    00h, 0
            exceptionhandler    01h, 0
            exceptionhandler    02h, 0
            […]

    Another code (that’s working):

    kernel_ex00h:
            mov            ebx, 0
            pushad
            movzx            eax, %1
            shl            eax, 4
            add            eax, exceptionmask
            jmp            kernel_syscall

    Any suggestion would be greatful. And PLEASE, if an error occurs in a multiline macro, print that line number…
    Cheers,
    Turdus

    • Nobody/Anonymous

      I’ve found the problem:

      %macro movez 1
      movzx %1
      %endmacro

      movzx 01h ;this will work
      movez 01h ;but this won’t

      nasm version: NASM version 0.98.40 (Apple Computer, Inc. build 11) compiled on Sep 23 2007

      Cheers,
      Turdus

      • Debbie Wiles

        movzx requires two parameters. It takes the form:

        movzx reg,reg/mem

        As Frank said, the second parameter must be sized, so if it is a memory reference you need an operand size specifier.

        «movzx 01h» should NOT work, because you are only giving it one operand. The error is right :)

    • Nobody/Anonymous

      I’d expect movzx to require a size specifier — byte or word (unless second operand is a reg). Try that. The «-e» switch should provide preprocessed output, try assembling that with «-a» and see where the error is(?). Or comment out lines one at a time.

      Best,
      Frank

    • Debbie Wiles

      One problem in your original code is how you defined the macro

                  %assign exceptionmask (event | event.hwexception << 2)
                  %macro exceptionhandler 2

      Change the above line to read:

      %macro exceptionhandler 1-2

      That will allow you to use either 1 or two parameters, and is documented in the nasm manual since earlier than the version you are using.

      Further in the code, you also have other problems:

                  kernel_ex%1:
                  %if %2

      In your code, this will always be true (assuming you call it with two parameters, as you are doing), and will create a problem later in your code…

                  pop ebx

                  %else

      This will never be used, as you are only allowing 2 parameters. It will either give an error (with one parameter) or will have popped ebx, without ever resetting the stack pointer.

                  mov ebx, 0
                  %endif

      At this point, if you used two parameters, you have popped 32-bits. If you used 1 parameter (and corrected the definition), you have pushed nothing. The stack pointer will not be the same for the two cases. One of these will break other parts of your code (without knowing all the code I don’t know which is wrong, but I assume popping a value and not correcting the stack pointer is the error here).

                  pushad
                  movzx eax, %1
                  shl eax, 4
                  add eax, exceptionmask
                  jmp kernel_syscall
                  %endmacro

      You can’t predict what will happen here if both routes through the macro leave the stack in a different state (ie at a different address and not always where it was on entry).

    • Nobody/Anonymous

      Frank: thanks for the advice, that’s what I did: I commented out line by line. Now I don’t understand: why does not require the size specifier if it’s not in a macro? It should produce the error anyhow, shouldn’t it?

      Wiles: I know movzx requires 2 parameter, I was just pointing out the problem. And I know, I could use variable number of arguments, but I don’t want to. I want to see that zero when calling the macro. As for conditional part, you’re right, I should have used %ifidn.

      Thanks everybody!

      Cheers,
      Turdus

    • Nobody/Anonymous

      Wiles: oh, just another thing about the stack. If you see Intel’s manual, you would see that some exceptions place a value on the stack, others don’t. So the stack is in undefined state here, and the point is, to get the value from the stack (if any), and leave stack pointer in the same state before the jump, therefore avoid the error :-)

      Cheers,
      Turdus

    • Nobody/Anonymous

      I can’t duplicate the problem with «movzx». Of course, if it occurs in a macro, «assemble.c» won’t see it unless the macro is invoked, and the problem is in a true branch. This is «obvious» when you think about how a macro works, but you can lose sight of it when you’re workin’ on the damn thing. (*I* can, anyway…).

      I’d have guessed «%if %2 = 0» for the conditional, but this emits *both* the «%if» and «%else» branch (???????… now *this* seems like a bug! ???) «%ifidn %2, 0» seems to work…

      Best,
      Frank

    • Nobody/Anonymous

      Hmmm, now I can’t duplicate the «emit both branches» problem — either «%if %2 = 0» or «%ifidn %2, 0» seem to work. Problem between the keyboard and the chair, I suspect…

      Oh well,
      Frank

    • Nobody/Anonymous

      > why does not require the size specifier if it’s not in a macro?
      > It should produce the error anyhow, shouldn’t it?

      YES. But it’s a known problem of probably __all__ assemblers that there are a few bugs available that the assembler __won’t__ report — bug of the assembler, yeah … assemblers are designed and tested more to __accept all valid__ instructions, rather than to reject __any possible __ buggy input.


Log in to post a comment.

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

Whole code of second stage bootloader.

;
;                        «Alt Ctrl Delet» 
;                           ACD Loader
;                  (Bootloader Stopnia Drugiego)
;                              v1.0
;
;                            Mrkaktus
;                      12 pazdziernika 2005
;     
;             
; Bootloader drugiego stopnia. Do jego zadan nalezy:
;
; [PROCEDURY 16bit]
; — Sprawdzenie typu procesora
;   (minimum 386)
;
; [PROCEDURY 32bit]
; — Zapisanie dostepnosci rozszerzen procesora
;   (Koprocesor, MMX, 3DNow!, SSE, SEE2, SSE3 itd.)
; — Sprawdzenie trybu pracy procesora
;   (wymagany tryb rzeczywisty)
; — Obliczenie rozmiaru pamieci operacyjnej RAM
;   (minimum 1mb RAM)
; — Wlaczenie linii A20
; — Zaladowanie Kernela do pamieci RAM
; — Utworzenie tablicy GDT
; — Utworzenie tablicy IDT
; — Utworzenie PD i PT systemu
; — Utworzenie GTB i TB
; — Oznaczenie zarezerwowanych stron w GTB/TB
; — Oznaczenie blokow specjalnych w PT
; — Uruchomienie PM
; — Wyczyszczenie potoku skokiem do kodu kernelu
;

;——————+
; PROCEDURY 16 BIT |
;——————+

; Inicjacja segmentow i reset stosu

     cli                                             ; Wylaczamy obsluge przerwan na
                                                     ; czas resetowania stosu.
     mov ax, 0x1800                                  ; Bootloader laduje nas pod adres
     mov ds, ax                                      ; 96KB wiec ustawiamy odpowiednio
     mov es, ax                                      ; nasze rejestry.
     mov ax, 0x0800                                  ; Resetujemy stos systemu.
     mov ss, ax                                      ; /
     mov sp, 0xFFFF                                  ; (Rozmiar stosu 64KB)
     sti                                             ; Przywracamy obsluge przerwan.

; Wyczyszczenie ekranu pod wyswietlenie komunikatow

     mov al, ‘ ‘                                     ; Czy?? znakiem spacji
     mov ah, 0x1B                                    ; Kolor tla niebieski a znaku bialy.
     mov dx, 0xB800                                  ;Za?aduj segment ekranu
     mov es, dx                                      ;/
     xor di, di                                      ; Brak przesuniecia (DI=0)
     mov cx, 2000                                    ; Ustal ilo?? powtu?e? czyszczenia (80×25=2000)
     cld                                             ;Powta?aj kopiowanie danych.
     rep stosw                                       ;/

     mov ax, 1                                       ; W pozycji X=1 Y=1
     mov bx, 2                                       ; wyswietla komunikat
     mov cl, 1fh                                     ;
     lds si, powitanie                               ; powitania
     call WRITE                                      ;

     HALT_CPU:                   ; Je?eli wyst?pi? powa?ny b??d skacze tutaj i
     jmp HALT_CPU                ; zatrzymuje wywo?anie systemu.

;————————————————————————————-
; Podstawowa procedura wyswietlajaca napis:                          v1.1 — 13.10.2005
; AX, BX — pozycja X,Y
;     cl — atrybuty tla i textu
; DS:SI  — wskaz na ciag znakow
WRITE:
     push cx
     mov cx, bx                                      ; Kopiuje Y do CX
     shl bx, 7                                       ; Mnozy Y * 128
     shl cx, 5                                       ; Mnozy Y * 32
     shl ax, 1                                       ; Mnozy X * 2
     add ax, bx                                      ;Dodaje (Y * 160) do (X*2)
     add ax, cx                                      ;/(przesuniecie na ekranie)
     mov dx, 0xb800                                  ;  Przygotowuje w ES:DI
     mov es, dx                                      ; |-adres poczatkowy do
     mov di, ax                                      ;/  zapisu na ekran.

     pop cx
     WR_PETLA:
     mov dl, [ds:si]                                 ; Odczytaj znak i sprawdz
     cmp dl, 0                                       ; czy nie koniec ciagu
     jz  WR_KONIEC                                   ; Jak tak to koncz
     movsb                                           ; Kopiuje z DS:SI do ES:DI
     mov byte [es:di], cl
     inc di                                          ; Omin parametry na ekranie
     jmp WR_PETLA                                    ; Kopiuj kolejny znak

     WR_KONIEC:                                      ; Konczymy procedure
     ret

powitanie db ‘Inicjuje system…’,0

so I think everything is ok. And about giving it in [powitanie] im not sure. Aren’t we getting the data from variable in such way?

In my quest to learn NASM, I am trying to create a really simple program that does a division and outputs the result. В своем стремлении изучить NASM я пытаюсь создать действительно простую программу, которая выполняет деление и выводит результат.

By the books, everything should run fine. По документам все должно работать нормально. I’m dividing 15 by 3, and it should automatically be stored in the AX register which I then move over to the ecx for output. Я делю 15 на 3, и оно должно автоматически сохраняться в регистре AX, который я затем перемещаю в ecx для вывода.

However, when I try to compile, I am getting the error Однако, когда я пытаюсь скомпилировать, я получаю ошибку

nums.asm:6: error: invalid combination of opcode and operands
nums.asm:7: error: invalid combination of opcode and operands

Does anyone know what is wrong with lines 6 and 7? Кто-нибудь знает, что не так со строками 6 и 7?

This is my code: Это мой код:

segment .text

    global main
main:

    div     3, 15
    mov     ecx, ax
    mov ebx,1       ; arg1, where to write, screen
    mov eax,4       ; write sysout command to int 80 hex
    int 0x80        ; interrupt 80 hex, call kernel



exit:   mov eax, 1
    xor ebx, ebx 
    int 0x80

en

Понравилась статья? Поделить с друзьями:
  • Error invalid class object
  • Error invalid captcha response
  • Error invalid byte sequence for encoding utf8 0xff
  • Error invalid byte sequence for encoding utf8 0xd0
  • Error invalid byte sequence for encoding utf8 0x00