1. Dashboard
  2. Mitglieder
    1. Letzte Aktivitäten
    2. Benutzer online
    3. Team
    4. Mitgliedersuche
  3. Forenregeln
  4. Forum
    1. Unerledigte Themen
  • Anmelden
  • Registrieren
  • Suche
Alles
  • Alles
  • Artikel
  • Seiten
  • Forum
  • Erweiterte Suche
  1. AutoIt.de - Das deutschsprachige Forum.
  2. Mitglieder
  3. AspirinJunkie

Beiträge von AspirinJunkie

  • MySQL select Abfrage multiple

    • AspirinJunkie
    • 5. November 2024 um 09:16
    Zitat von wuff100

    Keine Version funktioniert.

    Ich habe dir gezeigt wie man Strings mit Variableninhalten anreichert - nicht mehr.
    Und diese Varianten funktionieren alle.

    Für dein MySQL-Problem fehlen, wie von SOLVE-SMART bereits geschrieben, relevante Informationen.
    Wir wissen ja noch nicht mal was mit "nicht funktioniert" überhaupt gemeint ist. Kommt nichts zurück? Kommt ein Fehler? Kommt das falsche Ergebnis?
    Was ist überhaupt das Ziel?
    Was möchtest du genau abfragen?
    Woraus möchtest du es abfragen?
    Wie ist die Quelle struktuiert und aufgebaut?
    Klappt prinzipiell die Anbindung an die Datenbank oder scheitert es schon an der Verbindung?

    etc. etc. etc....

  • MySQL select Abfrage multiple

    • AspirinJunkie
    • 5. November 2024 um 06:31
    Zitat von wuff100

    Denke habe ein Syntax Problem.

    Genau.
    Das And ist bei dir nicht Teil der Zeichenkette sondern steht außerhalb (je nach Editor siehst du das auch gleich am Syntax-Highlighting - wie hier auch im Forum).
    Daher wirkt es als klassischer AutoIt-And-Operator und verknüpft logisch 2 Strings.
    Da es beides keine Leerstrings sind, ist das Ergebnis daher (da True And True = True) True.
    Den Fehler hast du gut eingegrenzt durch Debugging (in deinem Fall: Ausgabe der derzeitigen Variableninhalte).

    Jetzt geht es dir also um die Frage wie du den String korrekt aufarbeitest, damit die richtige Query bei MySQL ankommt.
    Dafür gibt es verschiedene Methoden:

    AutoIt
    ; Variablen
    $iID = 123456
    $sOrdner = "Hallo"
    
    ; bisherige Variante
    $sQuerySelect = "SELECT id FROM webtable WHERE Nummer=" & '123456' And "Ordner=" & 'Hallo'
    ConsoleWrite($sQuerySelect & @CRLF)
    
    ; Variante mit Konstanten:
    $sQuerySelect = 'SELECT id FROM webtable WHERE Nummer=123456 And Ordner="Hallo"'
    ConsoleWrite($sQuerySelect & @CRLF)
    
    ; Variante mit Variablen:
    $sQuerySelect = 'SELECT id FROM webtable WHERE Nummer=' & $iID & ' And Ordner="' & $sOrdner & '"'
    ConsoleWrite($sQuerySelect & @CRLF)
    
    ; Variante mit Stringformat (wäre mein Favorit):
    $sQuerySelect = StringFormat('SELECT id FROM webtable WHERE Nummer=%d And Ordner="%s"', $iID, $sOrdner)
    ConsoleWrite($sQuerySelect & @CRLF)
    
    ; Variante mit ExpandVarStrings
    Opt("ExpandVarStrings", 1)
    $sQuerySelect = 'SELECT id FROM webtable WHERE Nummer=$iID$ And Ordner="$sOrdner$"'
    ConsoleWrite($sQuerySelect & @CRLF) 
    Alles anzeigen

    Ideal wäre eigentlich noch eine Funktion, welche die einzufügenden Strings escaped um SQL-Injections zu verhindern (oder alternativ prepared statements oder gleich procedures).
    Für SQLite gibt es soetwas in der mitgelieferten UDF.
    Ob deine verwendete MySQL-UDF soetwas auch hat müsstest du mal schauen.

  • Keine Leerzeichen im ungültigen Verknüpfungszielpfad

    • AspirinJunkie
    • 31. Oktober 2024 um 10:05
    Zitat von fee

    Kann jemand dieses Verhalten bestätigen

    Ich kann das Verhalten bei mir nicht reproduzieren (AutoIt: v. 3.3.16.1, Windows: v. 11 H24H2)
    Die Pfade werden korrekt eingetragen (mit Anführungszeichen ohne Ersetzung mit Unterstrichen)

    Das Problem hängt mit großer Sicherheit nicht auf AutoIts Seite, sondern wurde von mehreren Leuten berichtet, welche die zugrundeliegende API-Funktion IShellLink verwenden: >>Link1<<, >>Link2<<, >>Link3<<

    Hintergrund ist wohl, dass die Funktion Informationen benötigt, welches Dateisystem auf dem Ziellaufwerk verwendet wird.
    Dann kann sie entscheiden ob Leerzeichen im Pfad erlaubt sind oder mehr als die 8.3-Notation geht usw.
    Wenn das Ziellaufwerk aber nicht existiert fehlen diese wichtigen Informationen und die Funktion geht einfach vom schlimmsten aus - nämlich, dass das Dateisystem dort keine Leerzeichen im Pfad unterstützt.
    Ich vermute daher stark, wenn dein Zieldateiname mehr als 8 Zeichen hat und die Endung mehr als 3, dann würde in diesem Fall auch auf 8.3-Format hin abgeschnitten - kannst du ja mal testen.
    Ein wirklicher Bug ist es daher auch nicht, da das Verhalten begründet ist.

    Aktuelle, supportete Windows-Versionen scheinen das Verhalten geändert zu haben.

  • Probleme mit WMIC

    • AspirinJunkie
    • 20. Oktober 2024 um 15:10
    Zitat von BigRox

    Wie komme ich an die Informationen zum WMI-COM-Objekt?

    Naiv rangegangen: Wenn du das jeweilige Objekt hast, frag dessen Typ mit ObjName() ab.
    Nach dem jeweiligen Wert dann googlen und du findest in der Regel damit die Eigenschaften des jeweiligen Objektes.

    Das WMI-Objekt wäre z.B. das SWbemServicesEx, was wiederrum nach der Beschreibung dort eine Erweiterung des SWbemServices ist.
    Das Ergebnis von .ExecQuery wäre dann das SWbemObjectSet und die einzelnen Items wären SWbemObjectEx bzw. SWbemObject usw.

  • Probleme mit WMIC

    • AspirinJunkie
    • 19. Oktober 2024 um 18:01

    Du kannst auch anstatt über externe Tools zu gehen, das WMI-COM-Objekt verwenden.
    Das macht das arbeiten strukturierter und flexibler.
    Dein konkretes Beispiel würde man z. B. damit folgendermaßen umsetzen können:

    AutoIt
    #RequireAdmin
    
    ; deine Variablen:
    $sUserName = "Test"
    
    ; WMI-Objekt erstellen
    Global $oWMI = ObjGet("winmgmts:")
    
    ; Query erstellen und ausführen (ermittelt die Objekte, welche geändert werden sollen)
    Global $sQuery = StringFormat('SELECT * FROM Win32_UserAccount WHERE Name="%s"', $sUserName)
    Global $oQueryResults = $oWMI.ExecQuery($sQuery, "WQL", 48)
    
    ; Ergebnisse durchgehen
    For $oItem In $oQueryResults
    
    	; Änderungen vornehmen
    	$oItem.PasswordExpires = False
    
    	; Änderungen übernehmen
    	$oItem.Put_()
    Next
    Alles anzeigen
  • LinearAlgebra UDF - LinearAlgebra für AutoIt mit BLAS/LAPACK

    • AspirinJunkie
    • 24. September 2024 um 07:27
    Zitat von Andy

    oder durch RtlMoveMemory ersetzen....

    Da ich nicht überlappend kopieren muss ist memcpy die schnellere Option.

    Zitat von Andy

    aber ich möchte sehen, was die einzelnen Funktionen können (seitens Geschwindigkeit s. Assemblerfunktion zum Aufsummieren direkt in AutoIt )

    Die Optimierung erfolgt auf vielen verschiedenen Ebenen. Einmal natürlich auf algorithmischer Ebene.
    Zum anderen natürlich die Ebene auf die du schielst: Welche Prozessorbefehle kommen wie zum Einsatz?
    Tatsächlich optimieren diese Bibliotheken noch auf einer anderen Ebene, welche man nicht so einfach aus dem Maschinencode lesen kann.
    Die Abarbeitung erfolgt so, dass die Prozessorcaches möglichst optimal genutzt werden.
    Hierzu gibt es ein sehr bekanntes Paper von Goto, wo beschrieben wird wie er damals vorgegangen ist (während vorherige Implementierungen sich auf den L1-Cache konzentriert haben lag sein Fokus hingegen auf dem L2-Cache).

    Zitat von Andy

    hat ggf. jemand die Möglichkeit bzw. eine Software, die 64-Bit-libopenblas.dll zu disassemblieren mit ähnlichem Funktionsumfang wie IDA Pro?

    Wäre >>Ghidra<< von der NSA evtl. etwas was dir weiterhelfen könnte?

  • LinearAlgebra UDF - LinearAlgebra für AutoIt mit BLAS/LAPACK

    • AspirinJunkie
    • 23. September 2024 um 07:49
    Zitat von Andy

    Die x86*.dll lässt sich, zumindest aktuell bei mir, nicht downloaden...

    Downloaden lässt sie sich bei mir durchaus problemlos (ich habe die OpenBLAS-0.3.28-x86.zip genommen und dort liegt die dll im Unterverzeichnis /bin/libopenblas.dll).

    Allerdings taucht damit ein völlig anderes Problem auf: Die allermeisten Skripte laufen nicht unter 32 Bit, was aber überhaupt nicht mit der BLAS-DLL zusammenhängt.
    Das Problem lag an anderer Stelle: Um Matrizen zu kopieren verwendete die UDF bisher RtlCopyMemory, was aber offensichtlich für 32 Bit-Programme gar nicht zur Verfügung steht.
    Ich hab das daher einfach durch memcpy ersetzt und nun laufen die Skripte bei mir auch unter 32 Bit.

    Das entsprechende Update habe ich hochgeschoben.

  • ShellExecute: Fehler beim Öffnen einer PDF

    • AspirinJunkie
    • 20. September 2024 um 08:43

    Erstmal willkommen im Forum.

    Dann: Am besten wäre ein Minimalskript.
    Also ein Skript, welches den Fehler reproduziert aber vorher schrittweise um die Teile entschlackt wurde die für die Fehlerreproduktion irrelevant sind.
    In deinem Fall könnte das sogar ein Einzeiler am Ende bedeutet: der Aufruf der pdf per z.B. Run oder ShellExecute().

    Vorteil für dich: Die deutlich höhere Wahrscheinlichkeit, dass dir auf dieser Basis jemand das Problem analysieren kann ist meistens nur der Nebeneffekt, da du beim Entschlackungsvorgang mit hoher Wahrscheinlichkeit selbst das Problem extrahieren konntest.

  • LinearAlgebra UDF - LinearAlgebra für AutoIt mit BLAS/LAPACK

    • AspirinJunkie
    • 19. September 2024 um 14:42

    Lineare Algebra in AutoIt

    Eine Bibliothek zur linearen Algebra, entwickelt in AutoIt. Diese Bibliothek bietet eine Vielzahl von Funktionen zur Durchführung von Berechnungen und Operationen in der linearen Algebra.

    Idee

    Eine UDF zur Linearen Algebra in AutoIt.
    Ziel dieser ist es möglichst thematisch umfassend, performant und einfach zugänglich zu sein.

    Als Grundlage der UDF dient die weit verbreitete Softwarebibliothek BLAS/LAPACK.
    Der Nutzer soll bei der Verwendung möglichst intuitiv arbeiten können und ohne größere adminstrative Aufwände auskommen.

    Ein besonderer Schwerpunkt liegt in umfangreichen Funktionalitäten zur Ausgleichungsrechnung.

    Aufbau

    Die UDF ist in 3 Teil-UDFs untergliedert: BLAS.au3, LAPACK.au3 sowie LinearAlgebra.au3.
    In den ersten beiden sind die Low-Level-Schnittstellen zu den jeweiligen BLAS/LAPACK-Funktionalitäten implementiert.
    Auf dieser Basis baut die LinearAlgebra.au3 auf, welche als primäre Schnittstelle für den Endanwender gedacht ist.
    Die Funktionen hier bieten einfacherere Schnittstellen und Zugang zu komplexeren Algorithmen wie z.B. Regressionen und Ausgleichungsrechnung.

    Neben diesen 3 Dateien wird zusätzlich noch eine DLL benötigt, welche die BLAS/LAPACK-Schnittstelle implementiert.

    Einrichtung

    • Download der 3 Dateien `BLAS.au3`, `LAPACK.au3` sowie `LinearAlgebra.au3` (oder gleich clone des Repositories) von >>Hier<<
    • Download einer aktuellen BLAS/LAPACK-DLL:
      • Empfehlung: OpenBLAS (theoretisch sollten auch andere BLAS/LAPACK-Implementierungen funktionieren - jedoch sind dann evtl. zusätzliche Anpassungen notwendig)
      • Download der Datei OpenBLAS-x.x.xx-x64.zip und Extraktion der Datei libopenblas.dll in den selben Ordner wie die LinearAlgebra.au3
    • Nun sollten die Beispieldateien im Unterordner /examples ausführbar sein.

    Umfang

    Code
    ---- vector/matrix creation ----
    _la_fromArray                 - converts a AutoIt array or array define string into a matrix map
    _la_fromStruct                - creates a matrix/vector map from a DllStruct as used here in the UDF
    _la_createVector              - creates new empty vector
    _la_createMatrix              - creates new empty matrix
    _la_createIdentity            - create identity matrix/vector
    _la_duplicate                 - creates an independent copy of a matrix/vector map
    _la_fromFile                  - reads a matrix or a vector from a file created by _la_toFile()
    
    ---- extraction/transforming ----
    _la_join                      - combines 2 matrices
    _la_transpose                 - transposes a matrix in-place or out-place and [optional] scaling
    _la_ReDim                     - changes the shape of a matrix by by changing the number of columns (also matrix <-> vector conversion)
    _la_getRow                    - extracts a row of a matrix as a vector
    _la_getColumn                 - extracts a column of a matrix as a vector
    _la_getDiag                   - extracts the diagonal of a matrix as a vector
    _la_getTriangle               - extract upper or lower triangle part of a matrix
    _la_VectorToDiag              - creates a diagonal matrix from a vector
    
    ---- data output ----
    _la_display                   - displays a matrix/vector map, similar to _ArrayDisplay
    _la_toArray                   - converts a matrix/vector map into an AutoIt array
    _la_toFile                    - write a matrix/vector into a file
    
    ---- scalar operations ----
    _la_rotate                    - applies a plane rotation to coordinate-pairs
    
    ---- matrix attributes ----
    _la_isPositiveDefinite        - checks whether a matrix is positive definite
    _la_isSymmetric               - checks whether a matrix is symmetrical
    _la_rank                      - determines the rank of a matrix
    _la_determinant               - calculate the determinant of a matrix
    _la_conditionNumber           - determine the condition number of a matrix
    
    ---- unary operations ----
    _la_inverse                   - calculates the inverse of a matrix
    _la_sum                       - calculates the sum of the elements of a matrix, vector or parts thereof
    _la_asum                      - calculate the sum of the absolute(!) values of a matrix/vector
    _la_amin                      - finds the first element having the minimum absolute(!) value
    _la_amax                      - finds the first element having the maximum absolute(!) value
    _la_norm                      - calculate the euclidian norm of a vector
    _la_mean                      - calculate the mean of a vector or parts of a matrix
    
    ---- element wise operations ----
    _la_sqrtElements              - calculates the square root of each element of a matrix/vector
    _la_squareElements            - calculates the square of each element of a matrix/vector
    _la_invElements               - forms the reciprocal (1/x) for each element of the matrix/vector
    
    ---- addition subtraction ----
    _la_sub                       - subtracts a matrix/vector B from matrix/vector A
    _la_add                       - calculate the sum of a matrix/vector/scalar mA and a matrix/vector/scalar mB
    
    ---- multiplication ----
    _la_mul                       - calculates a multiplication between a matrix/vector/scalar A and a matrix/vector/scalar B
    _la_outerproduct              - calculates the outer product ("tensor product") of two vectors
    _la_dot                       - calculate the "dot product"/"scalar product"/"inner product" of two vectors
    _la_scale                     - multiplies the elements of a matrix/vector by a scalar value
    _la_mulElementWise            - calculates the element-wise ("Hadarmard") product between two matrices/vectors
    _la_cross                     - calculates the cross product between two 3-element vectors
    
    ---- factorization / decomposition ----
    _la_LU                        - calculates the LU decomposition of a matrix
    _la_QR                        - calculates the QR decomposition of a matrix
    _la_SVD                       - calculates the singular value decomposition (SVD) of a matrix
    _la_cholesky                  - calculate the cholesky decomposition of a symmetric, positive definite matrix ( A --> L * Lᵀ or A --> U * Uᵀ )
    
    ---- eigenvalues / eigenvectors ----
    _la_eigen                     - computes for an N-by-N real matrix A, the eigenvalues and the left and/or right eigenvectors.
    
    ---- solve linear equation systems ----
    _la_solve                     - computes the solution to a system of linear equations A * X = B
    
    ---- least squares solving ----
    _la_lstsq                     - solves overdetermined or underdetermined [weighted] linear system
    
    ---- regression ----
    _la_regression                - calculates an n-dimensional linear or non-linear regression
    
    ---- adjustment ----
    _la_adjustment                - performs a least-squares adjustment calculation for a system of different [weighted] non-linear equations
    _la_adjustment_l1             - performs a adjustment calculation to L1 norm for a system of different [weighted] non-linear equations
    _la_adjustment_addObservation - adds an observation to the adjustment system
    
    ---- additional helper functions ----
    _la_adj_showResult            - formats the results of _la_adjustment more clearly and display them in a window
    Alles anzeigen

    Dokumentation
    Die Dokumentation zu den einzelnen Funktionen ist direkt im Quellcode enthalten. Jede Funktion ist mit einer Beschreibung versehen, die ihre Parameter und Rückgabewerte erklärt. In den meisten Fällen ist hier auch ein kurzes Beispiel mit hinterlegt. Zudem findest du detaillierte Erklärungen in den Beispieldateien.


    ToDo

    • Bestimmte Funktionen (z.b. _la_add(), _la_mul(), _la_solve(), _la_inverse() ...) sind derzeit für den allgemeinen Fall implementiert. Diese profitieren jedoch entsprechend, wenn die spezifischen Funktionen für spezielle Matrixgeometrien (symmetrische Matrizen, Dreiecksmatrizen, Bandmatrizen, ...) jeweils verwendet würden. Die hierfür notwendigen Grundfunktionen sind bereits in der BLAS.au3 und LAPACK.au3 implementiert.
  • erledigt: Umkreis von 50 oder 100 Meter auf einer Karte

    • AspirinJunkie
    • 16. September 2024 um 06:18
    Zitat von Alina

    Wenn ich danach einen zweiten Standorte setze, sollen beide Kreise zu sehen kann. Das ganze mit bis zu 5 Standorte.

    Du willst nicht zufällig eine (überbestimmte) Triangulation machen - oder?

  • Assemblerfunktion zum Aufsummieren direkt in AutoIt

    • AspirinJunkie
    • 15. September 2024 um 11:54
    Zitat von Andy

    Problem dabei ist, du musst die DLL disassemblen um den Einsprungpunkt in die einzelnen Funktionen zu finden....

    Die Info ist ja in der shared lib enthalten.
    Wenn ich mir mit gcc eine shared lib (.so-Datei) erstelle, dann kann ich mir mit nm, readelf, oder objdump die offsets für die jeweiligen Funktionen auslesen lassen. Für mich wäre eher das Problem die Länge des Codeabschnittes zu ermitteln (einfach nur bis zum nächsten ret-opcode könnte sehr gefährlich werden...)

    Edit: Auch der Umweg über Assembler führte leider nicht zum gewünschten Ergebnis (Binary ist am Ende wieder das was wir nicht haben wollen):

    Code
    ; mit gcc den "guten" Assemblercode erzeugen:
    gcc -m64 -O3 -mabi=ms -S -c test.c -o test.s
    
    ; assemblieren (in binary überführen)
    as -o test.o test.s
    
    ; die eigentliche Funktion extrahieren
    objcopy -O binary -j .text test.o final.bin
  • Assemblerfunktion zum Aufsummieren direkt in AutoIt

    • AspirinJunkie
    • 15. September 2024 um 11:32

    Also wenn ich mal auf einem lokalen gcc folgendes ausführe:

    Code
    gcc -m64 -O3 -mabi=ms -Wl,--oformat=binary -c test.c -o binary.bin

    enthält die binary.bin entgegen der Aussage dort immer noch Daten im ELF-Format. Auch der darin enthaltene Binary-Code entspricht nicht dem gewünschten Code sondern dem problematischen.

    Wenn ich hingegen die manuelle Kaskade durchlaufe:

    Code
    gcc -m64 -O3 -mabi=ms -c test.c -o test.o
    objcopy --only-section=.text --output-target binary test.o binary.bin

    erhalte ich wieder unser vorheriges problematisches Ergebnis mit den unaufgelösten Relokationen. (per objdump --disassemble test.o schön zu sehen)

    Vielleicht versuche ich es mal mit der Dll-Variante und versuche die relevanten Binaries dort anschließend herauszulösen (oder ich versuche diese Memcall-Methode).

  • Assemblerfunktion zum Aufsummieren direkt in AutoIt

    • AspirinJunkie
    • 14. September 2024 um 15:48

    Hui, das sind ja schonmal starke Hinweise wo man suchen muss.
    So wie ich das Problem verstehe haben wir das Problem, dass wenn man sich das binary auch zurückgeben lässt, der gcc für die Konstanten Relokationen erstellt.
    Sprich: Wo der Wert 5.8 mal stehen wird ist beim Kompilieren noch nicht klar. Erst der Linker muss das, wenn alle Codeteile vorliegen, entsprechend auflösen.
    Nun haben wir jedoch das Problem, dass bei compiler explorer gar kein Linker zum Einsatz kommt.
    Die Relokationen bleiben also bestehen.

    Es gibt zwar flags mit denen sich bestimmte Relokationen vermeiden lassen.
    Die haben hier aber bei mir nicht zum Erfolg geführt.
    Jetzt bin ich bisschen ratlos zugegeben.
    Die Alternative wäre ja wirklich kompilieren + linken.
    Schade - compiler explorer mit der simplen API wäre schon schick gewesen.

  • Assemblerfunktion zum Aufsummieren direkt in AutoIt

    • AspirinJunkie
    • 14. September 2024 um 08:38
    Zitat von Andy

    Nicht nur ziemlich rund...das ist schon fast perfekt.

    Hm nein leider noch nicht.
    Aktuell habe ich ein Problem bei der Behandlung von Gleitkommakonstanten und damit allen Berechnungen die mit denen gemacht werden (z.b. das Reziproke bilden).
    Hier mal am Beispiel:

    AutoIt
    #AutoIt3Wrapper_UseX64=y
    #include "JIT.au3"
    
    Global $sSourceCode = _	; hint: write CALLCONV in front of every function!
    'CALLCONV double test() {             ' & @LF & _
    '    return 1.0;                      ' & @LF & _
    '}                                    ' & @LF & _
    'CALLCONV double test2(double test) { ' & @LF & _
    '    return test;                     ' & @LF & _
    '}'
    
    
    ; get compiled code as binary struct
    Global $mCode = _jit_codeTostruct($oHTTP, $mCEServer, $sSourceCode)
    Global $mFuncOffsets = $mCode.Funcs ; offsets for the included functions
    
    ; call function test
    Global $aDll = DllCallAddress("double", $mCode.ptr + $mFuncOffsets["test"], "DOUBLE", 1.0)
    ConsoleWrite("test: " & $aDll[0] & @CRLF)
    
    ; call function test
    Global $aDll = DllCallAddress("double", $mCode.ptr + $mFuncOffsets["test2"], "DOUBLE", 1.0)
    ConsoleWrite("test2: " & $aDll[0] & @CRLF)
    Alles anzeigen

    Meine Vermutung ist, dass ich den gcc unter Linux anspreche und evtl. hier noch Unterschiede in der Behandlung von Gleitkommazahlen zwischen Linux und Windows existieren.
    Darüber hinaus klappt das Beispiel hier auch nicht mit der 32-Bit-Variante - warum auch immer.
    Ich wollte daher mal einen Windows-basierten Compiler stattdessen verwenden - mingw gcc oder msvc - aber die bekam ich mit der API hier bislang nicht zum laufen - immer kein Response.
    Also spiele ich gerade mit den gcc-Parametern -mabi=ms -mrtd herum um die CALLCONV-Geschichte zu umgehen.

  • Assemblerfunktion zum Aufsummieren direkt in AutoIt

    • AspirinJunkie
    • 12. September 2024 um 08:46

    Na das bringt mich schonmal ein großes Stück weiter.
    Versuchen wir doch mal das ganze etwas zu strukturieren und leichter zugänglich zu machen.
    Hierzu habe ich das mal als rudimentäre UDF verpackt - nennen wir die Datei einfach mal "JIT.au3":

    AutoIt
    #include "JSON.au3" ; https://github.com/Sylvan86/autoit-json-udf
    
    ; global http request object
    Global $oHTTP = ObjCreate("winhttp.winhttprequest.5.1")
    
    ; Basic settings, which compiler-explorer server should be used and with which settings.
    ; could be overwritten by user
    Global $mCEServer[]
    $mCEServer.domain     = "https://godbolt.org"   ; domain to a compiler-explorer instance (https://github.com/compiler-explorer/compiler-explorer)
    $mCEServer.langID     = "c"			            ; derive with _jit_getLanguages()
    $mCEServer.compilerID = "cg142"                 ; derive with _jit_getCompilers()
    
    ; takes a code as a string, compiles it and prepares it so that it can be called via DllCallAdress
    Func _jit_codeTostruct(ByRef $oHTTP, ByRef $mCEServer, $sCode, $b64 = (@AutoItX64 = 1) , $sCompilerFlags = "-O3")
    
    	If $b64 Then
    		$sCode = '#define CALLCONV __attribute__((ms_abi))' & @LF & $sCode
    		$sCompilerFlags &= " -m64"
    	Else
    		$sCode = '#define CALLCONV __attribute__((stdcall))' & @LF & $sCode
    		$sCompilerFlags &= " -m32"
    	EndIf
    
    	Local $mCompiled = _jit_compileCode($oHTTP, $mCEServer, $sCode, $sCompilerFlags)
    	If $mCompiled.Code = "<Compilation failed>" Then Return SetError(1, 0, Null)
    
    	$mCompiled.struct = __jit_BinaryToStruct($mCompiled.Binary)
    	$mCompiled.ptr = DllStructGetPtr($mCompiled.struct)
    
    	Return $mCompiled
    EndFunc
    
    ; compiles a code via a compiler explorer server and returns the asm-code and the binary
    Func _jit_compileCode(ByRef $oHTTP, ByRef $mCEServer, $sCode, $sCompilerFlags = Default)
    
    	Local $mPostData[]
    	$mPostData.source = $sCode
    	$mPostData.lang   = $mCEServer.langID
    
    	Local $mOptions[]
    	If IsString($sCompilerFlags) Then $mOptions.userArguments = $sCompilerFlags
    
    	Local $mFilters[]
    	$mFilters.binary       = True ; with this also opcodes are returned
    	$mFilters.binaryObject = True
    
    	$mOptions.filters = $mFilters
    	$mPostData.options = $mOptions
    
    	; do the api compile request
    	Local $sResponse
        With $oHTTP
            .Open("POST", $mCEServer.domain & "/api/compiler/" & $mCEServer.compilerID & "/compile", False)
    		.SetRequestHeader("Accept", "application/json") ; so that JSON comes back as return type
    		.setRequestHeader("Content-type", "application/json")
            .Send(_JSON_Generate($mPostData))
            $sResponse = .ResponseText
        EndWith
    
    	; extract the asm code and the binary opcodes
    	Local $sASMCode = "", $sBinary = "", $mLine, $sOpCode, $mFuncs[], $iOffset = 0
    	For $mLine In _JSON_Parse($sResponse).asm
    		If Not  MapExists($mLine, "text") Then ContinueLoop
    		If $mLine.text = "main:" Then ExitLoop
    
    		If StringRegExp($mLine.text, '^\w+:') Then
    			$mFuncs[StringLeft($mLine.text, StringInStr($mLine.text, ":", 1) - 1)] = $iOffset
    		EndIf
    
    		$sASMCode &= $mLine["text"] & @CRLF
    
    		If MapExists($mLine, "opcodes") Then
    			For $sOpCode In $mLine["opcodes"]
    				$sBinary &= $sOpCode
    				$iOffset += 1
    			Next
    		EndIf
    	Next
    
    	Local $mRet[]
    	$mRet.Code = $sASMCode
    	$mRet.Binary = Binary("0x" & $sBinary)
    	$mRet.BinaryString = $sBinary
    	$mRet.Funcs = $mFuncs
    
    	Return $mRet
    EndFunc
    
    ;~ For $mLang in _jit_getLanguages($oHTTP, $mCEServer)
    ;~ 	ConsoleWrite(StringFormat("id: %s\nname: %s\n\n", $mLang["id"], $mLang["name"]))
    ;~ Next
    ; return a list of supported languages of a compiler explorer server
    Func _jit_getLanguages(ByRef $oHTTP, ByRef $mOptions)
    	Local $sResponse
    
        With $oHTTP
            .Open("GET", $mCEServer.domain & "/api/languages", False)
    		.SetRequestHeader("Accept", "application/json") ; so that JSON comes back as return type
            .Send()
            $sResponse = .ResponseText
        EndWith
    	Return _JSON_Parse($sResponse)
    EndFunc
    
    ;~ For $mCompiler in _jit_getCompilers($oHTTP, $mCEServer, "c", "amd64")
    ;~ 	ConsoleWrite(StringFormat("id: %s\nname: %s\ninstruction set: %s\n\n", $mCompiler["id"], $mCompiler["name"], $mCompiler["instructionSet"]))
    ;~ Next
    ; return a list of supported compilers of a compiler explorer server
    Func _jit_getCompilers(ByRef $oHTTP, ByRef $mOptions, $sLang = Default, $sInstructionSet = Default)
    	Local $sResponse
    
        With $oHTTP
            .Open("GET", $mCEServer.domain & "/api/compilers" & (IsKeyword($sInstructionSet) = 1 ? "" : "/" & $sLang), False)
    		.SetRequestHeader("Accept", "application/json") ; so that JSON comes back as return type
            .Send()
            $sResponse = .ResponseText
        EndWith
    
    	Local $aCompilers = _JSON_Parse($sResponse)
    
    	; delete all compilers that have the wrong instruction set
    	Local $iNew = 0, $mCompiler
    	For $i = 0 To UBound($aCompilers) - 1
    		$mCompiler = $aCompilers[$i]
    
    		; filter instruction set
    		If (Not IsKeyword($sInstructionSet) = 1) And $mCompiler["instructionSet"] <> $sInstructionSet Then ContinueLoop
    
    		; keep entry
    		$aCompilers[$iNew] = $aCompilers[$i]
    		$iNew += 1
    	Next
    	Redim $aCompilers[$iNew]
    
    	Return $aCompilers
    EndFunc
    
    ;~ MsgBox(0, "push", _jit_describeOpcode($oHTTP, $mCEServer, "push").tooltip)
    ; describe an assembler opcode
    Func _jit_describeOpcode(ByRef $oHTTP, ByRef $mOptions, $sOpCode, $sInstructionSet = "amd64")
    	Local $sResponse
        With $oHTTP
            .Open("GET", StringFormat("%s/api/asm/%s/%s", $mCEServer.domain, $sInstructionSet, $sOpCode), False)
    		.SetRequestHeader("Accept", "application/json") ; so that JSON comes back as return type
            .Send()
            $sResponse = .ResponseText
        EndWith
    	Return _JSON_Parse($sResponse)
    EndFunc
    
    ; converts a binary into a DllCall structure to be able to call it with DllCallAddress
    Func __jit_BinaryToStruct($sBinary) ; without 0x!
    	; You are responsible for releasing the memory!
        ; If you no longer need the structure, use VirtualFree!
    
    	; binary as string or already as binary
    	Local $bBin = IsString($sBinary) ? Binary($sBinary) : $sBinary
    	Local $iNCode = BinaryLen($bBin)
    
    	; align at 64 bit
    	Local $aStructMem = DllCall("kernel32.dll", "ptr", "VirtualAlloc", "ptr", 0, "ulong_ptr", DllStructGetSize(DllStructCreate("byte[" & $iNCode & "]")), "dword", 4096, "dword", 64)
    	Local $tStruct = DllStructCreate("byte[" & $iNCode & "]", Ptr($aStructMem[0]))
    	DllStructSetData($tStruct, 1, $bBin)
    
    	Return $tStruct
    EndFunc
    Alles anzeigen


    Wenn wir das haben können wir das ganze folgendermaßen verwenden um Code zu kompilieren und anschließend auszuführen (auch der Zugriff auf mehrere Funktion wird hier gezeigt):

    AutoIt
    #AutoIt3Wrapper_UseX64=y
    #include "JIT.au3"
    
    Global $sSourceCode = _	; hint: write CALLCONV in front of every function!
    'CALLCONV double sumArray(double *arr, int size) {      ' & @LF & _
    '    double sum = 0.0;                                  ' & @LF & _
    '    for (int i = 0; i < size; i++) {                   ' & @LF & _
    '        sum += arr[i];                                 ' & @LF & _
    '    }                                                  ' & @LF & _
    '    return sum;                                        ' & @LF & _
    '}                                                      ' & @LF & _
    'CALLCONV double squaresumArray(double *arr, int size) {' & @LF & _
    '    double sum = 0.0;                                  ' & @LF & _
    '    for (int i = 0; i < size; i++) {                   ' & @LF & _
    '        sum += arr[i] * arr[i];                        ' & @LF & _
    '    }                                                  ' & @LF & _
    '    return sum;                                        ' & @LF & _
    '}'
    
    ; double data array
    Global $iN = 100
    Global $tData = DllStructCreate("DOUBLE [" & $iN & "]")
    For $i = 1 To $iN
    	DllStructSetData($tData, 1, Number($i & "." & $i), $i)
    Next
    
    ; get compiled code as binary struct
    Global $mCode = _jit_codeTostruct($oHTTP, $mCEServer, $sSourceCode)
    Global $mFuncOffsets = $mCode.Funcs ; offsets for the included functions
    
    ; call function sumArray
    Global $aDll = DllCallAddress("double", $mCode.ptr + $mFuncOffsets["sumArray"], "PTR", DllStructGetPtr($tData), "INT", $iN)
    ConsoleWrite("sum: " & $aDll[0] & @CRLF)
    
    ; call function squaresumArray
    Global $aDll = DllCallAddress("double", $mCode.ptr + $mFuncOffsets["squaresumArray"], "PTR", DllStructGetPtr($tData), "INT", $iN)
    ConsoleWrite("square sum: " & $aDll[0] & @CRLF)
    Alles anzeigen


    Natürlich wollen wir nicht jedesmal neu kompilieren, also macht es Sinn sich einmalig den Binary-String z.b. so zu erzeugen:

    AutoIt
    #AutoIt3Wrapper_UseX64=y
    #include "JIT.au3"
    
    $oHTTP.SetProxy(2, "localhost:3128")
    
    Global $sSourceCode = _	; hint: write CALLCONV in front of every function!
    'CALLCONV double sumArray(double *arr, int size) {' & @LF & _
    '    double sum = 0.0;                            ' & @LF & _
    '    for (int i = 0; i < size; i++) {             ' & @LF & _
    '        sum += arr[i];                           ' & @LF & _
    '    }                                            ' & @LF & _
    '    return sum;                                  ' & @LF & _
    '}'
    
    Global $mCode = _jit_codeTostruct($oHTTP, $mCEServer, $sSourceCode)
    
    ConsoleWrite("0x" & $mCode.BinaryString & @CRlF)
    ClipPut("0x" & $mCode.BinaryString)
    Alles anzeigen


    Und dann fortan folgendermaßen zu verwenden:

    AutoIt
    #AutoIt3Wrapper_UseX64=y
    #include "JIT.au3"
    
    Global $sBinary = @AutoItX64 _
                      ? "0x85d27e4c83fa01744c4189d04889c8660fefc041d1e849c1e0044901c80f1f00f20f58004883c010f20f5840f84939c075ee89d083e0fe83e201740c4898f20f5804c1c30f1f4000c30f1f8000000000660fefc0c331c0660fefc0ebdf" _
    				  : "0x538b4c240c8b5c240885c97e3383f901743489cad9ee89d8d1eac1e20401da90dc0083c010dc40f839c275f489c883e0fe83e1017403dc04c35bc208008d7600d9ee5bc2080031c0d9eeebea"
    
    ; prepare code for execution with DllCallAddress
    Global $tStruct = __jit_BinaryToStruct($sBinary)
    Global $pCodeStart = DllStructGetPtr($tStruct)
    
    ; double data array
    Global $iN = 100
    Global $tData = DllStructCreate("DOUBLE [" & $iN & "]")
    For $i = 1 To $iN
    	DllStructSetData($tData, 1, Number($i & "." & $i), $i)
    Next
    
    ; run code
    Global $aDll = DllCallAddress("double", DllStructGetPtr($tStruct), "PTR", DllStructGetPtr($tData), "INT", $iN)
    ConsoleWrite("sum: " & $aDll[0] & @CRLF)
    Alles anzeigen


    Für mich sieht das schon ziemlich rund aus - was meint ihr dazu?


    Kanashius Vielen vielen Dank schon mal für deine Erläuterungen.
    Das werde ich mir mal in Ruhe zu Gemüte führen.
    Wird aber sicherlich ein bisschen dauern, da ich ja nun durch die Geschichte hier mehrere Hochzeiten habe auf denen ich tanzen möchte.

  • Assemblerfunktion zum Aufsummieren direkt in AutoIt

    • AspirinJunkie
    • 11. September 2024 um 08:56

    Ja aber dort muss man den kompletten Compiler mitbringen.
    Bei unserem Ansatz hier braucht es nur Internet und ein kleines Skript.

  • Assemblerfunktion zum Aufsummieren direkt in AutoIt

    • AspirinJunkie
    • 11. September 2024 um 06:15
    Zitat von Andy

    "Es" funktioniert in allen Fällen in denen der Compiler in der Lage ist, ohne einzubindende Module (ASM-)Code zu erzeugen. Ich bin mir sogar sicher dass funktionsfähiger Code entstehen würde, wenn du bspw. die SQRT()-Funktion aus der Bibliothek herauslösen würdest und in den Quellcode einbindest.

    Ja da bin ich mir auch sicher. Allerdings hab ich mir mal den Quellcode für sqrt() in den Standardbibliotheken angesehen - das ist richtig viel Code, welcher auch wieder etliche Nebenabhängigkeiten mitbringt.
    Allerdings war die sqrt-Geschichte ein schlechtes Beispiel. Dafür gibt es ja bereits eigene CPU-Befehle und als ich diese per intrinsics aufgerufen habe (Assemblerbefehl "sqrtsd"), konnte ich auch mit dem godbolt-Code hier eine Funktion mit Wurzel schreiben die funktionierte.

    Mein Problem liegt derzeit noch an einer anderen Stelle: Ich schaffe es nicht Pointer zu übergeben um ein Array abzuarbeiten.
    Folgendes Beispiel läuft bislang nicht bei mir:

    AutoIt
    Global $sSourceCode = _
    'double sumArray(double *arr, int size) {' & @LF & _
    '    double sum = 0.0;' & @LF & _
    '    for (int i = 0; i < size; i++) {' & @LF & _
    '        sum += arr[i];' & @LF & _
    '    }' & @LF & _
    '    return sum;' & @LF & _
    '}'
    
    ; double data array
    Global $tData = DllStructCreate("DOUBLE [5]")
    For $i = 1 To 5
    	DllStructSetData($tData, 1, Number($i & "." & $i), $i)
    Next
    
    ; get compiled code as binary struct
    Global $tCode = _CodeToCallStruct($sSourceCode)
    
    ; run code
    Global $aDll = DllCallAddress("double:cdecl", DllStructGetPtr($tCode), "PTR", DllStructGetPtr($tData), "INT", 5)
    ConsoleWrite(@error & @TAB & @extended & @CRLF)
    _ArrayDisplay($aDll)
    Alles anzeigen
    Zitat von Andy

    Aber wo ist das Problem, aus bspw. C(++) - Bibliotheken die einzelnen Funktionen zu assemblieren und später an dein Programm "anzuhängen".

    Ja eben wo ist das Problem?
    Braucht man dafür einen Fluxkompensator?
    Die sqrt-Funktion z.B. mal eben rauszulösen ist nicht ohne, da sie ziemlich aufwendig gestaltet ist und selbst wiederrum haufenweise weitere Abhängigkeiten mitbringt.
    Ich denke im ersten Schritte würde es ja reichen erst einmal eigene unabhängige Funktionen lauffähig zu bekommen.
    Aber da komme ich ja schon wie gesagt (siehe Pointer-Geschichte oben) nicht weiter.

    Zitat von Andy

    dieser Code hat aber ein Problem. Wenn assembliert, startet der code bei add() und wird beim nächsten ret beendet. main() wird NIE aufgerufen.

    Die Funktion _ce_compileCode() gibt eine Map zurück. Dort findet sich auch der Eintrag ["Funcs"].
    Das sind die benamten Funktionen im Assemblercode mit ihren Start-Offsets als Value.
    Man kann also auch mehrere Funktionen kompilieren und dann über ihre Offsets in DllCallAddress einzeln ansprechen.
    Bei Verweisen im Code zwischen den Funktionen müsste man wahrscheinlich dann aber noch die Call-Aufrufe entsprechend anpassen, da die Sprungadresse beim Call noch nicht feststeht(?).
    Nur die Main-Funktion lasse ich explizit aus dem Ergebnis verschwinden, da ich diese für meinen Anwendungsfall ja nicht brauche.

    Zitat von UEZ

    Man kann auch die DLLs in das Skript integrieren (Base64) und per MemCall() aufrufen, somit würde das Weitergeben der DLL entfallen.

    Klingt mir sehr zielführend und effizient.
    Ich dachte wir hätten uns aber auf den komplizierten, instabilen und umständlichen Weg geeinigt?... ;)

    Ne das wäre sicherlich tatsächlich ein sehr gangbarer Weg, welchen ich auch mal probieren werde (und evtl. als finalen Ansatz für mein Projekt verwende).
    Aktuell ist das mit dem Binary-Code aber nicht lebensnotwendig, so dass ich das gerade als Anlass für Spielereien sehe.
    Ein in AutoIt eingebauter C-Compiler wäre schon fein wenn das als "Abfallprodukt" hinten raus fällt.

    Aber zu der Rust-Dll-Geschichte: Eh ich erst einmal selbst wieder auf Recherchejagd gehe: Hast du da vielleicht gleich online Dokus wie man mit Rust entsprechende Dlls erstellt und evtl. sogar in AutoIt per MemCall einbindet?

  • Assemblerfunktion zum Aufsummieren direkt in AutoIt

    • AspirinJunkie
    • 3. September 2024 um 07:11

    Zugegeben - bedeutend schlauer bin ich nicht noch nicht wirklich.

    Zitat von Andy

    ; ist das die Größe des 1. Parameters in Bytes?
    $a=4
    ;nein, das ist der Parameter, der Integer der quadriert werden soll

    Ok mich hatte an der Nummer verwundert, dass man die Werte bereits beim Erstellen des Codes einträgt. Wenn ich das aber richtig verstehe, geht es darum, dass man die Debugging-Funktionalität damit nutzen kann?

    Traumziel wäre ein JIT-Compiler für derartige Sachen in AutoIt.
    Aktuell stehe ich aber noch vor dem Problem, dass du ein Opcode vom Kompilat des gcc-Compilers ausgetauscht hast und ich (mangels ASM-Kenntnisse) nicht weiß warum das nötig ist.
    Momentan sieht mein Grundgerüst auf Grundlage deiner Skripte folgendermaßen aus:

    C
    #AutoIt3Wrapper_UseX64=y
    
    #include "JSON.au3" ; https://github.com/Sylvan86/autoit-json-udf
    #include "Array.au3"
    
    Global $sSourceCode = _
    'double square(double num) {' & @LF & _
    '    return num * num;' & @LF & _
    '}'
    
    ; klappt noch nicht (vermutlich weil hier der sqrt-Code nicht mit gelinkt ist)
    ;~ Global $sSourceCode = _
    ;~ '#include <math.h>' & @LF & _
    ;~ 'double squareroot(double num) {' & @LF & _
    ;~ '    return sqrt(num);' & @LF & _
    ;~ '}'
    
    
    ; get compiled code as binary struct
    Global $tCode = _CodeToCallStruct($sSourceCode)
    
    ; run code
    Global $aDll = DllCallAddress("double:cdecl", DllStructGetPtr($tCode), "double", 12)
    _ArrayDisplay($aDll)
    
    
    
    
    ; takes a code as a string, compiles it and prepares it so that it can be called via DllCallAdress
    Func _CodeToCallStruct($sCode, Const $sCompilerID = "cg142", Const $sLangId = "c", Const $sProxy = Default, Const $sCEServerDomain = "https://godbolt.org")
    	Local $oHTTP = ObjCreate("winhttp.winhttprequest.5.1")
    
    	; set proxy if neccesary
    	If IsKeyword($sProxy) <> 1 Then $oHTTP.SetProxy(2, $sProxy)
    
    	Local $mCompiled = _ce_compileCode($oHTTP, $sCode, $sCompilerID, $sLangID, Default, $sCEServerDomain)
    
    	; adapt the code by exchanging individual opcodes
    	Local $bCode = Binary("0x" & StringRegExpReplace($mCompiled.BinaryString, '(?i)7D|[[:xdigit:]]{2}(*SKIP)(?!)', "4D"))
    	Local $iNCode = BinaryLen($bCode)
    
    	; convert to a 64Bit aligned structure
    	Local $aStructMem = DllCall("kernel32.dll", "ptr", "VirtualAlloc", "ptr", 0, "ulong_ptr", DllStructGetSize(DllStructCreate("byte[" & $iNCode & "]")), "dword", 4096, "dword", 64)
    	Local $tCodeBuffer = DllStructCreate("byte[" & $iNCode & "]", Ptr($aStructMem[0]))
    
    	DllStructSetData($tCodeBuffer, 1, $bCode)
    
    	Return $tCodeBuffer
    EndFunc
    
    
    ; compiles a code via a compiler explorer server and returns the asm-code and the binary
    Func _ce_compileCode($oHTTP, $sCode, $sCompilerID, $sLangID = "c", $sCompilerFlags = Default, Const $sCEServerDomain = "https://godbolt.org")
    
    	Local $mPostData[]
    	$mPostData.source = $sCode
    	$mPostData.lang   = $sLangID
    
    	Local $mOptions[]
    	If IsString($sCompilerFlags) Then $mOptions.userArguments = $sCompilerFlags
    
    	Local $mFilters[]
    	$mFilters.binary       = True ; with this also opcodes are returned
    	$mFilters.binaryObject = True
    
    	$mOptions.filters = $mFilters
    	$mPostData.options = $mOptions
    
    	; do the api compile request
    	Local $sResponse
        With $oHTTP
            .Open("POST", $sCEServerDomain & "/api/compiler/" & $sCompilerID & "/compile", False)
    		.SetRequestHeader("Accept", "application/json") ; so that JSON comes back as return type
    		.setRequestHeader("Content-type", "application/json")
            .Send(_JSON_Generate($mPostData))
            $sResponse = .ResponseText
        EndWith
    
    	; extract the asm code and the binary opcodes
    	Local $sASMCode = "", $sBinary = "", $mLine, $sOpCode, $mFuncs[], $iOffset = 0
    	For $mLine In _JSON_Parse($sResponse).asm
    		If Not  MapExists($mLine, "text") Then ContinueLoop
    		If $mLine.text = "main:" Then ExitLoop
    
    		If StringRegExp($mLine.text, '^\w+:') Then
    			$mFuncs[StringLeft($mLine.text, StringInStr($mLine.text, ":", 1))] = $iOffset
    		EndIf
    
    		$sASMCode &= $mLine["text"] & @CRLF
    
    		If MapExists($mLine, "opcodes") Then
    			For $sOpCode In $mLine["opcodes"]
    				$sBinary &= $sOpCode
    				$iOffset += 1
    			Next
    		EndIf
    	Next
    
    	Local $mRet[]
    	$mRet.Code = $sASMCode
    	$mRet.Binary = Binary("0x" & $sBinary)
    	$mRet.BinaryString = $sBinary
    	$mRet.Funcs = $mFuncs
    
    	Return $mRet
    EndFunc
    Alles anzeigen

    Eventuell kannst du Licht ins Dunkel bringen in welchen Fällen das versagt und in welchen es klappt und was dazu immer notwendig ist.

  • _ArraySum + Variante mit minimalen Rundungsfehlern

    • AspirinJunkie
    • 2. September 2024 um 09:47

    Da es letztens Thema war, habe ich mal den Kahan-Algorithmus implementiert, welcher die binären Rundungsfehler bei der Summation von Gleitkommazahlen minimiert.
    Dazu gibt es auch eine normale _ArraySum()-Funktion, einfach weil eine solche bislang nicht mitgeliefert wird:

    AutoIt
    Global $aValues = [1, 1e100, 1, -1e100]
    
    $fSum = _ArraySum($aValues)
    ConsoleWrite(StringFormat("% 15s: %.20g\t(%d values)\n", "naive sum", $fSum, @extended))
    
    $fSum = _ArraySumPrecise($aValues)
    ConsoleWrite(StringFormat("% 15s: %.20g\t(%d values)\n\n", "Neumaier sum", $fSum, @extended))
    
    
    ; #FUNCTION# ====================================================================================================================
    ; Name ..........: _ArraySum()
    ; Description ...: calculates the sum over a 1D array, a map or a column of a 2D array
    ; Syntax ........: _ArraySum($aValues, [$iFrom = 0, [$iTo = Default, [$iCol = 0]]])
    ; Parameters ....: aValues - [Array] 1D/2D array or map
    ;                  iFrom   - [Int] (Default: 0)
    ;                          ↳ start index (0-based)
    ;                  iTo     - [Int] (Default: Default)
    ;                          ↳ end index (0-based)
    ;                  iCol    - [Int] (Default: 0)
    ;                          ↳ 2D array case: column over which the sum is to be calculated
    ; Return value ..: Success: SetError(2, UBound($aValues, 0), Null)
    ;                  Failure: Null and set @error to:
    ;                           | 1: invalid data type for $aValues
    ;                           | 2: $aValues is not a 1D or 2D array (@extended: number of dimension of $aValues)
    ;                           | 3: invalid value for $iFrom (@extended: number of elements in the array[-column])
    ;                           | 4: invalid value for $iTo (@extended: number of elements in the array[-column])
    ;                           | 5: invalid value for $iCol (@extended: number of columns in the array)
    ; Author ........: AspirinJunkie
    ; Modified.......: 2024-09-02
    ; Example .......: Yes
    ;                  $aValues = [1, 2, 3, 4, 5]
    ;                  $fSum = _ArraySum($aValues)
    ;                  ConsoleWrite(StringFormat("% 5s: %.20g\t(%d values)\n", "sum", $fSum, @extended))
    ; ===============================================================================================================================
    Func _ArraySum($aValues, Const $iFrom = 0, $iTo = Default, Const $iCol = 0)
    	Local $i
    	Local $fSum = 0.0
    
    	; convert map values into 1D-Array
    	If IsMap($aValues) Then
    		Local $aTmp[UBound($aValues)]
    		$i = 0
    		For $fVal In $aValues
    			$aTmp[$i] = $fVal
    			$i += 1
    		Next
    		$aValues = $aTmp
    	EndIf
    
    	; retrieve main shape values
    	Local $iD = UBound($aValues, 0), _
    	      $iM = UBound($aValues, 1)
    
    	If IsKeyword($iTo) = 1 Then $iTo = $iM - 1
    
    	; check parameters for correctness
    	If Not IsArray($aValues)        Then Return SetError(1, 0,   Null)
    	If $iFrom < 0 Or $iFrom >= $iM  Then Return SetError(3, $iM, Null)
    	If $iTo >= $iM Or $iFrom > $iTo Then Return SetError(4, $iM, Null)
    
    	If $iD = 1 Then ; 1D-Array
    
    		For $i = $iFrom To $iTo
    			$fSum += $aValues[$i]
    		Next
    
    	ElseIf $iD = 2 Then ; 2D-Array
    		Local $iN = UBound($aValues, 2)
    
    		If $iN >= $iCol Or $iCol < 0 Then Return SetError(5, $iN, Null)
    
    		For $i = $iFrom To $iTo
    			$fSum += $aValues[$i][$iCol]
    		Next
    
    	Else
    		Return SetError(2, UBound($aValues, 0), Null)
    
    	EndIf
    
    	Return SetExtended($iTo - $iFrom + 1, $fSum)
    EndFunc
    
    ; #FUNCTION# ====================================================================================================================
    ; Name ..........: _ArraySumPrecise()
    ; Description ...: calculates the sum over a 1D array, a map or a column of a 2D array
    ;                  and minimises the binary rounding error that occurs
    ; Syntax ........: _ArraySumPrecise($aValues, [$iFrom = 0, [$iTo = Default, [$iCol = 0]]])
    ; Parameters ....: aValues - [Array] 1D/2D array or map
    ;                  iFrom   - [Int] (Default: 0)
    ;                          ↳ start index (0-based)
    ;                  iTo     - [Int] (Default: Default)
    ;                          ↳ end index (0-based)
    ;                  iCol    - [Int] (Default: 0)
    ;                          ↳ 2D array case: column over which the sum is to be calculated
    ; Return value ..: Success: SetError(2, UBound($aValues, 0), Null)
    ;                  Failure: Null and set @error to:
    ;                           | 1: invalid data type for $aValues
    ;                           | 2: $aValues is not a 1D or 2D array (@extended: number of dimension of $aValues)
    ;                           | 3: invalid value for $iFrom (@extended: number of elements in the array[-column])
    ;                           | 4: invalid value for $iTo (@extended: number of elements in the array[-column])
    ;                           | 5: invalid value for $iCol (@extended: number of columns in the array)
    ; Author ........: AspirinJunkie
    ; Modified.......: 2024-09-02
    ; Remarks .......: The function implements Neumaier's "improved Kahan-Babuška algorithm". Basically the 1:1 translation of the pseudo code on Wikipedia.
    ; Link ..........: https://en.wikipedia.org/wiki/Kahan_summation_algorithm#Further_enhancements
    ; Example .......: Yes
    ;                  $aValues = [1, 2, 3, 4, 5]
    ;                  $fSum = _ArraySumPrecise($aValues)
    ;                  ConsoleWrite(StringFormat("% 5s: %.20g\t(%d values)\n", "sum", $fSum, @extended))
    ; ===============================================================================================================================
    Func _ArraySumPrecise($aValues, Const $iFrom = 0, $iTo = Default, Const $iCol = 0)
    	Local $i
    	Local $fSum = 0.0, $fC = 0.0, $fT
    
    	; convert map values into 1D-Array
    	If IsMap($aValues) Then
    		Local $aTmp[UBound($aValues)]
    		$i = 0
    		For $fVal In $aValues
    			$aTmp[$i] = $fVal
    			$i += 1
    		Next
    		$aValues = $aTmp
    	EndIf
    
    	; retrieve main shape values
    	Local $iD = UBound($aValues, 0), _
    	      $iM = UBound($aValues, 1)
    
    	If IsKeyword($iTo) = 1 Then $iTo = $iM - 1
    
    	; check parameters for correctness
    	If Not IsArray($aValues)        Then Return SetError(1, 0,   Null)
    	If $iFrom < 0 Or $iFrom >= $iM  Then Return SetError(3, $iM, Null)
    	If $iTo >= $iM Or $iFrom > $iTo Then Return SetError(4, $iM, Null)
    
    	If $iD = 1 Then ; 1D-Array
    
    		For $i = $iFrom To $iTo
    			$fT = $fSum + $aValues[$i]
    
    			$fC += Abs($fSum) >= Abs($aValues[$i]) _
    			       ? $fSum - $fT + $aValues[$i] _
    			       : $aValues[$i] - $fT + $fSum
    
    		   $fSum = $fT
    		Next
    
    	ElseIf $iD = 2 Then ; 2D-Array
    		Local $iN = UBound($aValues, 2)
    
    		If $iN >= $iCol Or $iCol < 0 Then Return SetError(5, $iN, Null)
    
    		For $i = $iFrom To $iTo
    			$fT = $fSum + $aValues[$i][$iCol]
    
    			$fC += Abs($fSum) >= Abs($aValues[$i][$iCol]) _
    			       ? $fSum - $fT + $aValues[$i][$iCol] _
    			       : $aValues[$i][$iCol] - $fT + $fSum
    
    			$fSum = $fT
    		Next
    
    	Else
    		Return SetError(2, UBound($aValues, 0), Null)
    
    	EndIf
    
    	Return SetExtended($iTo - $iFrom + 1, $fSum + $fC)
    EndFunc
    Alles anzeigen
  • Assemblerfunktion zum Aufsummieren direkt in AutoIt

    • AspirinJunkie
    • 1. September 2024 um 14:29
    Zitat von Andy

    Bin heute Abend wieder Online, dann versuchen wir das mal ohne Modifikationen am Code....bis denne

    Ok vielleicht hilft dir ja folgendes Skript ein bisschen:

    AutoIt
    ; API-Documentation: https://github.com/compiler-explorer/compiler-explorer/blob/main/docs/API.md
    
    #include "JSON.au3" ; https://github.com/Sylvan86/autoit-json-udf
    
    ; global http request object
    Global $oHTTP = ObjCreate("winhttp.winhttprequest.5.1")
    ;$oHTTP.SetProxy(2, "localhost:3128")
    
    ; Domain of the compiler explorer server
    Global Const $__g_CE_DOMAIN = "https://godbolt.org"
    
    ; choose language
    Global $sLangID = "c"
    Global $sCompilerID = "cg142"
    
    ; the C source-code:
    Global $sSourceCode = _
    'int square(int num) {' & @LF & _
    '    return num * num;' & @LF & _
    '}'
    
    ; compile
    Global $mCompilated = _ce_compileCode($sSourceCode, $sCompilerID, $sLangID)
    
    ; display results
    MsgBox(0, "ASM Code", $mCompilated.Code)
    MsgBox(0, "Binary", $mCompilated.Binary)
    
    ; compiles a code via a compiler explorer server and returns the asm-code and the binary
    Func _ce_compileCode($sCode, $sCompilerID, $sLangID = "c", $sCompilerFlags = Default)
    
    	Local $mPostData[]
    	$mPostData.source = $sCode
    	$mPostData.lang   = $sLangID
    
    	Local $mOptions[]
    	If IsString($sCompilerFlags) Then $mOptions.userArguments = $sCompilerFlags
    
    	Local $mFilters[]
    	$mFilters.binary       = True ; with this also opcodes are returned
    	$mFilters.binaryObject = True
    
    	$mOptions.filters = $mFilters
    	$mPostData.options = $mOptions
    
    	; do the api compile request
    	Local $sResponse
        With $oHTTP
            .Open("POST", $__g_CE_DOMAIN & "/api/compiler/" & $sCompilerID & "/compile", False)
    		.SetRequestHeader("Accept", "application/json") ; so that JSON comes back as return type
    		.setRequestHeader("Content-type", "application/json")
            .Send(_JSON_Generate($mPostData))
            $sResponse = .ResponseText
        EndWith
    
    	; extract the asm code and the binary opcodes
    	Local $sASMCode = "", $sBinary = "", $mLine, $sOpCode
    	For $mLine In _JSON_Parse($sResponse).asm
    		If Not  MapExists($mLine, "text") Then ContinueLoop
    		If $mLine["text"] = "main:" Then ExitLoop
    
    		$sASMCode &= $mLine["text"] & @CRLF
    
    		If MapExists($mLine, "opcodes") Then
    			For $sOpCode In $mLine["opcodes"]
    				$sBinary &= $sOpCode
    			Next
    		EndIf
    	Next
    
    	Local $mRet[]
    	$mRet.Code = $sASMCode
    	$mRet.Binary = Binary("0x" & $sBinary)
    
    	Return $mRet
    EndFunc
    
    ; describe an assembler opcode
    ;~ MsgBox(0, "push", _ce_describeOpcode("push").tooltip)
    Func _ce_describeOpcode($sOpCode, $sInstructionSet = "amd64")
    	Local $sResponse
    
        With $oHTTP
            .Open("GET", StringFormat("%s/api/asm/%s/%s", $__g_CE_DOMAIN, $sInstructionSet, $sOpCode), False)
    		.SetRequestHeader("Accept", "application/json") ; so that JSON comes back as return type
            .Send()
            $sResponse = .ResponseText
        EndWith
    
    	Return _JSON_Parse($sResponse)
    EndFunc
    
    ; return a list of supported languages of a compiler explorer server
    Func _ce_getLanguages($sLang = Default, $sInstructionSet = Default)
    	Local $sResponse
    
        With $oHTTP
            .Open("GET", $__g_CE_DOMAIN & "/api/languages", False)
    		.SetRequestHeader("Accept", "application/json") ; so that JSON comes back as return type
            .Send()
            $sResponse = .ResponseText
        EndWith
    
    	Return _JSON_Parse($sResponse)
    EndFunc
    
    ; return a list of supported compilers of a compiler explorer server
    Func _ce_getCompilers($sLang = Default, $sInstructionSet = Default)
    	Local $sResponse
    
        With $oHTTP
            .Open("GET", $__g_CE_DOMAIN & "/api/compilers" & (IsKeyword($sInstructionSet) = 1 ? "" : "/" & $sLang), False)
    		.SetRequestHeader("Accept", "application/json") ; so that JSON comes back as return type
            .Send()
            $sResponse = .ResponseText
        EndWith
    
    	Local $aCompilers = _JSON_Parse($sResponse)
    
    	; delete all compilers that have the wrong instruction set
    	Local $iNew = 0, $mCompiler
    	For $i = 0 To UBound($aCompilers) - 1
    		$mCompiler = $aCompilers[$i]
    
    		; filter instruction set
    		If (Not IsKeyword($sInstructionSet) = 1) And $mCompiler["instructionSet"] <> $sInstructionSet Then ContinueLoop
    
    		; keep entry
    		$aCompilers[$iNew] = $aCompilers[$i]
    		$iNew += 1
    	Next
    	Redim $aCompilers[$iNew]
    
    	Return $aCompilers
    EndFunc
    Alles anzeigen

    Damit kannst du direkt aus AutoIt heraus den ASM-Code und auch das Binary von dem godbolt-Server beziehen ohne erst auf deren Seite zu müssen.

Spenden

Jeder Euro hilft uns, Euch zu helfen.

Download

AutoIt Tutorial
AutoIt Buch
Onlinehilfe
AutoIt Entwickler
  1. Datenschutzerklärung
  2. Impressum
  3. Shoutbox-Archiv
Community-Software: WoltLab Suite™