nasm: ELF format cannot produce non-PC-relative PLT references - nasm

I'm experiencing an error with nasm compiler. Inside nasm's source code the error originates here.
I' trying to build an relocatable object file that can resolve a specific symbol during run time linkage (not build time linkage).
Minimal code:
EXTERN start
foo:
; wrt: with respect to
dd start wrt ..plt
The error is ELF format cannot produce non-PC-relative PLT references.
What's going on here?

It seems like you have to use dd start wrt ..got, i.e. reference the global offset table instead of the procedure linkage table. The latter would only work with something like call start wrt ..plt, i.e. an real instruction. In this case you are using dd, i.e. storing an immediate value in the output.

Related

Does WINE implement "_printf" and similar functions in MSVCRT?

Here is an example program that illustrates my problem, it can be compiled using FlatAssembler without using a linker:
format PE console
entry start
include 'win32a.inc'
section '.text' code executable
start:
mov dword [esp],_output1
call [printf]
mov dword [esp+4],first
mov dword [esp],_input
call [scanf]
mov dword [esp],_output2
call [printf]
mov dword [esp+4],second
mov dword [esp],_input
call [scanf]
finit
fld dword [first]
fabs
fld dword [second]
fxch
fld1
fxch
fyl2x
fldl2e
fdivp st1,st0
fmulp st1,st0
fldl2e
fmulp st1,st0
fld1
fscale
fxch
fld1
fxch
fprem
f2xm1
faddp st1,st0
fmulp st1,st0
fstp dword [result]
fld dword [result]
fst qword [esp+4]
mov dword [esp],_output
call [printf]
invoke system,_pause
invoke exit,0
_output1 db "Enter the first number: ",0
_output2 db "Enter the second number: ",0
_input db "%f",0
_pause db "PAUSE",0
_output db "The first number to the power of the second number is: %f.",10,0
section '.rdata' readable writable
result dd ?
first dd ?
second dd ?
section '.idata' data readable import
library msvcrt,'msvcrt.dll'
import msvcrt,printf,'printf',system,'system',exit,'exit',scanf,'scanf'
So, the expected output is, of course, something like this:
Enter the first number: -2.5
Enter the second number: -2
The first number to the power of the second number is: 0.16
And that's the output I indeed get if I run that program on Windows 10. However, if I try to run that program on WINE on Oracle Linux, the output I get is:
000f:fixme:service:scmdatabase_autostart_services Auto-start service L"MountMgr" failed to start: 2
000f:fixme:service:scmdatabase_autostart_services Auto-start service L"WineBus" failed to start: 2
wine: Bad EXE format for Z:\home\teo.samarzija\Documents\Assembly\debug.exe.
Any idea what's going on?
I've done a little research, and I can't find any reference confirming that _printf and _scanf are even implemented in WINE's MSVCRT. However, I am not sure that's the problem, and, if it is a problem, that that's the only problem.
However, if I try to run that program on WINE on Oracle Linux, the
output I get is:
000f:fixme:service:scmdatabase_autostart_services Auto-start service L"MountMgr" failed to start: 2
000f:fixme:service:scmdatabase_autostart_services Auto-start service L"WineBus" failed to start: 2
wine: Bad EXE format for Z:\home\teo.samarzija\Documents\Assembly\debug.exe.
A "Bad EXE format" error is something different entirely. It doesn't imply that the problem is a missing imported function. The loader never got that far. It wasn't even able to read your binary. This is very likely caused by a bitness mismatch. For example, trying to run a 64-bit application on a 32-bit system.
Aside from this problem, it is worth pointing out that your attempted use of C runtime library functions is inherently non-portable. It might work, if Wine (or whatever other runtime environment) provides a function with an identical signature, but it very likely won't.
I suppose I should further clarify, since calling a standard C runtime library function "non-portable" may raise a few eyebrows. These functions are portable at the source-code level, but not at the binary level. Even without the added complexity of Wine, the C runtime library functions are non-portable, as Microsoft's CRT is versioned—you have to link to the appropriate version and have that DLL available at runtime, or your application will not work.
This exact problem is why Windows provides wrappers for these standard functions as part of the basic platform API, which is universally available. If you want to be fully portable to all implementations of the Win32 environment, and you aren't linking in your own copy of the C runtime library, then you should call these functions instead.
The Win32 version of the sprintf function is wsprintf. It has the same interface as sprintf, so you can call it the same way, as a drop-in replacement. In fact, although you shouldn't rely on this, it is implemented by Windows as a simple wrapper around the sprintf version provided by the local copy of the C runtime libraries.
If you want a version to which you can pass an argument list (a la vsprintf), then you can call wvsprintf.
Note that, unlike most of the Windows API functions, these functions use the __cdecl calling convention, not the __stdcall calling convention. Make sure that you are adhering to that in your assembly code. In short, that means passing arguments from right-to-left and cleaning up the stack at the call site.
Microsoft has, however, deprecated these functions, as they aren't entirely safe (buffer overflows and etc. are possible). As replacements, they offer the functions in the StrSafe.h header. These functions come in two variants: those which take a count of bytes (Cb) and those which take a count of characters (Cch). The relevant ones to this discussion would be either StringCbPrintfA or StringCchPrintfA. These are trickier to use from assembly language, however, because they're meant to be used inline by simply including the StrSafe.h header file. You can use them in library form, but then you'll need to pass the corresponding StrSafe.lib stubs to the linker. Note that linking to this library means your application will only run on Windows XP with SP2 or later.
This gets you halfway there. You are actually trying to call printf, rather than sprintf. The gap, of course, is getting the formatted string written to the console. Once you have the formatted string (generated by wsprintf, StringCchPrintfA, or whatever), that can be accomplished by calling the WriteConsole function, which is the Win32 API for writing output to the console window. If you want STDOUT, then you need to open that handle first with GetStdHandle(STD_OUTPUT_HANDLE).
Anyway, I got the answer:
https://www.linuxquestions.org/questions/linux-general-1/can%27t-install-wine-on-64-bit-oracle-linux-4175655895/page2.html#post6012838
In short, on 64-bit Oracle Linux, WINE needs to be compiled from source to work properly.

riscv/gcc/ld - "Undefined reference to printf" using own script to link

Currently, I'm learning RISC-V, use the RISC-V toolchain, and edit a new ld script for my embedded. I write a example, and compile to watch the opcode.
Example:
#include <stdio.h> //float.c
int main()
{
float a=1.04;
printf("a=%f\n",a);
return 0;
}
My steps is:
1. riscv64-unknown-elf-gcc -S float.c  *//generate assembly code*
2. riscv64-unknown-elf-as float.s -o float.o  *//generate obj file*
3. riscv64-unknown-elf-ld -T elf64lriscv1.x float.o *//use own script to link, -T is using other script*
and then,it will show "float.c:(.text+0x50): undefined reference to `printf'
I'm try
Add -lc parameter, but doesn't working, it will show more undefined message.
My ld script
OUTPUT_FORMAT("elf64-littleriscv", "elf64-littleriscv","elf64-littleriscv")
OUTPUT_ARCH(riscv)
ENTRY(_start)
SEARCH_DIR("/path/to/install/riscv/toolchain/riscv64-unknow-elf/lib");
/*MEMORY{ //for my embedded allocation
flash : org = 0x0, l = 0x10000
ram : org= 0x10000, l = 512
}*/
SECTIONS{
_start =0x10000;
.text :
{
*(.text)
}
.bss :
{
*(.bss)
*(.sbss)
}}
Also, i'm trying to use the default script, like this command:
$ riscv-unknown-elf-ld float.o -o float
but it is same result....
please help me!
Regards!
printf is provided by the C standard library (and is very difficult to implement). You need to link it (perhaps by adding -lc to your riscv-unknown-elf-ld command, or by giving the complete path of that library)
You might pass additional options to your riscv-unknown-elf-ld perhaps -M, -L search-dir, --trace, --verbose, etc. Read also more carefully the chapter about ld scripts.
Since you are cross-compiling, you might need to cross-compile some libc from source code.
You need to spend more time understanding the behavior of linkers and ELF object files and executable format (see also elf(5)). Consider reading Linkers and Loaders
You could use other cross- binutils programs (like cross- objdump, nm, readelf etc...) to explore the relevant object files.
If you are coding for a bare metal system, you might want to compile in freestanding mode (passing -ffreestanding to your GCC) and provide so implement your own printf (or other output) function. Existing free software C libraries could inspire you (but you need to find one or work many months to develop some equivalent). Study for inspiration the source code of GNU libc or of musl-libc.
I recommend also reading about OSes, e.g. Operating Systems: Three Easy Pieces (since the OS concepts are relevant to you, because an embedded system on the bare metal share features with OSes). OSDEV wiki might also be helpful (but is not about RISC-V).
You could need several months of work (or even years), so budget it appropriately.
BTW, I am surprized that you use a float in your example. Floating point is difficult. See floating-point-gui.de ; For a first try, I would consider using integer only.

While generating kernel image, Getting error as unrecognized command line option ‘-mlongcalls'

While generating kernel image for Xtensa ISS platform
i'm getting compilation error as unrecognized command line option ‘-mlongcalls'
Can any one explain me about the -mlongcalls ? and Why it's unrecognized ?
I'm using Buildroot for generating cross compilation environment.
refer to man gcc
"
**-mlongcalls**
**-mno-longcalls**
When this option is enabled, GCC instructs the assembler to translate direct calls to indirect calls unless it can determine that the target of a direct call is in the range
allowed by the call instruction. This translation typically occurs for calls to functions in other source files. Specifically, the assembler translates a direct "CALL"
instruction into an "L32R" followed by a "CALLX" instruction. The default is -mno-longcalls. This option should be used in programs where the call target can potentially be
out of range. This option is implemented in the assembler, not the compiler, so the assembly code generated by GCC still shows direct call instructions---look at the
disassembled object code to see the actual instructions. Note that the assembler uses an indirect call for every cross-file call, not just those that really are out of range.
"

Difference in md5sums in two object files

I compile twice the same .c and .h files and get object files with the same size but different md5sums.
Here is the only difference from objdump -d:
1) cpcidskephemerissegment.o: file format elf64-x86-64
Disassembly of section .text:
0000000000000000 <_ZN68_GLOBAL__N_sdk_segment_cpcidskephemerissegment.cpp_00000000_B8B9E66611MinFunctionEii>:
2) cpcidskephemerissegment.o: file format elf64-x86-64
Disassembly of section .text:
0000000000000000 <_ZN68_GLOBAL__N_sdk_segment_cpcidskephemerissegment.cpp_00000000_8B65537811MinFunctionEii>:
What can be the reason? Thanks!
I guess, the compiler didn't know how to name this namespace and used path to the source file plus some random number.
The compiler must guarantee that a symbol in unnamed namespace does not conflict with any other symbol in your program. By default this is achieved by taking full filename of the source, and appending a random hash value to it (it's legal to compile the same source twice (e.g. with different macros) and link the two objects into a single program, and the unnamed namespace symbols must still be distinct, so using just the source filename without the seed is not enough).
If you know that you are not linking the same source file more than once, and want to have a bit-identical object file on re-compile, the solution is to add -frandom-seed="abcd" to your compile line (replace "abcd" with anything you want; it's common to use the filename as the value of random seed). Documentation here.
The reasons can be many:
Using macros like __DATE__ and __TIME__
Embedding counters that are incremented for each build (the Linux kernel does this)
Timestamps (or similarly variable quantities) embedded in the .comments ELF section. One example of a compiler that does this is the xlC compiler on AIX.
Different names as a result of name mangling (e.g. C++)
Changes in environment variables which are affecting the build process.
Compiler bug(s) (however unlikely)
To produce bit identical builds, you can use GCC's -frandom-seed parameter. There were situations where it could break things before GCC 4.3, but GCC now turns functions defined in anonymous namespaces into static symbols. However, you will always be safe if you compile each file using a different value for -frandom-seed, the simplest way being to use
the filename itself as the seed.
Finally I've found the answer!
c++filt command gave the original name of the function:
{unnamed namespace}: MinFunction(int, int)
In the source was:
namespace
{
MinFunction(int a, int b) { ... }
}
I named the namespace and got stable checksum of object file!
As I guess, the compiler didn't know how to name this namespace and used path to the source file plus some random number.

sprof "PLTREL not found error"

I'm trying to profile our shared library, but whenever I have the environmental variable LD_PROFILE set, I get "PLTREL not found in object ". What gives? Is there some sort of linker flag I'm missing or what? There seems to be no information about this on the internets. The man page for sprof is about 10 words long.
According to an unanswered question on Google Groups, it looks like you aren't the very first person with this problem.
I think pltrel means plt-relative; in some ELF design notes,
There is a .plt section created in the code segment, which is an array of function stubs used to handle the run-time resolution of library calls.
And here's yet a little more:
The next section I want to mention is the .plt section. This contains the jump table that is used when we call functions in the shared library. By default the .plt entries are all initialized by the linker not to point to the correct target functions, but instead to point to the dynamic loader itself. Thus, the first time you call any given function, the dynamic loader looks up the function and fixes the target of the .plt so that the next time this .plt slot is used we call the correct function. After making this change, the dynamic loader calls the function itself.
Sounds to me like there's an issue with how the shared library was compiled or assembled. Hopefully a few more searches to elf PLT section gets you on the right track.
Found this that may be relevante for you:
Known issues with LD_AUDIT
➢ LD_AUDIT does not work with Shared Libraries with no code in them.
➢ Example ICU-4.0 “libicudata.so”
➢ Error: “no PLTREL found in object /usr/lib/libicudata.so.40”
➢ Recompile after patching libicudata by sed'ing -nostdlib etc away sed -i --
"s/-nodefaultlibs -nostdlib//" config/mh-linux
It seems the same applies for LD_PROFILE

Resources