Am not able to call C++ function pointers from inline assembly

文章推薦指數: 80 %
投票人數:10人

Stack Overflow for Teams – Start collaborating and sharing organizational knowledge. Create a free Team Why Teams? ... Connect and share knowledge ... Resultsfromthe2022DeveloperSurveyarenowavailable ArduinoStackExchangeisaquestionandanswersitefordevelopersofopen-sourcehardwareandsoftwarethatiscompatiblewithArduino.Itonlytakesaminutetosignup. Signuptojointhiscommunity Anybodycanaskaquestion Anybodycananswer Thebestanswersarevotedupandrisetothetop Home Public Questions Tags Users Companies Unanswered Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore AmnotabletocallC++functionpointersfrominlineassembly AskQuestion Asked 2yearsago Modified 2yearsago Viewed 248times 1 Duetosomecuriosity,IwastryingtousesomeassemblywithmyArduinoMEGA2560. Iamnotabletoinvokeafunctionfromac++functionpointerarray. WhenIuncommentthecallfunction,func_aruns.However,whenIalmostreproducetheassembly,itdoesntwork. Example: extern"C"void__attribute__((used,noinline,noreturn))func_a(); typedefvoid(*volatilefunc_ptr)(); func_ptrtasks[MAX_TASKS]={&func_a}; extern"C" void__attribute__((used,noinline))call(func_ptr*ptr){ (*ptr)(); } void__attribute__((noreturn,used))setup(){ //call(tasks); asmvolatile( "ldsr26,(tasks)\n" "ldsr27,(tasks+1)\n" "ldr30,X+\n" "ldr31,X\n" "eijmp\n" ); } Generatedassemblyrecoveredfromavr-objdump 000001c6: 1c6:a0910002ldsr26,0x0200;0x800200 1ca:b0910102ldsr27,0x0201;0x800201 1ce:ed91ldr30,X+ 1d0:fc91ldr31,X 1d2:1994eijmp 1d4:0895ret 000001d6: 1d6:dc01movwr26,r24 1d8:ed91ldr30,X+ 1da:fc91ldr31,X 1dc:1994eijmp AnspecificresourcesIshouldreferforthingslikethis? Ifitmatters,I'musingplatformioonalinuxsystemforcompilation. c++atmega2560assembly Share Improvethisquestion Follow askedJun18,2020at10:48 darkspinedarkspine 11344bronzebadges Addacomment  |  2Answers 2 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 3 Itseemsyougotconfusedbythepointerindirections,whichis confoundedbytheimplicitindirectionsmadebythecompiler. Here: extern"C" void__attribute__((used,noinline))call(func_ptr*ptr){ (*ptr)(); } Theparameterptrisnotafunctionpointer:it'sapointertoa functionpointer.Youhavetodereferenceittwiceinordertogetthe function:(**ptr)();.Notethatthecompilerimplicitlydereferencesa functionpointerifyoucallitlikeafunction:that'swhyyougetno errorbyexplicitlydereferencingthepointeronlyonce.Inthe generatedassembly,thelines ldr30,X+ ldr31,X dereferenceptrinordertogettheaddressofthefunctiontocall. Youprobablywantedtowrite extern"C" void__attribute__((used,noinline))call(func_ptrptr){ ptr(); } Andthenuseitas: call(tasks[0]); Ifyoujustcall(tasks),thearrayidentifierdecaystopointer,and thecompilerhandlesthisasashortcutforcall(&tasks[0]);,which turnsouttobecompatiblewithyourinitialimplementationofcall(). Now,inyourinlineassemblyyouhave ldsr26,(tasks) ldsr27,(tasks+1) Theassemblytreatstasksasasymbolrepresentingtheaddressof thetasksarray.Thelinkerreplacesthosesymbolsbytheactual address(0x0200).ThoseinstructionsreadtheRAMatthisandthe followingaddress.TheseslotsofRAMholdthefirstitemofthearray, namely&func_a.SonowyouhavethisaddressintheXregisterpair. NoneedtoreadRAMagain:youcanmovwr30,r26anddotheindirect jump.Or,betteryet,loadintoZtobeginwith: ldsr30,(tasks) ldsr31,(tasks+1) eijmp SeealsoMajenko'sanswer:hereIamassumingEINDissomehow correctlysetuptobeginwith.OnanUno,youwouldjustuseijmp insteadofeijmpandnotworryaboutEIND. Share Improvethisanswer Follow answeredJun18,2020at13:17 EdgarBonetEdgarBonet 36.2k44goldbadges3333silverbadges7171bronzebadges 2 Thatkindofeplainedthings.WhenIused(tasks)intheasm,Iexpectedittoloadtheaddressofthefirstelementofthearrayandnotthevaluepointedtobyit.Imnotsurehowtodothat.MaybeIwillhavetounderstandtheextendedasmsyntax. – darkspine Jun19,2020at5:18 @darkspine:Youcanloadtheaddressoftaskswith,e.g.,ldir26,lo8(tasks)\nldir27,hi8(tasks).Unlikelds,theldiinstructiondoesnotaccesstheRAM,astheaddressisknownatbuildtimeandfilled-inbythelinker. – EdgarBonet Jun19,2020at7:33 Addacomment  |  2 IwillstartoffbysayingthatIamnoexpertinAVRassembly,soIhavenoideaifanyofthisisactuallycorrect.HoweverfromreadingthevariousdocumentsonthesubjectIhavegleaned: OntheATMega2560EIJMPusesacombinationofboththeZregisterandtheEINDregistertoformafulladdress. ThatmeansthataswellassettinguptheZregisterforthelower16bitsoftheaddressyoualsohavetosetuptheEINDregisterfortheupper5bitsoftheaddress. IndirectjumptotheaddresspointedtobytheZ(16bits)PointerRegisterintheRegisterFileandtheEINDRegisterintheI/Ospace.Thisinstructionallowsforindirectjumpstotheentire4M(words)Programmemoryspace. Itthengoesontoshowanexample: ldir16,$05;SetupEINDandZ-pointer outEIND,r16 ldir30,$00 ldir31,$10 eijmp;Jumpto$051000 HowyoudeterminewhattheEINDregistershouldbe?Well,ingeneralyoudon't.Youwouldn'tuseEIJMP.FromwhatIunderstandforfunctionsoutsidethelower64kwordsofaddressspacethecompilerbuildsa"jumptable"whichisstoredinthelowerareaofmemory.YoujumptotheentryinthattablewithIJMPandthattablethenjumpstothefinaldestinationwithEIJMPforyou. Doingthiskindofjumpinginassemblyisn'treallyanicethingtotryandfigureout.It'smessy.BettertoletthecompilerdoitforyouanduseCratherthanassembly.TheAVR-GCCguysputalotofworkintomakingfunctionpointersworkcorrectly(fromwhatIhavereaditwasn'teasyevenforthem),andyou'rejustre-inventingthewheel. Attheveryleastyoushouldimplementyourcode100%inCtobeginwiththenlookatthecompiledoutputtoseehowthecompilerthinksitshouldbedone. Share Improvethisanswer Follow answeredJun18,2020at12:58 Majenko♦Majenko 102k55goldbadges7070silverbadges128128bronzebadges 1 1 Iswitchedtoeijmpbecausethatswhatgccwasusing.Theproblemturnedouttobethattasksisdereferencedwhenusingitintheasm.Also,thanksforthedocument,ItsmuchmoreverbosethantheATMega2560datasheet. – darkspine Jun19,2020at5:20 Addacomment  |  YourAnswer ThanksforcontributingananswertoArduinoStackExchange!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedc++atmega2560assemblyoraskyourownquestion. TheOverflowBlog Askedandanswered:theresultsforthe2022Developersurveyarehere! LivingontheEdgewithNetlify(Ep.456) FeaturedonMeta Testingnewtrafficmanagementtool Upcomingcleanupofduplicatevotes Sitedesignandlogo—Draft Related 3 Storinginaglobalvariableusinginlineassembly 3 Understandinghowmethodsandpointersinsideafunctionwork 7 AccessingaC++staticvariablefromgccinlineasm 1 Dynamicallymodifyingthecallstackusingpointers 2 HowdoIconvertthisprogramtoassemblyfromc++ 0 Returningstructfromfunctiongenerates'doesnotnameatype'compilationerror 0 LEDBlinkinassemblywithtimer1outputcompareinterruptnotworking 0 ParallelI/O-maybeuseMachinecodefunctioncall HotNetworkQuestions ArrayaccessisO(1)impliesafixedindexsize,whichimpliesO(1)arraytraversal? WhatcountsasawordforthepurposesofSending? Hiomneslingua:Whylinguaisputinsingular? Checkamushroomforest ProtectingSmokeAlarmRelayfromLarge(6.5amp@120V)InductiveLoad Howtoapplyudevruletoanon-partitionedlocaldisk? Isitacceptabletoincludeinformationinaposterthatwasn'tinthepublication? Children’sbookwithamousecalledNils 14/3fordual120appliance WhatcanIdoifaflightdelaymakesmemissthetransferfromtheairport? Doesthiscountasdeniedentry? HowtoinfluencethematerialwithGeometryProximity? HowtocreateanatomicheadortreatsomeheadasatomicduringMap? Ican'tfindtheGeoreferencer Docountries(withruleoflaw)existwhereacourtcanrequirethelegislaturetovoteonalawinordertoclearambiguities? Iboughtmyfirstroadbike,andithurtsmybackandhands Whydoesthegovernmentnotintroduceanamendmenttotheconstitutiontoallowabortion? HowdoImakeaprogramquitwith"q"andrestoretheconsolelike"man"does? Isthereanysign"theWest"isdeliberatelytryingtoprolongfightinginUkraineforthesakeoffighting? TCP-WhydoRSTpacketsnotrequireacknowledgements(andFINpacketsdo)? Howwouldyoustandardizeon-callexpectationsacrosssoftwareteamswhenthey'vedivergedatthesamesalarylevel? Thebestwaytopreparetheundergraduatestudentbeforeenteringthescientificresearch Couldsomeonepleaseexplainthewordorderhere? Can"due"meaning"owed"beusedwithout"to"inAmE?e.g."therecognitionwhichwasdueher" morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cpp Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?