//------------------------------------------------------------------- // launch.cpp // // This program illustrates use of the UNIX 'mmap()' function // to map a file having so-called 'binary-executable' format, // and then execute it by making an (indirect) function-call. // A special 'linker-script' was used to override the default // Executable and Linkable File-format (ELF) that is normally // produced by the GNU compiler tools (gcc, as, and ld). The // binary-executable format used here is inteded to be loaded // (and to reside during execution) at virtual address zero. // // programmer: ALLAN CRUSE // written on: 19 OCT 2004 //------------------------------------------------------------------- #include // for printf(), perror() #include // for open() #include // for exit() #include // for lseek(), close() #include // for mmap(), unmap() void (*myexec)( void ); // null function-pointer char filename[] = "courseid.b"; int main( int argc, char **argv ) { //----------------------------------------------- // open the executable file for read-only access //----------------------------------------------- int fd = open( filename, O_RDONLY ); if ( fd < 0 ) { perror( filename ); exit(1); } //---------------------------------------------- // memory-map this file at virtual-address zero //---------------------------------------------- int size = lseek( fd, 0, SEEK_END ); int prot = PROT_READ | PROT_EXEC; int flag = MAP_PRIVATE | MAP_FIXED; void *mm = mmap( NULL, size, prot, flag, fd, 0 ); if ( mm == MAP_FAILED ) { perror( "mmap" ); exit(1); } //---------------------------------------------------- // execute the program with an indirect function-call //---------------------------------------------------- myexec(); //----------------------------------------------- // close the file, destroy the mapping, and exit //----------------------------------------------- munmap( mm, size ); close( fd ); exit(0); }