ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools...

96
ESSENTIAL Linux For EMBEDDED Developers The open source way!

Transcript of ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools...

Page 1: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

ESSENTIALLinuxForEMBEDDEDDevelopers

Theopensourceway!

Page 2: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

AnoverviewofLinuxenvironment

LinuxEvolutionWhatisLinux?Distributions

LinuxVirtualizationLinuxEverywhere

TheLinuxkernelarchives

Page 3: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

http://en.wikipedia.org/wiki/Linux

Page 4: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

GNU/Linux

• Recursiveacronym“GNU’snotUNIX”• http://www.gnu.org/ nothttp://www.gnu.com/

• RichardStallman(1983)GoalafreeUnix• KnownforFreeSoftwaremovement,GNU,Emacs,gcc• NeverreallyreleasedGNUoperatingsystem

• Linus1992opensourcedLinuxKernelandnamedGNU/Linux

• FreeSoftwareFoundation• http://www.fsf.org/

http://en.wikipedia.org/wiki/GNU

Page 5: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

TypicalLinuxSYSTEMLayout

SystemReserved

Rootfs

Kernel

Bootloader

Hardware

Page 6: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Linux Distributions

•Redhat/fedora/Centos• Most popular, good all around choice• Fedora – community supported• Enterprise Redhat – corporate supported

•Debian/Ubuntu/Mint• Completely noncommercial• Massive package selection and easy management• Not as user friendly, but improving

•SuSe• IBM Preferred Linux – z/Series Linux of choice

Page 7: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

TheBlackfin uClinux DistributionbyAnalogDevices–aforkoftheuClinux distributionforBlackfin processors

EmbeddedAlley- seehttp://www.embeddedalley.com/

Lineo SolutionsuLinux

MontaVista Linux- seehttp://www.mvista.com/products_services.php

Pengutronix - seehttp://www.pengutronix.de/oselas/bsp/index_en.html

RidgeRun Linux- seehttp://www.ridgerun.com/sdk.shtml

TimeSys Linux- seehttp://www.timesys.com/embedded-linux/linuxlink

WindRiver- seehttp://www.windriver.com/products/linux/

Digi EmbeddedLinuxforDigi's ARMbasedmodules

EmbeddedLINUX

Page 8: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Virtualization

GuestOperatingSystemVirtualization SharedKernelVirtualization

KernelLevelVirtualization HypervisorVirtualizationXen,VMwareESXServerandMicrosoft'sHyper-Vtechnology(UML)and(KVM).

LinuxVServer,SolarisZonesandContainers,andOpenVZVMwareServerandVirtualBox.

SeeL4LinuxCoLinuxMkLinux

Page 9: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

LinuxKERNELTODAY

Page 10: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Kernel.org

Page 11: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Linux Kernel Information

l The Linux kernel version numbers consist of three numbers separated by decimals, such as2.2.14. The first number is the major version number. The second number is the minor revisionnumber. The third number is the patch level version

l There are two stages of kernel releases: “stable” and “development”. Development kernels endin an odd number (2.3, 2.5, …), stable or production kernels end in an even number (2.4,2.6,3.0).

l Once a kernel is deemed stable, it will move from an odd to even second number for release(e.g., from 2.3.51 to 2.4.0).

l You can get a good sense of what the future production state of Linux will be by looking at thedevelopment kernel.

l http://www.kernel.org

Page 12: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

ApplicationinteractionsinLinuxTheKernelArchitectureoverviewandaddressspaceview

Applicationandmodesofoperations,KernelandUseraddressSpacesSystemcall,entryandexitpoints,lowlevelview,strace,

parameterpassingandkernelimplementations

Page 13: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Structure:The“Core” LinuxKernel

Applications

SystemLibraries(libc)

SystemCallInterface

Hardware

Architecture-DependentCode

I/ORelated ProcessRelatedScheduler

MemoryManagement

IPC

FileSystems

Networking

DeviceDrivers

Mod

ules

Page 14: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

OperativeModes

• To avoid having applications that constantly crashed,newer OSs were designed with 2 different operativemodes:

• Kernel Mode:• the machine operates with critical data structure, directhardware (IN/OUT or memory mapped), direct memory,IRQ, DMA, and so on.

• User Mode:• users can run applications.

Page 15: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Usermode&Kernelmode(32bit)

Init|

Mdm|

Mdm|

gnome-terminal|

Bash|

App.exe

Vmlinux KernelAddressSpace

UserAddressSpace

0xC10000000xBFFFFFFF

0xFFFFFFFF

0x00000000

3G

1G

Page 16: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

OperativeModes

• Kernel Mode "prevents" User Mode applications fromdamaging the system or its features.

•Modern microprocessors implement in hardware atleast 2 different states. For ex. under Intel, 4 statesdetermine the PL (Privilege Level). It is possible to use0,1,2,3 states, with 0 used in Kernel Mode.

• Linux/UnixOSrequiresonly2privilegelevels,andwewillusesuchaparadigmaspointofreference

Page 17: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

SwitchingfromUserModetoKernelMode-1

• Whendoweswitch?• Onceweunderstandthatthereare2differentmodes,wehavetoknow

whenweswitchfromonetotheother.

• Typically,thereare2pointsofswitching:

1. WhencallingaSystemCall:2. WhenanIRQ(orexception)comes

Page 18: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Let’sobservetheuser/kernelspace

• usevmstat tograsprecentprocesscontext

Page 19: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Librarycallvs SystemCallinLinuxWrapperandWrapperbased

Systemcall,EntryandExitPointsExampleofwrappertoasystemcallflow

Page 20: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Systemcalls

• Themaininterfacebetweenthekernelanduserspace isthesetofsystemcalls

• About~300systemcallsthatprovidesthemainkernelservices• Fileanddeviceoperations,networkingoperations,inter-

processcommunication,processmanagement,memorymapping,timers,threads,synchronizationprimitives,etc.

• Thisinterfaceisstableovertime:onlynewsystemcallscanbeaddedbythekerneldevelopers

• ThissystemcallinterfaceiswrappedbytheClibrary,anduserspace applicationsusuallynevermakeasystemcalldirectlybutratherusethecorrespondingClibraryfunction

Page 21: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

SystemCalls:read• Cexample:

count=read(fd,buffer,nbyte)

• pushparametersonstack

• calllibrarycode

• putsystemcallnumberinregister

• callkernel(TRAP)• kernelexaminessystemcallnumber• findsrequestedsystemcallhandler• executerequestedoperation

• returntolibraryandcleanup• increaseinstructionpointer• removeparametersfromstack

• resumeprocess

application

user spacekernel space

count = read (fd , buffer , nbytes)

read libraryprocedure

register

memory (stack) buffer

nbytesbufferfd

X (read)

system callhandler

X

sys_read()

Page 22: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

KernelEntryandExit

Kernel

Devices

Library Code

System Call Interface

appapp

trap /interrupt

table

systemcalltable

schedulerboot

80h

exceptions(error traps)

interrupt devicedialog

trap

page faults

Page 23: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

SystemCallsvs.LibraryCalls

•man2• historicalevolutionof#ofcalls

• Unix6e(~50),Solaris7(~250)• Linux2.0(~160),Linux2.2(~190),Linux2.4(~220)

• librarycallsvs.systemcallpossibilities:• librarycallneverinvokessystemcall• librarycallsometimesinvokessystemcall• librarycallalwaysinvokessystemcall• systemcallnotavailablevialibrary

• caninvokesystemcall“directly” viaassemblycode

Page 24: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

CostofCrossingthe“KernelBarrier”

•Morethanaprocedurecall• Lessthanacontextswitch• Costs:

• Establishingkernelstack• Validatingparameters• Kernelmappedtouseraddressspace?

Page 25: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

ImplementationExample:“Hello,world!”

.data#sectiondeclaration

msg:.string"Hello,world!\n"#ourdearstringlen =.- msg #lengthofourdearstring

.text #sectiondeclaration

#wemustexporttheentrypointtotheELFlinkeror.global_start#loader.Theyconventionallyrecognize_startastheir

#entrypoint.Useld -efootooverridethedefault._start:#writeourstringtostdout

movl $len,%edx #thirdargument:messagelengthmovl $msg,%ecx #secondargument:pointertomessagetowritemovl $1,%ebx#firstargument:filehandle(stdout)movl $4,%eax#systemcallnumber(sys_write)int $0x80#callkernel

#andexit

movl $0,%ebx#firstargument:exitcodemovl $1,%eax#systemcallnumber(sys_exit)int $0x80#callkernel

Page 26: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

LinuxSystemCalls(1)

Invokedbyexecutingint $0x80.• Programmedexceptionvectornumber128.• CPUswitchestokernelmode&executesakernelfunction.

• Callingprocesspassessyscall number identifyingsystemcallineax register(onIntelprocessors).

• Syscallhandlerresponsiblefor:• Savingregistersonkernelmodestack.• Invokingsyscallserviceroutine.• Exitingbycallingret_from_sys_call().

Page 27: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

ParameterPassing

• Onthe32-bitIntel80x86:• 6registersareusedtostoresyscall parameters.

• eax (syscall number).• ebx,ecx,edx,esi,edi storeparameterstosyscall serviceroutine,identifiedbysyscallnumber.

Page 28: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

InteractingwithModules

App_1 App_2 App_N

/dev/device_nodes

Vmlinuxmodule.ko

Page 29: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Basicutility,filter&developercommandessentials

UnderstandingRootFileSystemHierarchy

Page 30: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

LinuxFilesystemsondesktop

• HistoricallyLinuxhadnofs ofitsownandformallyhadminix fs runningonit

• Lateradpoted thethesecondextendedfilesystemformallyknownasext2fs

• Hasbeenenhancedtoext3fs,ext4fs• NowtheLinux3.XislookingtohaveBtrfs

• Btrfs isanewcopyonwritefilesystem forLinuxaimedatimplementingadvancedfeatureswhilefocusingonfaulttolerance,repairandeasyadministration

Page 31: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

LinuxTreeHierarchy

/

/root /bin /proc /usr /sbin /dev /opt /home

/home/ram

/home/sita

/src

linux

/ - (unnamed) the actual root

/root – a home area for root

/bin – utility commands

/proc – a bogus fs for Linux kernel

/usr – usr utilities and application/sbin – special commands /privileged /dev – device node for external devices /opt – optional applications /home – usually all you do is here/var – spool , log messages etc

Page 32: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

TheShell

• CommandinterpreterinoriginalUnix

• Readcommand• Perhapspre-processcommand

• Fork/execute• Returnexitstatusofcommand

• Alittlehistoryrevisited• BourneShell(sh)• Cchell• Korn shell• BourneAgainshell(bash)

Page 33: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Entrylevelcommands

• man• which• whatis• info• apropos

• date• cal• who• w• id• Write• mesg• bc

Page 34: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

PiPEs (|)&FILTER

• ps• nice• sleep• at• nohup• kill• ctrl+c• ctrl+z• fg• bg• top• vmstat

• grep• sort• tr• cut• paste• more• less• head• tail• nl• tee• wc

PROCESS

Page 35: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

FILEs/misc

• pwd• mkdir• cd• Ls• rmdir• cat• cp• ln• mv• rm

• chmod• chgrp• Chown• comm• cmp• diff• Uniq• touch• stat• file• compgen

DIR/FILE

Page 36: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

CSCOPE

• Lookatthefunctiondefinitionsstraightwayfromthefunctioncall• Lookoutforalltheplacesfromwhereaparticularfunctionisbeing

called.• Searchingstringsandpatterns• Determiningsourceswhichincludeaspecificheader• Besides,itdoeseditortaskslikeviewingthesourcefile,replacing

strings,etc

Page 37: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

CSCOPE• $cscope-help• Usage:cscope[-bcCdehklLqRTuUvV][-ffile][-Ffile][-ifile][-Idir][-sdir]

• [-pnumber][-Ppath][-[0-8]pattern][sourcefiles]

• -bBuildthecross-referenceonly.• -CIgnorelettercasewhensearching.• -cUseonlyASCIIcharactersinthecross-reffile(don’tcompress).

• -dDonotupdatethecross-reference.• -eSuppressthe-ecommandpromptbetweenfiles.

• -Fsymfile Readsymbolreferencelinesfromsymfile.

• -freffile Usereffile ascross-reffilenameinsteadofcscope.out.

• -hThishelpscreen.• -Iincdir Lookinincdir forany#includefiles.• -i namefile Browsethroughfileslistedinnamefile,insteadofcscope.files

• -kKernelMode– don’tuse/usr/includefor#includefiles.

-LDoasinglesearchwithline-orientedoutput.

-lLine-orientedinterface.

-num patternGotoinputfieldnum (countingfrom0)andfindpattern.

-PpathPrependpathtorelativefilenamesinpre-builtcross-reffile.

-pnDisplaythelastnfilepathcomponents.

-qBuildaninvertedindexforquicksymbolsearching.

-RRecurse directoriesforfiles.

-sdir Lookindir foradditionalsourcefiles.

-TUseonlythefirsteightcharacterstomatchagainstCsymbols.

-UCheckfiletimestamps.

-uUnconditionallybuildthecross-referencefile.

-vBemoreverboseinlinemode.

-VPrinttheversionnumber.

Page 38: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

SHELL• Internalcommandsvs externalcommands• Variables- local,exported,ENV• Arithmetic- expr [+,- ,\*,/,%]• Controls

• if[expression];then;…else…fi• caseexpressionin;1);;2);;*);;esac

• Looping:• while[expression]do…done• until[expression]do…done• forindexinexpressiondo…done

• CommandLine• $1,…$9• shift• $*,$#,$$,• Set

• Funtion:• hidesthecommandline• mustassigntoshellvars

Page 39: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

BuildingApplicationsonLinuxToolChainOverviewandComponent

Binutils,Kernel-header,GCC,Library,Debugger,Vendor&PreBuilt

Page 40: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Definition

• TheusualdevelopmenttoolsavailableonaGNU/Linuxworkstationisanativetoolchain

• Thistoolchainrunsonyourworkstationandgeneratescodeforyourworkstation,usuallyx86

• Forembeddedsystemdevelopment,itisusuallyimpossibleornotinterestingtouseanativetoolchain• Thetargetistoorestrictedintermsofstorageand/ormemory• Thetargetisveryslowcomparedtoyourworkstation• Youmaynotwanttoinstallalldevelopmenttoolsonyourtarget.

• Therefore,cross-compilingtoolchains aregenerallyused.Theyrunonyourworkstationbutgeneratecodeforyourtarget.

Page 41: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Environment

x86

ARMx86

Compilationmachine

Execution machine

Sourcecode

NativetoolchainCross-compiling

toolchain

x86binary ARMbinary

Page 42: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Components

Binutils Kernelheaders

C/C++libraries GCCcompiler

GDBdebugger(optional)

Page 43: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Binutils

• Binutils isasetoftoolstogenerateandmanipulatebinariesforagivenCPUarchitecture• as,theassembler,thatgeneratesbinarycodefrom

assemblersourcecode• ld,thelinker• ar, ranlib,togenerate.a archives,usedfor

libraries• objdump, readelf, size, nm, strings,

toinspectbinaries.Veryusefulanalysistools!• strip,tostripuselesspartsofbinariesinorderto

reducetheirsize• http://www.gnu.org/software/binutils/• GPLlicense

Page 44: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Kernelheaders(1)

• TheClibraryandcompiledprogramsneedstointeractwiththekernel• Availablesystemcallsandtheir

numbers• Constantdefinitions• Datastructures,etc.

• Therefore,compilingtheClibraryrequireskernelheaders,andmanyapplicationsalsorequirethem.

Kernel

Kernelheaders

CLibrary

Applications

• Available in <linux/...> and <asm/...> and a few other directories corresponding to the ones visible in include/ in the kernel sources

Page 45: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Kernelheaders(2)

• Systemcallnumbers,in<asm/unistd.h>

• Constant definitions, here in <asm-generic/fcntl.h>, included from <asm/fcntl.h>, included from <linux/fcntl.h>

• Data structures, here in <asm/stat.h>

#define __NR_exit 1#define __NR_fork 2#define __NR_read 3

#define O_RDWR 00000002

struct stat {unsigned long st_dev;unsigned long st_ino;

[...]};

Page 46: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Kernelheaders(3)

• Thekernel-to-userspace ABIisbackwardcompatible• Binariesgeneratedwithatoolchain usingkernelheadersolder

thantherunningkernelwillworkwithoutproblem,butwon'tbeabletousethenewsystemcalls,datastructures,etc.

• Binariesgeneratedwithatoolchain usingkernelheadersnewerthantherunningkernelmightworkoniftheydon'tusetherecentfeatures,otherwisetheywillbreak

• Usingthelatestkernelheadersisnotnecessary,unlessaccesstothenewkernelfeaturesisneeded

• Thekernelheadersareextractedfromthekernelsourcesusingtheheaders_install kernelMakefile target

Page 47: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

GCCcompiler

• GNUCCompiler,thefamousfreesoftwarecompiler

• CancompileC,C++,Ada,Fortran,Java,Objective-C,Objective-C++,andgeneratecodeforalargenumberofCPUarchitectures,includingARM,AVR,Blackfin,CRIS,FRV,M32,MIPS,MN10300,PowerPC,SH,v850,i386,x86_64,IA64,Xtensa,etc.

• http://gcc.gnu.org/• AvailableundertheGPLlicense,

librariesundertheLGPL.

The image part with relationship ID rId4 was not found in the file.

Page 48: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Clibrary

• TheClibraryisanessentialcomponentofaLinuxsystem• Interfacebetweentheapplications

andthekernel• Providesthewell-knownstandardC

APItoeaseapplicationdevelopment

• SeveralClibrariesareavailable:glibc,uClibc,eglibc,dietlibc,newlib,etc.

• ThechoiceoftheClibrarymustbemadeatthetimeofthecross-compilingtoolchaingeneration,astheGCCcompileriscompiledagainstaspecificClibrary.

Kernel

CLibrary

Applications

Page 49: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

glibc

• http://www.gnu.org/software/libc/• License:LGPL• ClibraryfromtheGNU project• Designedforperformance,standardscomplianceand

portability• FoundonallGNU/Linux hostsystems• Ofcourse,activelymaintained• Quitebigforsmallembeddedsystems:approx2.5MBonarm (version2.9- libc:1.5MB,libm:750KB)

The image part with relationship ID rId4 was not found in the file.

Page 50: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Using the Toolchain

build host target

Native buildused to build the normal gcc of a

workstation

build host target

Cross buildused to build a toolchain that runs on

your workstation but generates binaries for the target

The most common solution in embeddedThe most common solution in Enterprise

Page 51: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Experimentonfollowing

• Gcc ccompiler• Ld gnulinker• As assembler• Size infooncs/ds• Nm symbolicinfo(var/codecommnets/…)• Readelf infoonfile• Strip removethedebugginginfo• Objdump disassemblyinfo• Strace systemcalltrace• Objcopy exe/binay copy/conversion• Ar createarchive(libraray)• Ranlib indeding ofarchive• Make automatethebuild• Ldd infoonlibraryfortheexe• Ldconfig pathsedits

Somesupportingutilitiescanbealsotriedoutstat,file,diff,cmp,comm,patch,wc,nl,bc,script,sdiff,vimeditorwithcscope isagoodchoicefordevelopers

Page 52: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

BuildLifecycleofanImage

SourceProgram

Preprocessorcpp / gcc -E

Compilercc1 / gcc -S

AssemblyCode Assembler

as / gcc -c

ObjectProgram

Linkerld / gcc -l

ExecutablesLoader

Page 53: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

ApplicationBuildstyles

• DynamicBuild• defaulttheprocessisbuildwithdynamicdependencies.• Itmeans,itusessharedlibraryfortheexetoloadcertainserviceatloadtime.Example:$gcc sample.c –osample.exe$ldd ./sample.exeLinux-gate.so.1=>(0xb7776000)libc.so.6=>/lib/i386-linux-gnu/libc.so.6(0xb75a9000) /lib/ld-linux.so.2(0xb7777000)

• StaticBuild• Iftheprocessisbuildwithstaticbuild,thereisnodynamicdependency.• Itmeans,itusesstaticlibraryfortheexe.

• Thisisfastbutoccupiedalotofspace.static build

• $gcc -staticsample.c -ossample.exe

Page 54: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

ExecutableImageonstaticanddynamicbuild

App1 App2 AppN

lib1.a lib1.a lib1.a

lib2.a lib2.a lib2.a

App1 App2 AppN

linux-gate.so.1

libc.so.6

ld-linux.so.2

Page 55: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Programmer’sviewofProgram

.stack

.heap

Environmentvariables

.bss

.text

.rodata

.data

_end_edata_etext

Page 56: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

ExecutableandLinkerFormat

Page 57: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

MaintainingSTPsStaticlibrary

DynamiclibraryRealname

LD_LIBRARY_PATHProductionreadywithldconfig

SonameandversioningtechniquesUsingdynamiclinkerasanAPIusinglibdl.so

LD_PRELOADDo’sandDon’tinSharedLibraries

Page 58: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

LIBRARIES

• Staticlibraries• special“archivefiles”• haveextension’.a’• createdfromobjectfilesusingGNUarchiver ‘ar’• usedbylinkertoresolvereferencestofunctionsatcompile

time

• Sharedlibraries• haveextension’.so’• preferredoverstaticlibraries• Memoryoptimises• Canbebuildintwoways

• Realname• Soname

Page 59: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

LIBRARIES

• GNUar tocreateastaticlibrary:$gcc -Wall-c-ohello.o hello.c

• $ar cr libhello.a hello.o• The‘cr’standsfor“createandreplace”

• The“tableofcontents”option‘t’canlisttheobjectfilesinanexistinglibrary

• $ar tlibhello.ahello_fn.obye_fn.o

• $gcc main.c /tmp/tmp/test/libhello.a -omain• $./main• Hello,everyone!

Page 60: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

LIBRARIES

• /*calc.c */• #include<math.h>• #include<stdio.h>

• int main(void){

• doublex=sqrt (2.0);printf ("Thesquarerootof2.0is%f\n",x);

• return0;• }

Page 61: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

LIBRARIES

• $gcc -Wallcalc.c -ocalc• /tmp/ccbR6Ojm.o:Infunction‘main’:• /tmp/ccbR6Ojm.o(.text+0x19):undefinedreferenceto‘sqrt’•

• ‘/tmp/ccbR60jm.o’isatemporaryobjectfilecreatedforlinking• Alibraryshouldappearafteranysourcefilesorobjectfiles

• $gcc -Wallcalc.c /usr/lib/libm.a -ocalc

Page 62: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

LIBRARIES

• -lNAME willlinkobjectfileswithlibraryfile‘libNAME.a’inthestandardlibrarydirectories

• $gcc -Wallcalc.c -lm-ocalc• Iflibrarylglpk usesanddependsonlmlibrary,itmustappearbeforelm

• $gcc -Walldata.c -lglpk -lm• Notallcompilerssearchalllibraries,soorderlibrariesfromlefttoright

Page 63: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Libraries

•Alibraryisacollectionofsubprogramsusedtodevelopsoftware.•Allowscodeanddatatobereused,shared andchanged inamodularfashion.

•Linking:Alinkerresolvesthereferencesbetweenexecutables andlibraries.

Page 64: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

BenefitsofUsingLibraries

•SoftwareEngineeringPerspective:• Increasingthereusability ofcommonroutines.•Easytoupgradebychanging thelibrariesonly.

•SystemUtilizationPerspective:•Thecodesegmentcanbesharingatruntime;decreasetheconsumeofmemoryanddiskspace.

Page 65: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

GNUBinaryUtilitiesusedwithlib

• strings:displayallprintablecharacters.• ar:createstatic-linkinglibraries.• nm:listsymbolsfromobjectfiles.• size:listsectionsizesandtotalsizes.• readelf:• objdump:• ldd• ldconfig

Page 66: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

PrintSharedLibraryDependencies

• UNIXPlatform> ldd /bin/bash

linux-gate.so.1 => (0xffffe000)

libncurses.so.5 => /lib/libncurses.so.5 (0xb7f1d000)

libdl.so.2 => /lib/libdl.so.2 (0xb7f19000)

libc.so.6 => /lib/libc.so.6 (0xb7dfb000)

/lib/ld-linux.so.2 (0xb7f61000)

• WindowsPlatform• PEViewerorPEExplorer• PE:PortableExecutable

Page 67: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Smallerismoreefficient

objjectfile

functionlibrary

objectfile

pointer

staticlinking

objectfile

functionlibrary

dynamiclinking

objectfile

pointer

sharedfunctionlibrary

executablefiles

Page 68: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

FromSourcetoExecution

SourceProgram

Preprocessorcpp / gcc -E

Compilercc1 / gcc -S

AssemblyCode Assembler

as / gcc -c

ObjectProgram

Linkerld / gcc -l

ExecutablesLoader

static-linking

dynamic-linking

Page 69: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

CategoriesofLibraries(bylinkingtime)

•Staticlinkinglibraries•Dynamiclinkinglibraries

•Run-TimeEnvironmentlibraries•ProgrammingLanguagelibraries

Page 70: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

StaticLinkingLibraries

•Thecodesegmentswillbecopytoeachexecutables

•Pros:•Easytouse;nodependencyproblemaftercompilation.

•Cons:•Theexecutablesizewillbelarger.•Requirere-linkingwhenlibrarieschanged.

Page 71: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

DynamicLinkingLibraries(1/2)

• Allowmultipleprocessestosharethesamecodesegment.• Pros:

• Greaterflexibility• Possiblesupportforplugins.

• Cons:• Slowapplicationatstarttime.• Dependentonthelibrarieswhenexecution.

Page 72: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

DynamicLinkingLibraries(2/2)

•Thereferencescanberesolvedeitherat:•Load-time•Run-time

Page 73: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

LocationofLibraries

•UNIXPlatform• /lib:runtimeenvironmentlibraries• /usr/lib:forprogramdevelopment

Page 74: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

LinkingwithCRuntimeLibraries

•StaticLinking• gcc–static –ohello-shelloworld.c/usr/lib/libc.a• hello-s:521,238bytes

•DynamicLinking• gcc–ohello-dhelloworld.c• hello-d:6,020bytes

•TheCRTlibrariesconsume515,218bytes.

Page 75: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Static-LinkingLibraries

•Build•gcc –cmystaticlib.c•ar –rmystaticlib.a mystaticlib.o

•Usage• (sameasusingCruntimelibraries)

Page 76: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Createtheobjectmodulesusing–fPIC

• $gcc -fPIC -g-c-Wallmod1.cmod2.cmod3.c• -fPIC (PositionIndependentCode)causescompilertogeneratecodethatcanbeloadedanywhereinvirtualmemoryatrun-time.

• Createthesharedlibrary:• $gcc -shared-olibfoo.so mod1.omod2.omod3.o

• Usualnamingconvention:libname.so[.version]

• Linkprogramagainstlibrary:• $gcc -g-Wall-oprog prog.c libfoo.so

• or:• $gcc -g-Wall-oprog prog.c -L.-lfoo

• Thisstepembedsnameofsharedlibraryinsideexecutablefile.

Page 77: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Run?

• Butwhenwetrytoexecutetheprogram:

• $./prog• ./prog:errorinloadingsharedlibraries:• libfoo.so:cannotopensharedobjectfile:• Nosuchfileordirectory

• Thelibrary"libfoo.so"couldnotberesolvedatrun-timebythedynamiclinker(aka:dynamiclinkingloader).

Page 78: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

TheDynamicLinker

• Examinessharedlibrarydependenciesinexecutablefileand• Loadssharedlibrariesintomemory(iftheyarenotalready);• ItisitselfasharedlibrarywhichispartofeveryELFexecutableusing

sharedlibraries:/lib/ld-linux.so• Itappliesasetofrulestofindlibrariesreferencedbytheprogram.• Therulesspecifyasetofstandarddirectories.

• (Forexample,manysharedlibrariesresidein/liband/usr/lib.)

• Theerrormessageearlieroccurredbecauseourlibraryisinthecurrentdirectory,whichisnotpartofstandardlist

Page 79: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

LD_LIBRARY_PATH

• Weneedtogivethedynamiclinkerinformationonhowtofindoursharedlibraryatrun-time

• Onesolution:LD_LIBRARY_PATH.• Setthisenvironmentvariabletoalistofcolon-separateddirectories.• Dynamiclinkersearchesthesedirectoriesbeforelookinginstandardlibrarydirectories.

• $LD_LIBRARY_PATH=../prog• Calledmod1-x1• Calledmod2-x2

• Note:productionapplicationsshouldnotuseLD_LIBRARY_PATHas• Usersshouldnothavetoknowwherethelibraryislocated

Page 80: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Thesharedlibrarysoname

• Intheearlierexample,weembeddedtheactualname(therealname)ofthesharedlibraryinanexecutablefile.

• Itispossibletocreateanalias,calledthesoname,whichwillbeembeddedinanexecutablefileinsteadoftherealname.

• Atrun-time,thedynamiclinkerwillusethesoname whensearchingforthelibrary.

• Thepurposeofthesoname istoprovidealevelofindirection.• Atrun-time,executablecanuseaversionofthesharedlibrarythat

isdifferent(butcompatible)fromthatagainstwhichitwaslinked.

Page 81: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

howtouseasoname

• Specifysoname whencreatingsharedlibrary:• $gcc -fPIC -c-Wall-gmod1.cmod2.cmod3.c• $gcc -shared-Wl,-soname,libbar.so -olibfoo.so \• mod1.omod2.omod3.o• -Wl,-soname,libbar.so instructslinkertomarkthesharedlibrarylibfoo.sowiththesoname libbar.so.

• Createexecutable:• $gcc -g-Wall-oprog prog.c libfoo.so

• Linkerdetectsthatlibfoo.so containsthesoname libbar.so andembedsthelatternameinsidetheexecutable.

Page 82: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Runtheprogram

• $LD_LIBRARY_PATH=. ./prog• ./prog:errorinloadingsharedlibraries:• libbar.so:cannotopensharedobjectfile:• Nosuchfileordirectory• Dynamiclinkercannotfindanythingnamedlibbar.so.

• Createasymboliclinkfromthesoname totherealnameofthelibrary:

• $ln -slibfoo.so libbar.so• $LD_LIBRARY_PATH=. ./prog

• Calledmod1-x1• Calledmod2-x2

• Atrun-timethislinkcanpointtoaversionofthelibrarywhichisdifferentfromtheversionagainstwhichlinkingwasperformed.

Page 83: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Sharedlibraryversionsandnaming

• Ifanewversionofasharedlibraryiscompatible withanexistinglibrary,wecanmakeanewminorversion ofthelibrary.

• Ifanewversionofasharedlibraryisincompatible withanexistinglibrary,wemustmakeanewmajorversion ofthelibrary.

• Constraint:itmustbepossibletocontinuerunningprogramsrequiringtheolderversionofthelibrary.

• Solution:anamingconvention isusedforsharedlibraryrealnamesandsonames.

Page 84: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

RealnameREALNAMEisNameofthefilecontaininglibrarycode.Format:libname.so.major-id.minor-id

• Majorversionidentifierisanumberwhichissequentiallyincrementedwitheachincompatiblereleaseofthelibrary.

• Minorversionidentifierdistinguishesdifferentcompatibleminorversionsofalibrarywithinthesamemajorversion.

• Usuallyeitheranumber,ortwonumbersseparatedbyadot,withfirstnumberidentifyingminorversion,andsecondnumberindicatingapatchlevelorrevisionnumberwithintheminorversion.

Examples:• libdemo.so.1.0.1• libdemo.so.1.0.2• libdemo.so.2.0.1• libreadline.so.4.0

Page 85: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

SonameFormat:libname.so.major-id• soname includesthesamemajorversionidentifier ascorrespondingrealname,

butdoesnotincludeminorversion identifier.

Purpose:run-timeloadingisdependentonlyonmajorversionnumberofthelibrary• soname iscreatedasasymboliclink (usuallyinsamedirectoryasrealname).• Thesoname foreachmajorlibraryversionpointstomostrecentminorversion.• Sinceitisthesoname (nottherealname)thatisembeddedinexecutableby

linker:Atanytime,wecanchangesoname symboliclinktopointtoanewerminorversion.

• Differentmajorversionscanco-exist andbeaccessedbytheprogramsthatrequirethem.

Examplesofsonames (alongwiththerealnamestowhichtheymightbesymbolicallylinked):

• libdemo.so.1->libdemo.so.1.0.2• libdemo.so.2->libdemo.so.2.0.1• libreadline.so.4->libreadline.so.4.0

Page 86: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Linkername

LinkernameFormat:libname.so

Purpose:allowsustoconstructversion-independentlinkcommands whichautomaticallyoperatewiththeright(i.e.mostuptodate)versionofthesharedlibrary.

Createdasasymboliclink toeitherrealname orsoname ofmostrecentmajorversionofthelibrary.

Moreconvenienttohaveitpointtosoname.

Examples:

libdemo.so ->libdemo.so.2Libreadline.so ->libreadline.so.4

Page 87: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

createasharedlibraryusingstandardnamingconventions

Createthesharedlibrarywithrealnamelibdemo.so.1.0.1andsoname libdemo.so.1.$gcc -fPIC -g-c-Wallmod1.cmod2.cmod3.c$gcc -shared-Wl,-soname,libdemo.so.1-olibdemo.so.1.0.1\

mod1.omod2.omod3.oCreatesymboliclinksforthesoname andlinkername:$ln -slibdemo.so.1.0.1libdemo.so.1$ln -slibdemo.so.1libdemo.so$ls -llibdemo.so*|cut-c1-11,55- #Verifythesetup

lrwxrwxrwx libdemo.so ->libdemo.so.1lrwxrwxrwx libdemo.so.1->libdemo.so.1.0.1-rwxr-xr-xlibdemo.so.1.0.1

Buildexecutableusingthelinkername:$gcc -g-Wall-o./prog prog.c -L.-ldemoRuntheprogramasusual:$LD_LIBRARY_PATH=../progCalledmod1-x1Calledmod2-x2

Page 88: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

DynamicloadingwithLinux

Function Descriptiondlopen Makesanobjectfileaccessibletoaprogramdlsym Obtainstheaddressofasymbolwithinadlopened objectfiledlerror Returnsastringerrorofthelasterrorthatoccurreddlclose Closesanobjectfile

Page 89: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Description

#include<dlfcn.h>

void*dlopen(const char*file,int mode);WithahandletotheELFobject,youcanidentifyaddressestosymbolswithinthisobjectusingthedlsym call.Thisfunctiontakesasymbolname,suchasthenameofafunctioncontainedwithintheobject.Thereturnvalueisaresolvedaddresstothesymbolwithintheobject:void *dlsym(void *restrict handle,const char *restrict name );IfanerroroccursduringacallwiththisAPI,youcanusethedlerror functiontoreturnahuman-readablestringrepresentingtheerror.ThisfunctionhasnoargumentsandreturnsastringifapriorerroroccurredorreturnsNULLifnoerroroccurred:char *dlerror();Finally,whennoadditionalcallstothesharedobjectarenecessary,theapplicationcancalldlclose toinformtheoperatingsystemthatthehandleandobjectreferencesarenolongernecessary.Thisisproperlyreference-counted,sothatmultipleusersofasharedobjectdonotconflictwithoneanother(itremainsinmemoryaslongasthereisauserforit).Anysymbolsresolvedthroughdlsym fortheclosedobjectwillnolongerbeavailable.char*dlclose(void*handle);

Page 90: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

DynamicallyLoaded(DL)Libraries

• Dynamicallyloaded(DL)librariesarelibrariesthatareloadedattimesotherthanduringthestartupofaprogram.

• They'reparticularlyusefulforimplementingpluginsormodules,becausetheypermitwaitingtoloadthepluginuntilit'sneeded.

• Forexample,thePluggableAuthenticationModules(PAM)systemusesDLlibrariestopermitadministratorstoconfigureandreconfigureauthentication.

Page 91: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Usingreadelf forinfo

$ldd$readelf -ldl

ElffiletypeisEXEC(Executablefile)Entrypoint0x8048618Thereare7programheaders,startingatoffset52

ProgramHeaders:TypeOffsetVirtAddr PhysAddr FileSiz MemSiz Flg AlignPHDR0x0000340x080480340x080480340x000e00x000e0RE0x4INTERP0x0001140x080481140x080481140x000130x00013R0x1[Requesting programinterpreter:/lib/ld-linux.so.2]

LOAD0x0000000x080480000x080480000x009580x00958RE0x1000LOAD0x0009580x080499580x080499580x001200x00128RW0x1000DYNAMIC0x00096c0x0804996c0x0804996c0x000d00x000d0RW0x4NOTE0x0001280x080481280x080481280x000200x00020R0x4GNU_STACK0x0000000x000000000x000000000x000000x00000RW0x4

$

Page 92: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

TestingEmbeddedApplication

QEMUCrossApplications

Page 93: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Qemu

Greattoolforembeddeddevelopers

Page 94: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

Whatisqemu

• QuickEMUlator”isaprocessoremulatorthatreliesondynamicbinarytranslationtoachieveareasonablespeedwhilebeingeasytoporttonewhostCPUarchitectures• Whenusedasamachineemulator,QEMUcanrunOSes andprograms

madeforonemachine• EX:ARMboardonadifferentmachine(e.g.yourownPC).• Byusingdynamictranslation,itachievesverygoodperformance.

• Whenusedasavirtualizer,QEMUachievesnearnativeperformancesbyexecutingtheguestcodedirectlyonthehostCPU.• WhenusingKVM,QEMUcanvirtualizex86,serverandembedded

PowerPC,andS390guests.

Page 95: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

TypicalSetup

GetQEMUConfigureQEMUforKVM

Build&InstallTesttheQEMU

GettoolchainConfiguretoolchain

Build&InstallTesttoolchain

Requirement/BoardspecificconfigurationConfigure,build&testyourkernelConfigure,build,&testfilesystem

Build&testbareapps

1 2

3

Page 96: ESSENTIAL Linux For EMBEDDED Developers · 2018. 9. 20. · • The usual development tools available on a GNU/Linux workstation is a native toolchain • This toolchain runs on your

TestApplicationonemulator

• arm-none-linux-gnueabi-gcc sample.c –osample.arm

• Qemu-arm–L/path_to_cross_sdk/arm…/libc/libsample.arm