Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
for example, we know that printf() function displays text in the console screen. But how are functions like printf() defined. Is it possible to write code to display text without the use of any library files? is assembly code used in defining these functions?
We can talk about C more easily, because it's a very basic language and really a little more higher over asm.
The answer is: system calls.
You could wonder: why? There are things that a language cannot do. And I/O is one of those. I/O streams are "owned" by the Operating System. It handles them.
The OS allows you to use them, but you must always rely on it before.
System calls are very basic: there are no format strings or whatever, for example.
Also you need to consider that system calls are OS-dependent. Windows' ones are different from Linux's ones.
puts implementation in the glibc
Since every library/code internally use the operating system calls provided by kernel.
So, It is possible to write your own printf like function without using c library.
If you want to know how these functions internally works, you can go for assembly language programming.
Is it possible to write code to display text without the use of any library files?
Yes of course it is. You might directly drive your display device, without any use of the standard functions.
is assembly code used in defining these functions?
Not necessarily, it can be completely accomplished in c or c++, without a single line of assembler code.
In the end it depends on the actual toolchain you are using to compile your programs, and the standard libraries that come with it, how these functions are defined. There are certain low level functions, you can 'override' for your concrete environment.
A common binding is to map the standard output interface (as used by printf()) to one of the UART interfaces of a MCU.
E.g for the commonly used newlib(c) coming with GCC toolchains here's some reference what's necessarily has to, and optionally can be ported to any environment: 'What steps do I need to do to port newlib to a new platform?'
Is it possible to write code to display text without the use of any library files?
Absolutely, since they have also done it, haven't they?
You would need to interface your kernel for writing low-level libraries like that, albeit it is not strictly necessary for each single case.
is assembly code used in defining these functions?
Yes, partially, using SIMD alike and other clever tricks for performance critical parts, etc.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I know that the inline asm exists, but is it also possible to execute machine code from a file during RUNTIME?
Would i need to write my own interpreter?
I'm using the GNU C++ compiler with c++ 14 enabled, on Windows 7.
Thanks for reading.
With your rephrasing into machine code, this question starts taking a more reasonable shape.
A short answer: Yes, you can run machine code from within your application.
A longer answer is - it's complicated.
Essentially, any string of bits and bytes in memory can be executed, given some conditions are met, such as the data being legal machine instructions (Otherwise the processor will invoke the illegal instruction exception and the OS will terminate your program) and that the memory page into which the data is loaded is marked with executable permissions.
Having said that, the conditions required for that machine code to actually run correctly and do what you expect it to do, is significantly harder, and have to do with understanding of Virtual Memory, Dynamic Loaders and Dynamic Linkers.
To bluntly answer your question, for a POSIX compliant environment at the least, you could always use the mmap system call to map a file into memory with PROT_EXEC permissions and jump into that memory space hoping for the best.
Naturally, any symbols that code would be expecting to find in memory aren't likely to be there, and the code was better compiled as PIC (Position Independent Code) but this roughly answers your question with a YES.
For better control, you'd usually prefer to use a more standard method, such as compiling your extra code as a shared object (Dynamic Link Library, DLL in Windows) and loading it into your application with dlopen while using dlsym to access symbols within it. It still allows you to load machine code from the disk into your application, but it also stores the machine code in a well formatted, standard way, which allows the dynamic linker to properly load and link the new code segment into your application, reducing unexpected behavior.
In neither of these cases will you need an interpreter, but neither is it a matter of language or compiler used - this is OS specific functionality, and will behave quite differently on Windows.
As a different approach, you could consider using the #include directive to import an external chunk of assembly code into your work while you're still working on it and properly incorporate it in compile time, which will yield far more deterministic results.
Edit:
For windows, the parallel for mmap is CreateFileMapping
dlopen is LoadLibrary
Not a Windows expert, sorry...
Let us distinguish between "assembler code"/assembly code (which is what this question initially asked about) and machine code (after one of the edits).
Anything you might describe as "assembler code" (or more usually "assembly code") but not machine code (i.e. anything not being actual, binary, executable, machine code) cannot be "executed". You can only read it into what I would call an "assembly-code-interpreter" and have it processed. I do not know of any such a program.
Alternatively, you can have it processed at runtime by a build process and execute the resulting executable. That however seems not to be what you are asking about.
Note that this does not mean that you can execute any machine code you might find in a file on your disk. It needs to be for the right, same platform and be supported by the appropriate runtime environment. That is applicable to executeables created for your machine or compatibles, e.g. the result of a built.
Note that I understand "assembler code" ("assembly code") to mean source code in assembly language, which is a (probably the most basic) representation of programs in (not really) human eye readable form. (As immortal has commented, an assembler is the program to process assembly code into machine code.) Opcode mnemonics are used, e.g. cmp r1, r2 for comparing two registers. That string of characters however is guaranteed not to make any sense when trying to execute it straight forward. (OK, strictly speaking I should say "almost guaranteed"...)
Machine code which is appropriatly made for your environment, including a loader, can be executed from a file. Any operating system will support you doing that, most will even provide a GUI for doing that. (I notice this sounds somewhat cynical, sorry, not meant to be.) Windows for example will execute an executable if you double-click its icon in the windows explorer.
An alternative to such executable programs are libraries. Especially the dynamic link libraries are probably quite close to what you are thinking of. They are very similar, in needing to be targeted at your environment. Then they can (usually partially) be executed from a linked program, via agreed calling mechanisms. Those mechanisms in turn ensure that the code is executed in a matching environment, including being able to return results.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to find different ways to reuse my C++ functions in different applications. Say for example I have the following functions:
Function A(){} // this will do a complex math operation
Function B(){} // this will load a complex shape file
Function C(){} // Print the results.
I need to use the above 3 functions in 3 different C++ programs. They are completely independent and I'm trying to see what the best way is to use them in all of my applications rather than writing same code 3 times.
I am thinking about the following options:
Option A: Writing static library
Option B: Writing dynamic library
Option C: Windows Services
Option D: Same code and compile everywhere
Are there any other options? Or what would be the best option?
If the functions are only going to be called "in-house" by yourself and/or your co-workers (i.e. they aren't going to be exposed to people who don't have access to your source code repository) then option (D) is sufficient. Just keep the the .cpp and .h files in a single well-known sub-directory of your source code repository and have each application's project file reference them as necessary. This is simple to implement and gives you maximum flexibility (since each project can compile the shared .cpp files with different compiler-flags that best suit its own needs, if necessary -- with a library you'd have to figure out a single set of compiler flags that would work for all applications that want to link to the library, which isn't always convenient).
If you're writing an API for public consumption, OTOH, things get a little more complex, since after you release the code to the public you will no longer be in full control of which versions are getting used and where. In that case you will have to make a decision based on who your users are and what you think they would be most comfortable with.
Option C can probably be tossed out since it's overkill for this sort of thing, and carries the penalty of tying your code to a particular OS with no compensatory advantage.
It's option D (compile everywhere) all the way -- with the only exceptions being stand-alone libraries that are shared with many, many other people (or closed-source).
This makes it a lot easier to manage releases, because there really aren't any -- each copy of the library can be updated independently -- whenever is convenient.
This makes it easy for each project to debug into the library, with the particular version of the library that is in use.
This gives you the option of customizing the library for each project -- but use this capability judiciously to minimize merging complexity.
This choice is independent of whether or not you build the library it into a separate binary package as part of your build process.
I would recommend using something like git-submodules to manage the code -- except that the git-submodules feature is kind of half-baked.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Is there a way how I can tell a C++ compiler/linker to compile the source code into my own homemade opcode list? I need it for my virtual machine which will execute on a microcontroller.
I don't want to create a C++ compiler from scratch, but only change the opcodes, addresses of CPU status register, stack pointer and GPIO registers, program memory and data memory from an existing compiler that is open source so that people making programs for it don't have to rewrite the whole code, but just port it using the libraries that are compatible with my own compiler's libraries.
Example is an avr-gcc compiler.
The compiler and its libraries must not be proprietary in the way that I or any programmer have to pay for it and I don't want it to be either GPL in such way that a programmer must reveal source for their own projects. I want all my programmers to freely use my compiler, be free to license their work in whatever way they want as well as choose to make it open source or proprietary.
Let's consider the steps involved:
Retargeting an existing C++ compiler: Several production-quality, retargetable C++ compilers are freely available today. For instance, the LLVM platform (clang++) provides some pointers on writing a backend for a new hardware architecture (this naturally applies to VM's as well!). Unfortunately, up-to-date documentation on porting the GNU compilers is harder to come by. It's entirely possible that many of the older documents remain relevant today, but I know far too little about GCC to say.
Note that the effort required to retarget either compiler is likely to depend on how well the instruction set of your virtual machine matches the compiler's low-level intermediate representation. Since they often (at least semantically) take the form of three-address code ― that is, instructions with two source operands and one destination ― writing a code generator for, say, a stack machine (in which all operands are implicitly addressed) could prove to be a bit more difficult.
From this point on, you really have two options. You could stick to the conventional way in which C++ programs are compiled, i.e., from source, to assembly, to object files, to linked executable or library. That involves going through the steps I have outlined below. But since you are targeting a virtual machine, it may have requirements that are radically different from those of modern hardware architectures. In that case, you may want to steer clear of existing software like binutils and roll your own assembler and linker.
Writing or porting an assembler: Unless your chosen compiler is able to directly generate machine code, you will most likely also need to write an assembler for your virtual machine, or port an existing one. If your virtual machine's instruction set looks anything like that of a modern machine, and if you want to use the standard C++ compilation/linking pipeline, you could look into porting binutils, specifically gas, the GNU assembler.
Writing or porting a linker: The object files produced by your assembler are not in themselves executable programs. Addresses must be assigned to symbols and segments, and references between object files must be resolved. This means that the linker needs some understanding of your instruction set. In particular, it must be able to find and patch locations in code and data that address memory. The binutils porting guide I linked above is relevant here, too; you may also enjoy reading Linkers and Loaders.
As #Mat noted in the comment section above, the GPL doesn't usually "infect" the output of a program licensed under it. See this section. Notably:
The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work.
I am not a lawyer, but I take this to mean that an exception would be made for, say, compiling the compiler with itself ― the output would still be subject to the terms of the GPL.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Is there any way within a C or C++ program of getting information on all the functions that could be called? Perhaps a compiler macro of some sort? I know that there are programs that could take in source files or .o files and get the symbols or the prototypes, and I suppose I could just run those programs within a c program, but I'm curious about maybe returning function pointers to functions or an array of function prototypes available in the current scope, or something related?
I'm not phrasing this very well, but the question is part of my curiosity of what I can learn about a program from within the program (and not necessarily by just reading its own code). I kind of doubt that there is anything like what I'm asking for, but I'm curious.
Edit: It appears that what I was wondering about but didn't know how to describe very well was whether reflection was possible in C or C++. Thank you for your answers.
The language doesn't support reflection yet. However, since you are looking for some sources of information, take a look at the Boost.Reflect library to help you add reflection to your code, to a certain extent. Also, look at ClangTooling and libclang for libraries that let you do automated code-analysis.
C and C++ have no way to gather the names of all the functions available.
However, you can use macros to test standards (ANSI, ISO, POSIX, etc) compliance, which can then be used to guarantee the presence of each standard's functions.
For example, if _POSIX_C_SOURCE is defined, you can (usually) assume that functions specified by POSIX will be available:
#ifdef _POSIX_C_SOURCE
/* you can safely call POSIX functions */
#else
/* the system probably isn't POSIX compliant */
#endif
Edit: If you're on a Linux system, you can find some common compatibility macros under feature_test_macros(7). OS X and the BSDs should have roughly the same macros, even though they may not have that manual page. Windows uses the WINVER and _WIN32_WINNT macros to control function visibility across releases.
No.
C++ meta-programming power is weak don't include any form of reflection. You can however use tools like gcc-xml to parse a C++ program and export its content in a easier to analyze format.
Writing your own parser for C++ to extract function declaration is going to be a nightmare unless you only need to do that on your specific project and you're ready to cut some corners.
I know many have asked this question before, but as far as I can see, there's no clear answer that helps C++ beginners. So, here's my question (or request if you like),
Say I'm writing a C++ code using Xcode or any text editor, and I want to use some of the tools provided in another C++ program. For instance, an executable. So, how can I call that executable file in my code?
Also, can I exploit other functions/objects/classes provided in a C++ program and use them in my C++ code via this calling technique? Or is it just executables that I can call?
I hope someone could provide a clear answer that beginners can absorb.. :p
So, how can I call that executable file in my code?
The easiest way is to use system(). For example, if the executable is called tool, then:
system( "tool" );
However, there are a lot of caveats with this technique. This call just asks the operating system to do something, but each operating system can understand or answer the same command differently.
For example:
system( "pause" );
...will work in Windows, stopping the exectuion, but not in other operating systems. Also, the rules regarding spaces inside the path to the file are different. Finally, even the separator bar can be different ('\' for windows only).
And can I also exploit other functions/objects/classes... from a c++
and use them in my c++ code via this calling technique?
Not really. If you want to use clases or functions created by others, you will have to get the source code for them and compile them with your program. This is probably one of the easiest ways to do it, provided that source code is small enough.
Many times, people creates libraries, which are collections of useful classes and/or functions. If the library is distributed in binary form, then you'll need the dll file (or equivalent for other OS's), and a header file describing the classes and functions provided y the library. This is a rich source of frustration for C++ programmers, since even libraries created with different compilers in the same operating system are potentially incompatible. That's why many times libraries are distributed in source code form, with a list of instructions (a makefile or even worse) to obtain a binary version in a single file, and a header file, as described before.
This is because the C++ standard does not the low level stuff that happens inside a compiler. There are lots of implementation details that were freely left for compiler vendors to do as they wanted, possibly trying to achieve better performance. This unfortunately means that it is difficult to distribute a simple library.
You can call another program easily - this will start an entirely separate copy of the program. See the system() or exec() family of calls.
This is common in unix where there are lots of small programs which take an input stream of text, do something and write the output to the next program. Using these you could sort or search a set of data without having to write any more code.
On windows it's easy to start the default application for a file automatically, so you could write a pdf file and start the default app for viewing a PDF. What is harder on Windows is to control a separate giu program - unless the program has deliberately written to allow remote control (eg with com/ole on windows) then you can't control anything the user does in that program.