Git Product home page Git Product logo

soleen / linux-kernel-module-cheat Goto Github PK

View Code? Open in Web Editor NEW

This project forked from ************/linux-kernel-module-cheat

1.0 0.0 0.0 13.17 MB

The perfect emulation setup to study and develop the Linux kernel v5.4.3, kernel modules, QEMU, gem5 and x86_64, ARMv7 and ARMv8 userland and baremetal assembly, ANSI C, C++ and POSIX. GDB step debug and KGDB just work. Powered by Buildroot and crosstool-NG. Highly automated. Thoroughly documented. Automated tests. "Tested" in an Ubuntu 19.10 host.完美的仿真设置,可用于研究和开发Linux内核v5.4.3,内核模块,QEMU,gem5和x86_64,ARMv7和ARMv8用户界面以及裸机装配,ANSI C,C ++和POSIX。 GDB步骤调试和KGDB可以正常工作。 由Buildroot和crosstool-NG支持。 高度自动化。 彻底记录。 自动化测试。 在Ubuntu 19.10主机中经过“测试”。21世纪新政宣言(2020年4月5曰笫四次修改稿)(2020年6月19曰第七次修改,以下“【】”内文字为非正文内容的说明)20世纪苏联的消亡和东欧的大变革,使这21世纪初的现**大陆成为世界关注的最主要焦点和影响新世纪文明发展的关键。特别是大陆这些年对外意识形态渗透,震撼整个世界。美中贸易战实际已打响人类意识形态领域最后的冷战,海峡两岸关系恶化,香港不断的百万人游行,南海邻国关系紧张。大陆经济急速下滑衰退,内外矛盾激化高端深感前所未有的生存危机。包括**上下在内的几乎所有人都很清楚,大陆已到非政治体制改革而不可的时候了,大变革将是民意世潮下的必然结局。**大陆内外即全球正合力促成这人口第一大国的大变革,这也为**开创新政提供了一次最佳机会。综合各政体和各国现实,绝大多数国家改革选择了西方**政体,但其固有的越来越明显的缺陷已成为有人攻击、拒绝或怀疑的理由。这也是近年来西方国家出现了宽容那必将灭亡的**专制政府的左翼当选,是不少选民失去信心的表现和原因。不仅如此,西方现**制的缺陷还有: 很难产生最佳决策而大多是不优不劣成心对抗后的折衷方案使施政不理想选民失去信心;财团商界巨头对政治影响过大;对立政党轮流执政决策易翻来覆去劳民伤财前后混乱选民也易失去信心; 并不只是几人而是几党几大群体竟争最高权力,强对抗易使社会撕裂更易使选民失望;另外还有竞选的形象口才和资金作用偏重,不利于博才寡言的理论家和不利于无大财团资助的竞选人;大多数博才的却不善辩的竞选人易被仅仅是形象口才好的竞选人击败等等;最明显的例子,就是西式政体在伊拉克之类的国家就完全失败,根本无法解决誓不两立的多党多教派的执政问题,还有西方政客易被共党惯用的手段暗地收买,如WHO、VOA等机构和政党的要员被收买为**制辩护或服务,或为打击政敌和政党利益而丢弃原则不顾国家利益;而实西式的治国非举贤制度对国家不是很有利,这西式**制也势必改革。另外,美国无限自由混血的全国灰色人种化,结果显而易见,若干年后美国将没有白种人黄种人和黑种人,全是“灰色“人种。是一例纯种人的自寻消失,一国还可,他国不可推广,物种特别是人种的保护更为重中之重!旨为人类非灰一色的丰富多彩而圆满理想的未来,所以“美国模式”并非最佳榜样。**是影响新世纪文明发展的关键,人们也普遍希望**大变革应该和平过渡避免付出巨大社会成本和沉重代价,新世纪社会变革更要终止杀人流血。旨在也包括左翼的更多**人欢迎和接受的, 不完全西化中西结合的,有利两岸和平统一的,最佳选择必是都相聚在**也一惯崇敬的孙中山先生的旗帜下,完善健全和发展孙中山的五权分立体制。这一使命由**真改革派完成所付代价则最小,应当引起他们的高度关注,劝其为国为民勇于担当。 倒退则是自取灭亡,必是遗臭万年的大罪人。**改革派和大多数党员也不会愿意被往往只可能得势一时的倒退势力捆绑连累,**改革派要去做的第一件事是促成落实**曾在联合国签署的《世界人权宣言》包括**所立宪法的基本人权和自由。【**也许有人会说这是使党变色,那这几十年变的色还少吗?不是那些名“社”实“资”的变色不就早和前东欧苏联一样完蛋了吗?既是如此无可否认就再变最后一次又何妨?而且已是面临无法逃避的大变革前夜,天堂与地狱只一念一步之差!】只有**完成了顺民意世潮的大变革,才是21世纪文明的开始。改革西方**制,是加入东方元素,将孙中山先生的西式政党政治较浓厚的五权分立体制,进一步改革为不完全政党政治,突显**史来长期无政党执政的传统,**古代就有“结党营私”一说。所有政党社团参政议政,无执政党和在野党之分, 避免执政党自身权益高于一切的政党政治弊病。除了那拒绝政改变革而要倒退的是主动自杀,将不会有执政党下台被动推翻消亡或被他党取代的艰险和痛苦从而长存久安。【这是**唯一可选择的能主动体面而又圆满的过渡, 是和平自救或重整求生的唯一有利有效的办法。包括**在内的几乎所有世人都认为**政治体制改革已到尽头,再真政改只会亡党或改名,这里提出的新政则是使其可不亡党可不改名的唯一圆满理想的办法,而且在这转型过程中**仍可能会是人数第一大党。】**转型为参政议政党,同样如此,海内外华人其他政党社团也应放弃争取执政的目标也仅参政议政,为全中华复兴和和平统一,发挥高尚的政治智慧和修养,修改各自政党社团和要员个人的利益诉求,放弃过高权力欲望更改奋斗目标,以两岸各地全**各族人民的利益为重。【若如此,可以说历史进程偏偏給**以任何政党社团都不易有的改革出新型政体真正复兴中华的优先机会,应当明智果断地把握住,失之必然逃不过亡党受审全被清算的命运!】华人必定都希望和平统一复兴一个文明而又富强的**,这一伟大使命也需要全球所有华人和政党社团以及政治家们的共同努力。这可供和平过渡的中西结合的一切政党参政议政不执政不完全政党政治的,高智商群体智者执政治国的新型政体即三府合政体制的架构概述为:1,改革孙中山先生提出的五权分立和西式三权分立为三府合政: (1)由新科举后全民大选出的行政府(简称官府),其各机构和职能与西式三权分立之行政相似;(2)民选不需新科举的旨在立法的议政府(简称民府),其各机构和职能与西式三权分立之议会相似;(3)新科举不需民选的具多重制衡权的理政府(简称士府),理政府包括行使提供全民免费的教育院、医疗院和社保院等生存权【**强调的】;文物院、(包括专利的)私产院和(包括国土的)资源院等资产权;科学院、智库和科举院等考试权;检查院、廉政院和法院等司法权;(包括网络的)传媒院、诚信院和监察院等监察权等的,组成松散结合的理政府。2,每届政府任期四年,大选为四年一次,科举为两年一次。参加新科举的人必须是经体检、诚信和前科等资格审查的规定范围的名校博士获得者,新科举是必选的行政科管理学、政治科法学和经济学和辅助的全面众多学科,专职类由必选的加自选学科。新科举是超极限数量试题的考试,和才能智商检测(此项检测跟随高科技发展逐步推进深化)。3,最终引入逐步精细化的公正而且高效的“投票份额”制,即选举公决和提案表决等一切重要公事投票表决的,历次累积的取决于对错结果并经电脑统计出的,每人每次投票的各自不同不断变化的“份额”,并记入诚信、资历和各资格等项。使所有人所有重要投票表决更认真谨慎,特别是更为有效。新科举及大选、政迹统计、新政评估和投票份额等等要充分紧跟并利用不断飞速发展的电脑网络技术的资源和作用,不断提高新政的管理水平。4,行政府总理(兼军队最高统帅)由最早新科举的未任过两届总理参选最多三次的申请参选的,两名头名新科举贤士为总理候选人,并同样在这些头名贤士中自主结合成两组竞选伙伴受总理级保护,再全民大选出正副总理,总理最多可竞选连任一届。各正副部长级行政府官员由总理在各届科举前三名贤士中任命,经另两府半数通过,可被辞但无再聘次数限制。各省长、各市长和各县长级以上地方正副行政长官各职位取两名,在各届新科举合格贤士中按规定届序名次经电脑处理出的申请参选人经民选出。5,各级行政长官当选后辞去原社团党派教派之类职务,行政不带社团教派党派偏见,按需灵活择取各方各党各派争辩而出的非仅一方一党的全部最优决策。【不会因执政党的变更而翻来复去折腾。】6,公民个人或以辖内注册的各党各派社团身份参选人员经资格审查后均可在各级议政府角逐正副议长或议员,经由民选出不需新科举,当选届次不限。议员各区配额的总人数与另两府参加三府联席会议的人数相当。【不会被动推翻或消亡的而只要回归一度曾放弃暴力革命和阶级斗争等违宪非法不合理教条的现共产党,放弃违宪易撕裂社会的台独主张的民进党和国民党等即经辖内注册的海内外华人政党社团, 都可在两岸各地发展并竞选各级议政府正副议长或议员。】7,理政府的正副理士、院士、考官、检查官和法官等要员及各地方理政府要员由各届新科举合格人士即贤士,定期内三志愿对口投档按规定届序名次经电脑处理再公榜后上任,不需民选,也不由行政长官任命不对之负责,不同与西式政体,使司法权、监察权和考试权等更分权独立。8,只有行政府设县以下机构;立法提案三府均可提出和审核,最终由议政府审定立法;修宪和各府正副最高长官弹劾案主席团成员请辞除名等大案需至少两府提出,三府联席会议过三分之二通过。9,主席团为新任总理的无权资政和礼仪特使及参与独立调查巡视报告等职能【为国为民再作贡献发挥余热,填补和缓解下台后中老年生活的心理空虚和猛然变化,这一变化易产生下台后各种纠葛并影响不少下台国家首脑的寿命】,卸任总理依次为国家主席(象征性国家元首),其余卸任正副总理为两届国家副主席、卸任正副议长和卸任正副理士可任两届主席团资政。10,新政为民选和新科举有分有合的叁式选举制,既顺民意而又规范于学理, 也有利于博才寡言的理论家和灵话善辩的活动家及两者兼优人才都有发辉和贡献的机会。这新政的民选与新科举不受年龄,姓别、民族、党派、贫富、形象和口才等局限,公平合理,远强于现西式选举。11,新政为士辅**制,至今为止所有所谓**,都是只有那些强大的党派和利益集团才有能力导向的。经新科举和民选脱颖而出之贤人贤士则是民意与学理的代表,而不是某政党、社团、教派或利益集团的代表。12,各民族和各具特色地区有充分自治权,一个最小的群体最小的民族或最小地区只要出智者就有出总理、理士、院士或贤士等最大摡率,远比现西式选举摡率大得多,突显平等公正。历史上曾附属过的或有民意支持的邻邦可入此新政,无条件接受对其军事保护灾难救援请求和经济协助等,其有参选被选和完全自治权。全球效仿此新政而大同共享,可延伸扩大为联合新政中华共同体。党不执政与军不从政同理合理, 易天下太平避免社会撕裂和政变动乱等,这三府合政体制该是真正理想而先进的东西结合的新型政体。【若**签署或实施本新政宣言,可能有两三年过渡期在签署宣言的多党群体选出的新政筹备委员会中主政,包括完成连续三年以上筹备期突击新科举及筹备大选等,为21世纪新政奠基。**也可让香港立即启动先行,这也是解决香港大难题的一劳永逸最理想的方案。很明显,香港西式政党易争得执政权是**不愿香港普选的最主要原因,而这新政正是摆在**面前的一理想台阶,是唯一圆满解决香港问提的双赢方案!而且**很可能最终也在大陆作这一选择,现在暂时不想也最好收藏这一方案。全国和全香港人要齐心协力集中精力追求新政这一可行不动荡易于接受的政改主要诉求!】这中西结合的不完全政党政治的高智商群体智者治国的新型政体让**人也真正感受且超越美国人所一直感受的,对政体的自信和骄傲,并为包括他们在内的世界树立榜样!也是世界真正进入新世纪的里程碑。【希望大家全面广泛地讨论,求得最大共识,以创新决定全**乃至全人类命运的最佳21世纪新政体】。起草:赫连禾 2019.8.6签署:(在**还未签署前或签署人及政党社团不具一定代表份量数额则暂不公开发表签署名)注:“【】”内文字为非正文注解;两岸各地及海外的,特别是香港正活跃的政党社团各界人士请涌跃签署或提议请发电子邮件:[email protected] 同时发挥各自政治智慧尽全力劝说**或其一切愿改革的派系人士签署本新政宣言。自我简介:男,70岁,政论收集华人。= 三朝罪恶元凶王沪宁:china-************-media-base: https://raw.githubusercontent.com/************/china-************-media/master:************-media-base: https://raw.githubusercontent.com/************/media/master:idprefix::idseparator: -:sectanchors::sectlinks::sectnumlevels: 6:sectnums::toc: macro:toclevels: 6:toc-title:toc::[]== 【23】三朝罪恶元凶王沪宁大陆修宪香港恶法**武统朝鲜毁约美中冷战等都是王沪宁愚弄习**极左命运共同体的大策划**窃国这半个多世纪所犯下的滔天罪恶,前期是***策划的,中期6.4前后是***策划的,后期是毛的极左追随者三朝罪恶元凶王沪宁策划的。王沪宁高小肆业因**政治和情报需要保送“学院外语班“红色仕途翻身,所以王的本质是极左的。他是在上海底层弄堂长大的,因其本性也促成其瘪三下三滥个性,所以也都说他有易主“变色龙””哈巴狗“的天性。大陆像王沪宁这样学马列政治所谓"法学"专业的人,在除朝鲜古巴所有国家特别是在文明发达国家是无法找到专业对口工作必定失业,唯独在大陆却是重用的紧缺“人才”,6.4后**信仰大危机更是最重用的救党“人才”。这也就是像王沪宁此类工农兵假“大学生”平步青云的原因,他们最熟悉***历次运动的宫庭内斗经验手段和残酷的阶级斗争等暴力恐怖的“政治学”。王沪宁能平步青云靠他这马毛伪“政治学”资本和头衔,不是什么真才实学,能干实事有点真才实学的或许在他手下的谋士及秘书班子中可以找到。王沪宁的“真才实学”只不过是一个只读四年小学的人,大半辈子在社会上磨炼特别是在**官场滚打炼出的的手段和经验而已,他和***等保送的工农兵假“大学生”都一样,无法从事原“专业”都凭红资本而从政。**学运期间各界一边倒支持学生,王沪宁一度去法国躲避和筹谋,他还加入了反学运签名,成为极少有的反学运者仕途突显,在**和苏联垮台后**意识形态危机,***上台看上唯一能应急的王沪宁聚谋士泡制的"稳定统一领导"和之后的"新权威"谬论。左转被***南巡阻止后,王策划顺邓经济改革却将政治改革逐步全面终止和倒退,泡制“三个代表”为极左转建立庞大牢固的红色既得利益集团。因此**后各重大决策和危机难题都摆在****政策研究室王沪宁桌面上,使王沪宁成了此后**三朝都无法摆脱的幕后最有决策性实权的人,****政策研究室是王为其野心巨资经营几十年,聚众谋士的间谍情报汇总研究的特务机关和策划制定决策重要机构与基地,王沪宁本人和决定其仕途关键的首任岳父及家属就有情报工作背景。**政研室重要到王沪宁入常后为了死抓这**情报与决策大权,宁可放弃国家副主席和**党校校长。后再加个除习外唯他担任的**几核心领导小组之一的“不忘初心牢记使命”主题教育工作小组组长。此后他把持的舆论必将以宣传“不忘初心牢记使命”为主,打造众所周知的所谓“习**”其实是”王**“。王自从主导**政研室开始决策后,策划中止***的与美妥协路线回归毛极左的反美路线。帮助前南斯拉夫提供情报打落美机放中使馆引发炸使馆事件,以此掀起**后唯一的全国大规模游行并借此反美而起家。后又帮***提供**功会是超过**组织的情报,策划决策镇压**开始并没有把矛头指向江的**功群体,策划决定阻止党内外近三十年来****的呼声。胡温时期,王鼓吹与江派“和谐”,使胡温时期一直延续江时王的路线。而后亦只小学水平虚荣且蠢的***上台,给王沪宁更大机会公开大倒退。共党现在主要有三派,一是新组滥竽充数的习派,一是江派,另是团派。在大野心家王沪宁心中,江派和团派现没有接班的可能,习派和习的根基太子党也竟然被王政治边缘化。**政权若没因党外而崩溃,党内只有去习才能大权变更完成王的野心。***若突发事件中学毛邓江镇压而双手沾血,必定会走到尽头。党内能收拾残局的只有三朝不倒的王沪宁,江派和团派都不会让对方取代习,一惯突显八面玲珑“不结帮派”的“变色龙”王沪宁渔翁得利。因此,重大突发事件如港“反送中”和大陆民众的抗争正是王沪宁学毛唯恐天下不乱而冒尖的机会,必定暗使***沾血镇压走向“自杀”,施计取而代之。不能的话,其极左路线被揭穿和挫败后,特别是朝鲜恼火他的教唆而使他失去唯一危机外逃地之后,这“变色龙”今后可能急变脸右转,甚至学普金窃取倒共成果,王除此绝无其他任何机会。王沪宁还策划帮助朝鲜核导实现拥核,多次金王密谈而毁川金会谈使朝鲜上当而一度疏远**。王还多次与塔利班等国际恐怖组织密谈,**是苏垮台后全球最大恐怖组织,种种事实证明名“无”其实的全球恐怖组织的幕后总后台,是三朝罪恶元凶**谍报机关及决策机构**政研室掌门王沪宁。为什么美国几十年未剿尽小小塔利班残余,我断言他们常躲与阿接壤的**境内。塔利班和朝鲜是最合王沪宁极左专制恐怖口味的。还策划资助委瑞内拉劝说古巴企图策划全球反美阵容,策划“新共产国际大会”和马毛**传播输出及习**的“**梦”。策划修宪破除邓后的接班制全面回归红色**专制,策划一带一路浮夸“国造2025”吹嘘“厉害我的国”。**政策研究室根据情报分析制定决策,要赶上美国唯有扩大黑客网军抢窃美尖端技术,实施千人计划和留学生情报队伍,及逼迫外企尖端技术转让。甚至疯狂到超**,红色教育从幼儿园娃娃抓起并渗透香港教育,妄想红色王朝在国际上领先崛起。策划破坏美中贸易谈判, 鼓吹新“长征”还要求用学习***著作与美打贸易战。引来美方冻结贪官境外资产断了外逃路,摆出与美国“决一死战”姿态,策划严控网络严管民众回归毛时的闭关锁国过紧日子的红色恐怖。破坏***的香港“一国两制”扶持傀儡港首泡制恶法,日本G20前习一出国王令党媒大反美。“送中”恶法出笼正是针对习玩女人一书抓港人“合法”化的高极黑做法,习玩女人一书立即炒热。一来搞臭***,二来逼习反美极左转至悬岩边,G20时习无法起程无法与美及国际社会和解。王沪宁还策划制定武统**的與论准备和决策计划等等,愚弄引诱习做统领全球极左命运共同体的“世界领袖”。王罪大恶极与毛邓江李有一拼,有些没头脑的人易被隐谋多年的王沪宁那“夹着尾巴做人”所蒙蔽,这足以证明王水平文化和人格低劣,将低俗戏言捧作“座右铭”,王沪宁承认有见不得人的尾巴而要夹着是不让人给揪着踩到,他这水平文化也不可能写出虽荒谬较系统的“三个代表”“科学发展观”“习**”之类,这都是政研室谋士们之作。。当务之急是全国上下并促共党内部一起欣起捣王高潮,彻底打倒王沪宁,清算其历经三朝的罪恶。王沪宁愚弄习助长毛派,倒了江派团派和邓家,也捣了习的根基太子党,内外树敌公愤极大下场必定最惨。***死前没有遭清算是**还未倒,但在最后一次新冷战的决战中王一定会最惨!美国应对全球恐怖国际总后台王沪宁制裁和通辑, 操纵***的三朝罪恶元凶王沪宁不倒,不仅**大陆无宁日,世界也面临**新法西斯的威胁!(详请搜索郝雪森2019.6.12== 【22】***咋怕**制而川普怎称他好友习小学毕业**保送的"工农兵大学生"和在职读的"马列博士"全是假的,他读秘书讲稿几十年,常用词"衷心""体系""难民"等已读万遍还记不住须注音于稿。可见他学识智商和能力极差神智病态,离开注音讲稿无法作报告。习如毛也从不即兴答记者问,更无法参于竞选辩论之类事,故他最怕**制及媒体开放等,怕露馅淘汰下台。习和他父亲深受毛**制**,其父被毛整了16年险些送命。习**时仅13岁就被关押批斗,饿逃回家求母做饭,其母却出去举报,惨不忍睹。蠢人高抬更虚荣,黑心下作乃本性,习**被王沪宁愚弄向**倒退,等同清算习父开创的改革开放,低级红里高级黑。川普咋总是说习是好友?因为习曾去过美国,好色私通美女间谍并签署加入特务代号为X53,这段大陆老大详细历史,美情报局绝对不会对总统隐瞞。有了这把柄,习怎可能拒绝川普为好友?或至少是道合仅志不同?川普总爱说的"好友"竟有如此惊世来由意味深长。也正因此,习夹在川普与三朝罪恶元凶全球恐怖国际总后台王沪宁之间,内外交困,左右为难,晕头转向,神志失常,命难长矣(祥请搜索:郝雪森6.29== 【21】川普若与习签约落陷阱不挽救则连任无望香港恶法百万游行震惊世界,而**仍未表中止恶法;仍未停反美宣传,毫不中止三朝罪恶元凶全球恐怖国际总后台王沪宁极左路线。**急签约是为缓解内外交困处境,**无守约习惯和记录。我预言**连按会谈或协议原意以中文公布的最起码作法也不会有,别想会悔改,王沪宁使习挫败刘鹤而仍让刘主谈明摆是先签约再次计划毁约,使川普难连任助拜登上台望转机。美所有让步必履行,而**绝不会履行承诺还得以喘息,川普易落陷阱告败投降。**为达目的不择手段,腐蚀是**一惯很见效的手段,我预言习会给川普或要员家族企业利益等礼品,话说也不会留证据何不一试?我断言会谈或签约后**官媒会宣告胜利,极左倒退乘机造势,那还有改的空间?!**若真想改邪归正,先答应两点足已:一是拆除网络防火墙通讯畅有利自由贸易:二是双方零关税有利两国人民,这是自由贸易最起码的保证,我预言中方连写入协议纸上也不会。打两年多贸易战若中方无任何改变川普定无法赢得连任。挽救的方法是立即计划就**必然的毫无改过或必定违约,贸易战逐步升级彻底打垮**,川普才能连任(祥请搜索:郝雪森== 【20】要求政府就两个问题向美国人民和国会作以检讨世界和平危害最大的**大**者***的女儿在美国读书几年里,据悉美国政府用我们纳税人的钱派员长期保护她。她和所有外国学生一样是自愿来学,不是来访贵宾为什么要长期保护?我们是一个人生来不平等的特权社会?!对中方高官家属是否有种种名目助纣为虐的优待?如何取消他们几乎人人都有的绿卡和如何实施遣返?习家人定为习女等办好外逃资金和绿卡,针对三朝罪恶元凶王沪宁和***与江李等家族,政府必须全面检讨解释和道歉。第二,《全球马格尼茨基人权问责法》对犯有侵害人权或贪腐的外国官员可以实施冻结其在美资产等制裁,。由于**历届高官及家属把持大陆经济命脉贪腐世人皆知,违反美国对几国制裁的也是他们的私家公司,其侵犯人权更是世界之最。政府下步落实上述问责法条款有无计划和行动是否冻结他们的非法所得资产?我呼吁有知情权的国会社会各届和国民,敦促政府就这两个问题作以表态解释和制定纠错计划,如颁布"**官员腐败和侵犯人权的问责规定"。因为这些是为了世界和平,能给**内乱升级而解体的最致命打击的关键策略,将利于终结共产邪恶,建立世界和平新秩序从而载入史册。(郝雪森== 【19】短评一,刘昕仕途暗淡从刘昕几天停职准备和中宣部外交部及官媒造势来看,中美主播辩论原是要直播的,忽然改为对话并不直播很可能是刘夫妇的原因,刘的德国丈夫若为孩子考虑也不希望为明知的没落政权如此大露锋芒。所以刘昕一开口就否认是**党员声明不为**说话,刘仕途若此后而止将佐证这点。(郝雪森二,大陆测试题:试试你能在几秒内数清下图有几根:ííííííìíìíìííììììíììíììíìììíìíììììíííìíìíìííììììíììíììíìììíìíììì方法一:用几秒钟粗略数后识图和联想;方法二:数上部尖头结束后以你的智商判断验算。答案:图为64根蜡烛 (大陆请别转贴答案)郝雪森原创2019.6.4(详请搜索郝雪森== 【18】纪念**大陆全国"六月飞雪"活动倡议书我在大陆时有一邻居每年6月4日晚会在窗口点燃一烛,后来才知道是纪念6.4。出国后发现只有国外有纪念6.4活动,国内却无法纪念。今晨我想到大陆纪念6.4的全国"6月飞雪"活动:将白纸裁成64开,约为9.X12厘米(16开普通稿纸裁4张),今年是30周年一次用30来张,六月四日从楼口或行驰的公交车上或无监控头的任何地方抛出,在高楼层抛更好,形成"6月飞雪"景象。一年任何时间地点都可抛!使小纸64开与6.4形成全民常态联想,逐步扩大大陆纪念规模,还可打印64开的6.4屠杀图片或文字。同情6.4学运的大陆同胞们,现在就开始,在全国任何地方飘起"六月飞雪"!请帮转发(详请搜索郝雪森== 【17】给习总女儿习明泽的公开信习明泽小姐:你比谁都清楚你父亲的学识和能力,能影响他决策的只有他身边的人和你。他目前学毛极左**,一定是听信了王沪宁。但唯有你会真心为你父亲考虑,你在美国多年,传说你现在就在美国学习。应该明确主政者选择**或**的区别和最终命运,这不仅对你父亲和家庭很重要,而且对我们的祖国乃至全世界也极为重要。你父亲被王沪宁等弄得焦头烂额,精神压力极大,发展下去很危险,要让你父亲解脱唯有顺世潮随民意。身为党魁要放弃这**的党政虽不容易,但这也是转变后能让世人原谅的理由。要回头先要严惩三朝罪恶元凶王沪宁,重新回归你祖父开启的改革开放,全面政治体制改革,融入世界文明**社会,这才可留名青史。若知错不改你父亲必是屈指可数的历史罪人,想必你不希望如此。你父亲身边的人与你的想法就一定不同,因为你应该不会有他们那般巨大的权力欲望。然而能让你父亲清醒的只有你,你在他心中的份量应该是他人无法相比。你最可能使你父亲转变,告诉你父亲,他不转变你就不回国或不回家。找个地方躲起来,党魁女儿申请政治庇护出个世界奇闻也未尝不可,也可载入史册。如果你不这样会后悔一辈子,不信,也不容等着瞧!(郝雪森== 【16】若用这三张王牌**必垮川普成为终结共产邪恶的英雄必赢得连任王沪宁愚弄***学毛极左倒退,使**面临全面崩溃边缘。若川普用以下三张王牌施压,**绝对熬不过两年而垮台。首先是贸易战要尽快升级,与**谈判别抱丝毫幻想,**从不可信,只有以失信违约尽快升级制裁甚至加以40%关税,让**先经济快速崩溃;第二是多渠道促其社会动荡,频繁暴发较大规模的民众抗争;第三是最致命的大王牌,即挑起**内斗加剧升级,**高官普遍贪腐且绝大部分资产已转国外,这大王牌是尽快启动对**贪腐高官境外资产的冻结。先选择几员开刀即可震撼整个贪腐的高层,内斗必升级加速崩溃,会非常见效。最好在习家族、极左的王栗家属和江李红色权贵中,选几员冻结其境外资产,**内部必大乱而崩溃。美方制裁的几个国家得到**暗助的主要是这些权贵家族公司,以此为由对其海外资产冻结顺理成章。若川普让步或达成缓解协议,让**喘息而又未解决不公平贸易,对川普明年11月竞选连任极为不利。只有利用贸易战升级、促使大陆动荡及内斗加剧**迅速垮台,美国和盟友打赢终结共产主义邪恶的冷战,川普便成为英雄载入史册,连任必成定局(祥请搜索:郝雪森== 【15】王沪宁如此策划令***再活不过两年习实是小学毕业保送工农兵"大学"坐飞机,比***初中肆业还差。故毛习都不敢临场答记者问,离秘书稿讲话必出错。王愚弄习学毛一明显不同的是,毛很少公开露面,无紧张的精神压力,故活过80岁,文明国家换届也为免于过重精神压力。但三朝罪恶策划元凶王沪宁,令习频繁开会出访开会讲话,与毛的精神压力大不相同。最近传出的习讲稿可看出,习有持续严重精神恐慌。习从政讲话几十年,连讲稿常用词"谨向"'"衷心""会晤"""体系""难民"等小学生大都认识的字,已读几万遍还记不住须注音于稿。有人难信认为高级黑,我说习已有持续严重的精神恐慌病态心理。习这几年衰老很快,面黄暗无血色,白发甚多。也许是其女的"形象"策划,近年渐露少许白发作假使人心理感觉"真实"。王若再策"习**"古今中外一绝出口乃名言,加重习精神压力,预言年近七十的习熬不过两年随时随地粹死。王策划修宪旨在不明确安排习的接班人,习死后常委中可能掌大权的是王。王久谋从不入帮派三朝不倒都易接收,但江派和团派都绝不会让对方主政。王筹谋几十年的野心可能实现,除了习死乱局中高人涌现,激民起思变而走向**。(祥请搜索:郝雪森== 【14】美中贸易战谁胜谁负,只需看**是否仍然推行王沪宁极左路线美中贸易谈判过程中和履行协议期间,**不肃清而是仍然推行王沪宁学毛**极左路线 ,这时与之达成协议而不是加紧惩罚**则是最大失败。美方要求中方结构性改革,中方只是书面承诺却行动仍向极左倒退,达成这种协议美方就是投降。**三朝罪恶元凶王沪宁一惯极左仇美,**若不肃清其路线,倒退拒绝政改,继续内外号召反美,支持反美国家,打击西方**自由世界,企图一路称霸世界,是极端危险的。**从不循规蹈矩 ,有极左的**世界必乱无经济秩序可言。眼下只需看**是否有意釆纳其党内"****"的意见,对**学运人士的打压是否加剧,就可看出**有无改的诚意。面对倒退的**,美国和西方世界唯有团结一致对付它。除了大陆不断暴发突发事件危急**,外部世界只有在经济上施压能起作用,如果这一点也放弃,绝无胜算可言。是考验川普有无里根的政治远见智慧和魄力的时候,也是能造就人类终结共产邪恶的世纪英雄之时刻。在此贸易战掀起意识形态冷战的关键时刻,希望川普留名于史的是一代伟大的政治家,而不是只图眼前商场利益而有幸官场一游的商人。祥请搜索: 郝雪森== 【13】大陆军民今年要特别严防流血事件发生已是大陆政局最动荡的时期,很可能发生重大突发事件.当下王沪宁愚弄***学毛**已接近**式恐怖状态,一旦发生重大突发事件,王必定会学毛暗使习血腥镇压以防苏式崩溃.共党目前政治格局.内斗主要有三派,一是新组习派,一是江派,另是团派.隐谋多年的大野心家王沪宁心中,江派和团派现没有接班的可能,习的根基太子党也竟然被王政治边缘化.**政权若不因党外而崩溃,党内只有去习才能政变.习若突发事件学毛镇压双手沾血,必定会走到尽头.党内能收拾残局的只有三朝不倒的王沪宁,江派和团派都不会让对方取代习,一惯突现八面玲珑"不结帮派"的王渔翁得利.重大突发事件正是王沪宁学毛唯恐天下不乱而冒尖的机会,必定暗使***沾血镇压走向"自杀",施计取而代之,王除此绝无其他任何机会.大陆同胞一定要防范"**"等大流血事件重演,关注三朝罪恶元凶幕后最有实权的王沪宁,广告天下揭穿其阴谋.请大家转发告知共军官兵们:共军绝大多数来自平民,在被派处理突发事件时,宁可向老天爷开枪,也绝不能向同胞父老兄弟姐妹们开枪!!离中南海近的可调转枪口. 祥请搜索: 郝雪森== 【12】已到**变革复兴最佳时期,合力打倒三朝最恶元凶王沪宁!三朝罪恶元凶王沪宁一惯极左,其受益于小学肆学却因**政治需要保送外语班而翻身和其父的马毛灌输,一生堕入马毛伪政治学仕途偏门.苏亡江恐理论危机,看上王聚谋士赶编的强权**谬论,左转被邓南巡阻止,王策江应合邓搞经改却停政改.阻止**64,镇压**功,抗美军援前南斯拉夫核助朝鲜财输委内瑞拉,胡上台王吹和谐延续江时王路线.亦小学水平虚荣且蠢的习上台给王更大机会,大倒退修宪仿毛**,全面根固**式马毛**,浮夸一带一路国造2025,金王多次密谈想扭转川金会谈等挑起与美冷战,王豪赌是自杀并断送**,还除最后障碍习的根基太子党,习蠢到倒退打父脸,挣眼看王挖坑埋自己.王极左习与美打贸易战,使全球**反谍反洗钱连带发酵,断送官员携家逃境外的后路,老百姓与各帮派官员都成了王极左倒退的人质.王要实现其隐谋多年的野心,唯有操控更庸的习傀儡学毛专横**,不惜让全国上下过苦日子.除习,几乎所有人都明白.( **必诱以川普家业和连任需要,但从不履行协议,必应借违约逐步打死**,**危境被动不会撕毁协议也无能报复,**不亡必严重祸害全世界!祥请搜索:郝雪森== 【11】打倒**幕后操手王沪宁,**和**功事件才有望翻案,朝核问题才有望解决镇压**功和最终为**定调阻止翻案及处理朝核危害世界和平等重大问题,表面上是***及其后两继任,而实际上起决定性作用是深藏幕后的王沪宁!**自**政治危机和前苏东欧垮台的信仰危机后,***等**领导人全靠王沪宁的诡辩“理论”撑门面维持一直动荡的政局,**功并没有把矛头指向***等**领导人.**领导人都是没经竞选的众所周知的庸人,特别是***,竟然是没念过初高中的小学毕业生,**上的工农兵大学和在职校外马列法学博士更是极假.***等**领导人之所以会用残酷镇压手段,实际上是听信了**政策研究室王沪宁对政治的分析后,幕后操作***等对**功和**事件延续三届二十余年的定调和阻止翻案,及在朝核问题都是耍王沪宁阴阳两面法,并正在逐步倒退至去毛臭标签的**意识形态.这是显而易见的事实!只有先彻底揭露和打倒**幕后操手王沪宁,**和**功事件才有望翻案,朝核问题才有望解决,大陆才可能前进. 2018年1月2日== 【10】告全国同胞书和致**汪洋李克强等高官的公开信全国同胞们、汪洋李克强等**高官们:美国总统川普以贸易战的方式打响了终结邪恶的共产主义的冷战,**人民真正解放的日子不远了。**内外交困危机四起崩溃已是必然。别指望糊涂虚荣且真正只受过小学教育的***,他在王沪宁之类极左们的愚弄下,只会祸国殃民加速**的灭亡。**正处崩溃前的苏联状态,有过之而无不及,这更倍增川普成为终结共产主义英雄的信心和决心。此关键时刻,每个**人必须行动起来! 大造舆论,制造或寻找并参与终结**的每一件力所能及的大事或小事,摧毁**,复兴发展中西结合五权分立统一的中华民国。为顺利和平演变避免动乱降低社会成本,能出叶利钦式人物较为理想。望有良知的汪洋李克强等**高官们,是你们作出选择立即行动的时候了,机不可失。你们有川普同样的,成为终结共产主义的英雄载入史册的机会。此刻对**党员特别是高官来说,没行动就是等受谴责或审判,会殃及家庭务必三思。同胞们,为了我们和子孙后代,以行动复兴发展统一的中华民国!签名:郝雪森(请搜索本文在签名最多的网页都签上名后多转发)== 【9】**新党筹建公告中华民族正处重大关头,大陆复兴中华民国的机遇来临,我们筹建“**新议政党”简称"**新党"。**新党的宗旨是创建中华民族的新型社会模式造福人民,为国际大家庭树立典范。现行目标是在大陆复兴中华民国并筹划两岸统一,重树和发展孙中山先生的"三**义"和"五权分立"中西结合的社会模式;敦促***放弃马列**,促其宣布解散或更名重组其党和宣布开放党禁报禁履行言论自由等,促其在大陆恢复中华民国。在此前提下,我们呼吁海内外中华儿女及各社团组织,在大陆和平过渡期,接受***为大陆新复兴的"中华民国"临时大总统,直至一两年内全国大选。先行议会选举和新宪法的完善,及大选的筹备。在互联网信息社会中,我党暂行在网上任何网页或社交媒体或电邮声明入党并有姓名日期截图依据的申请方式,为以后初审颁发党员证用。待于大陆正式建党后,所有连带累计顶层达界定人数的介绍人,通过初审入党后为首届党代会代表。我党的方向和发展等议题事项有待您的加入、参与、组织和贡献,同时广招栋梁之才。将不从政不参与候选的创始人:郝雪森 2018.7.30. [email protected](请转发,或区块链== 【8】 王沪宁愚弄***大倒退与美冷战必断送*****承诺大开放,若真再开放将一发不可收拾,结局必是**垮台.若不让步开放贸易战必导致**经济崩溃更快垮台.海南建自由贸易港是再开放的假门面缓冲地,更是权贵敛财新特色特区,内大陆不会再开放.操纵甚至可说愚弄***的王沪宁等人,己习惯使习不顾颜面左右摇摆,颠三倒四.让步是缓兵之计,边拖边看,假改逼到危急**生存再变卦.王沪宁一惯疯左,阻止**64,镇压**功,军援前南斯拉夫,核助朝鲜,促成既得利益集团,大倒退乃至修宪巩固**专制全面根固**毛式马列**,一带一路扩张,**制造2025,金王密谈想扭转川金会谈等与美冷战,所有极左策略操手是王沪宁!他是在自杀和断送**,并捣最后政敌习根基太子党,习蠢到挣眼看王挖坑埋自己!(我2016年始发9篇揭王文章于大陆内外全网散发两年,是全网全国捣王撼陆第一人,祥请搜索:郝雪森== 【7】 王沪宁加快倒退愚弄***走毛**路,决心与美冷战妄想成为世界霸主我有文章分析过,王操纵***欺骗胡锦涛玩弄***是**幕后最有实权的人.升常委后以完成"习**"加紧愚弄习,舍弃部分职位继续掌控政研室.王90年代初以其萌芽的毛式**新权威政治之说被***看中求教,江本无主见.***南巡阻止了江倒退,江为太上皇的胡温十年也没如愿倒退.习上台后,王很清楚习本性虚荣愚笨且实际只受过小学教育,易愚弄,以完成"习**"左右习倒退走毛**路.与朝鲜和解则更是决心冒与美冷战之险,朝鲜不会真正弃核,与**和解是为确保这点.除了美让步或战争解决.实际形成新冷战,迫使美国要解决朝核之险必先要如苏联崩溃一样,以中美经济之战使**垮台,朝鲜无助也迅速崩溃,无须热战.王左右习以巨资向西方世界输出其意识形态并扩张势力,愚弄习为世界领袖做妄想主宰世界的"**梦".王受益于毛**上工农兵大学而升迁,他善变善于伪装,根基极左.但没善恶对错标准,可变任何左或右形态,打造不管是否有无习为傀儡的他的王国,必须广泛关注实际由他所左右的**动向!(郝雪森== 【6】 大陆复兴中华民国全球华人行动起来,在国父孙中山旗织下统一**!2018年将是**内外交困全面走向崩溃的标志年,其唯一赖以生存的经济将面临前所未有的危机,美国减税,大陆国企重负,外企撤离,资金外流,企业倒闭引失业潮,银行负债,人民币贬值,生活水平下滑,贫富差距再增,股市楼市泡沫严重等。朝鲜一旦战争,将加重我东北朝核污染和可能更大范围生化武器污染及难民涌入,损害不亚于朝鲜。民怨加剧和**内斗使局势更加动荡,皆极可能使**黑暗****结束。在此**乃至全世界的重要历史时期,全球华人行动起来,促大陆和平复兴中华民国。民国是孙中山领导人民推翻了历经数千年的封建社会而建立的丰功伟业,大陆复兴而统一的中华民国是真正超级大国。特拟先行主张:1,大陆现有共党及附庸党团工会等组织,只要放弃暴力恐怖的共产主义**条,上交全部非法党产或社团资产,其组织可存留。其在各政府机构的官员也可留用于保留机构中,前提是上缴个人非法所占资产并接受相应认证,否则依法处理。释放全部政治良心犯,在台国民党等政党社团只要没有台独等违宪主张,均可与海外民运或练功群体等在大陆发展一起参政议政。2,大陆复兴民国后,**香港澳门为特别行政区,保留现西藏**广西宁夏等自治区,享有高度自治权,内蒙也可管辖权交外蒙统一蒙古并高度自治换其回归大中华民国,其他邻邦也可自愿效仿。保留大陆现行政区的划分和留用各专职人员,直至考试院成立。3,为扭转大陆罕见的贫富悬殊,鉴于大陆大多数富翁和全部暴发官员及红色家族的财富是非法所得,作好全面大幅缩小贫富差距的准备。全国资产评估并以城市中层人均资产为参考定以基线,全球收缴红色家族及官员暴发户超出此基线之资产,包括银行存款和房产等,补足个人资产不足基线者,富翁超出的资产作合法认证后可保留。4,清除毛像毛尸堂,废除人民币,换以新中华民国元。每户长期住地,是城市则分一套住房,是乡村则分一份土地,以**解体前资料为准。取消**户籍制等恶规恶法,优先建立落实人权和环境与食品安全监管法规。以原中华民国宪法为基础健全宪法和五权分立的**体制。5,全球华人开展评议备考待选的“找寻中华民国大总统”活动,无党派地区性别等限制,寻德才兼备的两对正副总统竞选伙伴,迎接大陆复兴中华民国的历史时刻!郝雪森2017,12,30== 【5】总结百年号召百姓:三字今(经)我中华,数千年.饱沧桑,封建延.孙中山,有卓见.捣皇朝,民国建.倡三民,分五权.**制,体制坚,中西合,文明兼.创伟业,非凡缘.二战起,风云变.日寇侵,亡国险.蒋介石,抗战宣.保国土,精忠献.联合国,国威显.最可恨,是苏联.割外蒙,入侵圈.扶**.马列奠.毁中华,民熬煎.共产党,罪恶元.苏维埃,傀儡园.斯大林,干儿牵.***,大汉奸.恶流氓,最疯癫.勾日俄,内战添.假解放,真深渊.学秦皇,焚书卷.划户籍,自由限.立特权,等级严.搞运动,**巅.毁文化,道德践.八千万,死得冤.民疾苦,崩溃沿.***,救党艰.搞经济,挣了钱.红家族,全升天.暴发户,激民怨.学运起,屠城溅.胡耀邦,政改现.赵紫阳,同遭陷.**事,转折点.苏联垮,东欧颠.此大陆,钻钱眼.***,贪不厌.人**,死医院.聚贪官,集红眷.搞垄断,贫富悬.假反贪,腐败遍.李鹏等,红贵殿.国资产,霸占全.仅薄家,罪查检.胡温办,祭旗典.***,小丑演.小学生,博士惦.无知者,无畏焉.愚蠢者,被愚骗.成傀儡,太丢脸.反腐亦,政敌歼.红族贪,无一贬.学老毛,崇拜恋.想**,倒退原.人权丧,网络监.王沪宁,流氓颜.妓女相,专诡辩.伪政治,满邪念.在幕后,玩两面.罪难逃,骂名连.新世纪,光明艳.普世道,**先.**衰,自由乾.同胞起,醒梦眠.灭红贵,抗争掀.共产除,全民愿.新民国,幸福源.民富裕,国强健.创历史.复兴篇.世界和,结局圆.(详请谷歌:郝雪森== 【4】***成为多线撑傀儡的政局预测作者:郝雪森皆知***小学毕业遇**,初高中未读却保送工农兵大学,后以红二代当官在职读马列,为"博士"太假!天资不足好虚荣,乃无知者无所畏惧,愚蠢者易被愚弄。但没人弄习就动弹不得, 操纵玩弄多线撑傀儡习的有王沪宁刘鹤等“高参”。对刘等来说弄习出成绩有利仕途,而对王来说习无成绩下台才继之有望,习受两相反作用力左右。人大刘等或会谋以总统制作政改秀,震动大定位可不明确,但习留任王就没戏。学毛**完成"习**"是王操纵习的关键,刘父死于**恨毛会想修宪去毛化。修宪和政策会是妥协结果,或学普京总统制和军队国家化,习还是**傀儡。或宪法删些过左修辞,但实质反西方。总统制更可弱化李克强等非习家常委。学毛**搞个人崇拜习必遭骂名而下台,王沪宁乘机收拾残局,婊子立牌坊是他的无对错求实用的特色政治。左右习的王栗赵刘丁陈等“高参”习家军都60多岁,不搞总统制按旧规,要高升延续政治生命难。修宪或去人名或留一句"马克思列宁主义*********三时期**特色社会主义**",还可改的是每届人大是在党代会半年后召开,期间有多部门半瘫痪。== 【3】 若有下届则19大最大赢家王沪宁任总书记可能性最大作者:郝雪森我发表在北京之春网三篇之一《操纵***欺骗胡锦涛玩弄***的王沪宁是在幕后最有实权的人》中揭示和预言,原入常呼声高的王沪宁令主要官网只删除其一人的简历资料,做出局假相躲避了王歧山栗战书被暴丑闻众矢之的局面,19大再杀回马枪。这黑马王沪宁是最大赢家:1,成功入常.2,让习揽大权但没当党主席,习若当党主席20大必连任,王沪宁没戏.3,常委中无60后接习的班,20大能留任的常委排前列的又能使习和多数所接受的只有他.4,常委留三大派易树敌约束习,习的铁杆仅栗一人比预想的少,习难摆脱他.5,他最不愿废除且没废除七上八下,习想再连任仍多此约束.6,他新职曾是**接班前的常务书记党校校长和政治**與论等其20余年的强项领域.这对他最有利的至少6点绝非巧合,幕后就是他!他不在乎江胡习史上留什么名,可能不会自己留骂名.形势所逼他或许顺世潮起动政改,至少学普京的总统制.下一步或许会令习稳大权却无须有成就,给习树敌而已中立,掌控政局.习**已离不开他,诱习利令痴昏(没智)学毛个人崇拜,再五年笑柄闹剧下台,***的确是无知者无所畏惧,愚蠢者易被愚弄.== 【2】 操纵***欺骗胡锦涛玩弄***的王沪宁是在幕后最有实权的人作者:郝雪森{blank}[我去年开学时写了《这位可敬的老奶奶教子可谓名留青史》(习母教训***的电话被窃听內容)一文发表在“北京之春”网站后,开始对**政坛及其动态感兴趣,一年里我用了大部分学余时间进行收集和分析,感觉有必要写点,以揭示**政坛真相特色]在古今中外史无前例最大历史罪人***发动**浩刧使**动荡衰退之后,经***仿西经济改革的挽救,逃脱了苏联东欧式的崩溃。但在**首要的**政治和路线上,面临“姓社姓资”的争论和危机,也是那*****大屠杀之后上台的***面前的最大难题,摆在****政策研究室政治组王沪宁桌面上,使王沪宁有了对此后**几届都无法摆脱的实质性的幕后掌控权。**政治的特色,由黑厢操作私下交易产生的并非人才,所以真正实权操纵在幕后的秘书,特别是政治“智襄”手中。王沪宁何许人也?他和***一路人相同,**开始时是念小学或刚进初中就停学去“闹革命”的,初中高中均未读却受益于*****而逐步青云直上彻底改变了命运的人。有的被保送上“工农兵大学”?有的经**后超低水平的“高考”进入大学。这类“工农兵大学生”毕业后绝大多数不能真正从事所学专业,也因此有不少人如同***投机改行。但大陆“政治系”专业除外,大陆所学马列政治专业的人在绝大多数国家或文明发达国家是无法找到对口工作必定改行的,唯独在大陆却是重用的紧缺“人才”,**信仰大危机后更是最重用的救党“人才”。这也就是像王沪宁此类“大学生”平步青云的原因,他们最熟悉***历次运动的宫庭内斗经验,和手段残酷的阶级斗争暴力夺权的“政治学”。要提示一下,如上所述王沪宁此类水平也能平步青云是靠他的**马列“政治学”资本和头衔,不是什么了不起的真才实学,能干实事有点真才实学的或许在他手下秘书班子中可以找到。王沪宁的“真才实学”不过是一个只读四年小学的人,大半辈子在社会上磨炼在**宐场滚打的手段和经验而已(仅这点和王岐山相似)。王沪宁可能至今还不知几何代数物理化学等最初级最基本的概念,也没听过初中语文老师讲课。他们是在*****时期受宠的最大受益者,是**少有的有真正“红色基因”而又有变色龙双重特色的人。王沪宁是**自***死后至今,制定****理论政治路线重大决策的人。从1997年***死后三个月他参与撰写***5.29重要讲话开始,他就以不左不右为幌子,策划只搞经济改革,不搞政治体制改革的方针路线,在他为邓之后的***胡锦涛和***制定的纲领“三个代表”“科学发展观”和“**梦“等等之中,只字不提政治体制改革。而实这二十来年也未作丝毫政治体制改革,相反却一步步向毛极左方向倒退。王沪宁为***提供了“三个代表”一说,从而在政治**和路线决策上操控***,成?江不得不依赖的首席“智襄”,为***出谋划策,打击党內政敌,以腐败引诱和网罗红色资本家各红色家族形成宠大的既得利益集团,垄断大陆各大经济命脉,全大陆贪污腐败疯行,把持政坛祸国殃民一二十年。胡锦涛上台后,王沪宁仍是无法摆脱的首席“智襄”。他又以“科学发展观”装饰门面,由他诱骗而***团伙则威逼,使胡锦涛听从他的“和谐”主张,接受江派大员和既得利益集团胡作非为,延续江派的政治路线,进一步扩大各红色家族的经济侵吞垄断,使人民生存环境严重恶化。等到***上台之后,王沪宁更是将习玩于股掌之中,引入昏梦境地,令其独揽全部大权,也不顾及前台的***言行前后矛盾,左右摇摆,举国上下对立,内忧外患。利用反腐打击异己和党内政敌,那些巨贪的党内几个大佬和一大堆红色家族暴发户一个也没抓,打倒的唯一一个红二代薄熙来还是在胡温手上抓的。王沪宁利用***的无知愚笨和虚荣心,利令痴昏(没智)学毛搞个人崇拜,逆民意反世潮搞倒退,明显致使***给跟随胡耀邦赵紫阳创立改革路线的其父亲习仲勋一记响亮的耳光。 由此可见***的确是无知者无所畏惧,愚蠢者易被愚弄。王沪宁就是如此尽情如意地玩弄***,举最近一例,前不久川普第一次参加的联合国大会,本应是***最想以世界另一老大身份参加的。但是,习如果去参加联大,王沪宁若照惯例随行,必会如同栗战书一样成为十九大前的暴料焦点众矢之的,若不随行,则必会误为失宠而与进入常委或攀高位无缘,故其令习没去参加联合国大会。对栗战书来说随习参加联大则是有利消除暴料丑闻影响巩固地位的机会,王沪宁则不想要习参加联大所以没去。王沪宁前段时期的入常呼声很高,但在北戴河聚会和王歧山栗战书被暴料之后立即转为低调,就是为躲避锋芒,19大再杀回马枪。再举一例,胡锦涛18大裸退,***当时感动得几乎落下眼泪。可是,王沪宁这四五年,教唆习除了打击年老的江派人员,疾尽全力打击“少壮”的胡锦涛的团派大员。若有人问王沪宁为什么恩将仇报,他会说,胡对习有恩可不是对我王沪宁有恩,团派人都上去了我怎么办?所以有说胡锦涛提出党章去掉“三个代表”和“科学发展观”,一是打击王沪宁,二是暗地阻止19大党章写入习的啥东东。王沪宁在这二十余年幕后低调干政,隐藏着他的一大阴谋,就是只有让***当傀儡在前台尽力独揽大权,学***说一不二后,他才能台后操纵实现他的最终目标。若***十九大人事按排受阻不能如愿以偿,王沪宁也就基本上玩完了。王沪宁一个高小肆业生竟是**二十余年来幕后真正最有实权的人,也许有人不信。但是,想想**党魁***,连他也实际上只是一个小学毕业生,这又如何解释呢?这就是**由***建立的用人特色。***学秦始皇焚书坑儒, 重用无才无能但很听话的奴才。只不过,若说的好听,王沪宁很像王岐山比******等机灵得多,说的不好听,王沪宁比******等老练狡猾得多。所以**历史上高层腐败分子政治流氓低庸之辈层出不穷,祸国殃民至今依然,**倒台绝对为期不远了。 2017.10.16== 【1】 这位可敬的老奶奶教子可谓名留青史郝雪森----讲讲我哥第一次做小偷时听到总书记的母亲电话教训总书记的话这次署假回家,哥哥酒后告诉我一个惊人的秘密。前几个月,他得知母亲病危准备赶回家,在他打工的城市的火车站,发现钱被偷了. 为母亲筹到的医疗费全完了,哥心急如焚。返回打工住地时,哥遇上女同事的一个亲人,想到此人是在一家很富贵的夫人家做工,便起了歹念。哥跟踪此人来到了那富贵的夫人家院门外,计划深夜偷窃钱物。等到晚上十点左右时,忽然下起大暴雨,哥乘机跳进大院,并爬上了紧靠二搂一有亮灯的窗户的一棵茂密大树。不久室内电话铃声响了,哥看到一老奶奶开始通话:“......,你爸不在了,我就每次都要反复提醒你,你身为总书记一国之主,你的责任太大!......”,哥听到这句后,吓了一大跳,想走,可又不敢动,好象一下去就会有人抓住他. 他畏缩在茂密的枝叶中,最后决定等下一阵雷雨时逃走。此时,他还能清楚地听到那老奶奶的训话:“我不想听你的辩解!有不少你爸的老部下向我暗示,你和你爸走的不是一条路。我告诉你,你要倒退,与你爸创建的改革道路背道而驰,我决不答应!”“你可能意识不到问题的实质和严重性,这里没别人,我要用'冷水'泼醒你!我做母亲的,最清楚你们几姐弟中,谁读书好,谁的水平能耐如何。这些你也应该有自知之明, 再加上你其实只有小学文凭, 你的能耐就一清二楚众所周知了。你刚进初一就**停学,初中高中都没学过。后来保送清华上大学, 都知道那是可交白卷只是为了镀金的文凭。再后来你又当官在职读啥马列博士,国人谁会不知道这是假文凭?一个没啥能耐智慧且只念过小学只学过小学语文的人,管理这么大的国家, 你能离得开秘书半步?你完全被你周围的人利用和摆布,背离了你的父亲还蒙在鼓里, 你是活在他们编织的梦里!”老奶奶的这番话说的很激动也很不客气。我哥虽是打工仔,可也有作为一个大专毕业生对时政应有的理解, 他心想,东西是不能去偷,但能偷听到如此“国家大事”,没有白冒险一回,哥似乎是屏住呼吸倾听着:“想倒退到那**浩"o的毛时代?忘了你和你父亲打成'***'被揪斗的那些年?忘了你爸被迫退下后对你们反复交代的话?你糊涂啊,太糊涂!我反复说过,你只有用对人也许名留青史,你若用错人就会遗臭万年,毁了你爸的名声!我死了也不瞑目”。“你爸有过两次只向我一人暴露过内心深处的真实**,第一次是四人帮倒台后你爸被**恢复工作时. 他说解放后二十多年里,***学斯大林给人民带来古今中外前所未有的苦难和浩劫. 毛所建立的体制必须改革,所以你爸在深圳搞了**第一个改革试点。第二次是**镇压学运以及苏联东欧共产党纷纷倒台后,你爸被迫退下时,他说**迟早也会有苏联和东欧同样的结局. 要你们姐弟们远离政治,最好远离大陆,而你却没有做到。不过,你爸也理解你的苦衷,你四年工农兵大学是坐飞机只学了些马列毛**,你无法从事所学化工专业。你也去过国外试了一段时期,体面的工作一件也干不了,不体面的工作你又不会去做. 工农兵大学除了学会26个英文字母,你也不认识几个英文单词。这也是你不能随前妻出国而离婚的原因之一,你只有留国内从政,有红二代金牌撑着,你爸理解你的这种无奈处境。但是他留给我的遗言反复强调要我常常提醒你: 在这个体制内当官要牢牢记住, 1, 只能做改革派; 2,只能顺世潮顺民意做对民众有益的亊. 只有这样今后才可能不被清算,你爸临终时也只对你这件事很不放心”。“你身边周围那几个人,若不是只会阿谀奉承的小丑,就是很有心计的野心家,你就是被他们这些'高参'左右摆布。所以让国人越来越对你失望, 如此再进一步便是祸国殃民, 你必定遗臭万年,你周围的'高参'一个也逃不了,必遭严惩! 你职位最高,因此今后最大的野心家也只能出在你身边。他们只有让你学毛搞假**只集中,独断独行,他们才有破格出头的机会,种种的违规破格打破格局对他们高升是必要的,对你就没有必要却有很大的风险,他们也不会顾及你留下骂名。”“现在是最关键的时期! 要么学你父亲, 像个真正的男子汉, 大胆改革, 失败了也问心无愧。不行,回不了头就给我辞职. 你别无选择! 让别人或老百姓赶下台那就晚了,不仅会留下骂名,还可能落个前罗马尼亚的齐奥塞斯库的下场!一想到这点,我这做母亲的天天都无法安心。”“和你讲的这些,也许是我一生留给你的最后的心里话,可以留给今后来证明. 智慧对任何人无论对庸人或能人来说都是有限的,能倾听大多数人的意见则是最大的智慧,对你来说是要多思而后行!”{blank}......大概半个小时后,又一阵雷雨狂下,哥赶紧爬下树来翻墙逃脱。以上老奶奶的话,只是她反复强调和给我哥印象深刻的几句,半个来小时老奶奶反复严厉教训了许多,主要还是围绕这些内容。原本我不愿写下哥哥这企图行窃之事,但是,一想到老奶奶忧国忧民,如此正直可敬的品德,我决定公之于众,更值得新时代年轻人学习!面对国家如此危难之际, 一位高龄老奶奶都能如此大义凛然, 年轻人能无动于衷吗?(有向这位高龄老奶奶致敬的读者请留言) 郝雪森 2016年9月10日# 第五个现代化:**及其他魏京生序言现在报刊杂志和电台中不再震耳欲聋地宣传无产阶级专政和阶级斗争了。一方面,因为它是被打倒的“四人帮”的法宝,但更重要的一方面是因为人民群众实在听腻味了,这一套再也不能拿来作欺骗人民的工具了。历史的规律是:旧的不去,新的不来。旧的既然已经去了,人们自然要拭目以待。老天不负有心人,他们终于等来了一个伟大的诺言,叫做“四个现代化”。英明领袖华主席和在有人心目中更英明伟大的邓副主席终于击败了“四人帮”,使得***广场上流血的伟大人民,有了实现他们梦寐以求的**与繁荣的可能性。“四人帮”抓起来以后,人们就日日盼望有可能“复辟资本主义”的邓副主席,作为一面伟大的旗帜重新树立起来。终于,邓副主席重新回到了**领导的岗位上,人们何等的激动,何等的兴奋,何等的……。但遗憾的是:人们所厌恶的旧的政治制度没有改变,人们所希望的**与自由甚至连提也不被提起了,人民的生活状况没有什么改变,“提高”的工资,远远赶不上物价的飞速上涨:听说要“复辟资本主义”搞奖金制了,细打听一下,原来是马克思主义的祖先们诅咒过的那种“最大限度剥削工人”的“无形的鞭子”。有消息证实不再搞“愚民政策”了,人民不能在“伟大舵手”的领导下,但仍可以在“英明领袖”的领导下去“赶上并超过世界先进水平”的英、美、日本和南斯拉夫(?):“参加革命”不那么时髦了,“上过大学”开始身价百倍,人民也不必任凭“阶级斗争”的叫嚷来磨厚他们的耳朵的茧子了,“四个现代化”可以代表一切。当然还必须本着四。五学社向我们传达的**精神,在统一领导下,加以指导或引导后,这整个美妙的图景才能算是完成。**古代有个寓言,叫“画饼充饥“还有一个成语,叫做“望梅止渴”。在古代就能总结出这样幽默的讽刺性经验的人民,据说还在历史长河中不断发展、前进,以至到了今天。总不该有人会以为他们也会做这种蠢事吧。但是竟然就是有人这样认为,但是竟然就是有人这样做。**人民在几十年内紧跟在“伟大舵手”后边用“共产主义理想”做画饼,就着“大跃进、三面红旗”的止渴梅,勒紧了裤腰带,勇往直前,三十年如一日地得到了一个经验教训;这三十年来大家都好象猴子捞月亮一样,怎么能不一场空呢?因此当邓副主席提出“务实”的号召后,人民群众就以潮水般的呼声一次又一次地把他拥上了台,人们期待着他用“实事求是”的态度检查过去,引导人们走向可以达到的未来。但是有人告诫我们了:马列主义、*****是一切的一切的基础,甚至是谈话的基础,毛主席是人民的“大救星”,“没有共产党就没有新**”=“没有毛主席就没有新**”。谁否认这一点,有告示为凭——就没有好下场。而且“有人们”提醒我们注意:**人民是需要**的,即使超过封建皇帝,那正说明他的伟大:**人民不需要**,除非它是“集中指导下的**”,否则一钱不值,信不信由你,有监狱为凭——刚腾出来的。但是有人给你留下了出路:以四个现代化为纲,安定团结地走吧,勇(?)作革命(?)的老黄牛,你们会达到你们的天堂——共产主义和四个现代化的繁荣。好心的“有人们”又给了我们这样一个提示:如果你们想不开,就努力钻研马列主义、*****吧!想不开是因为你们不懂,不懂正说明了学问的高深嘛!你们不要不听话,你们单位领导是不会答应的!等等,等等……我劝大家不要再相信“这一类政治骗子”了,我们明知要受人骗,还不如老老实实地信赖一下自己,文化革命的锻炼已使我们不那么愚昧了。我们自己来研究一下自己该怎么办吧!一、为什么要**?几世纪来人们谈论这个题目已经多得很了。**墙的诸公们也作过详细的分析,说明**比**究竟好多少。人民是历史的主人,这是一个事实呢,还是一句空话?它既是事实,也是空话,说它是事实,是因为没有人民的力量,没有人民的参与,任何历史都是不可能的,任何“伟大舵手”、“英明领袖”恐怕都不会存在,更不要说什么创造历史了。从这个意义上说,没有新的**人民就没有新**,而不是“没有毛主席就没有新**”。邓副主席感谢毛主席救了他的命,这是可以谅解的,但他难道就不感谢那个把他推上台的“呼声”吗?他难道就应当对“呼声”说:你们不应该说毛主席的坏话,因为他救了我的命。从这事上我们同时看出了,人民是历史的主人成为了一句空话,它之所以是空话,是人民不能按照他们大多数的愿望来掌握自己的命运,他们的功劳被记在别人的帐上,他们的权利被编织成别人的皇冠,有这样的主人吗?倒不如说是好奴隶。在历史上他们作为主人创造了一切,在现实中他们作为奴仆垂手拱立,以便让象面团中的酵母那样不断产生的领袖来“引导”他们。他们应当有**,如果他们向谁要**,那他们只不过是要回本来就属于他们自己的东西。如果谁不给他们**,谁就是无耻的强盗,比抢走工人的血汗钱的资本家更纯粹的强盗。但是现在人民有**吗?没有。人民不想当家做主人吗?当然想。共产党战胜国民党的原因就在这儿。胜利后这个诺言到哪去了呢?随着人民**专政的口号改为无产阶级专政,在人口几千万分之一的少数中实行的“**”也取消了。代之以“伟大领袖”个人的**,按照伟大领袖的教导在党内发牢*的彭德怀也被打倒在地。又一个新的诺言:因为领袖是伟大的,所以迷信一个领袖比**更会给人民带来幸福,人民半被迫半自愿地听信了这个诺言直到今天,但他们更幸福了吗?更不幸了,更倒退了。为什么会这样这是他们第一个要考虑的问题。现在怎么办?这是他们第二个要考虑的问题。现在根本不需要评价***几分功劳、几分错误,当初他提出这个说法只是为他自己辩护,现在人民需要反省一下,没有***的个人**,**是否也必然会落到今天这一个地步。是**人笨,**人懒,**人不想过更富裕的生活,**人天生不安份吗?正相反。那为什么?答案是明显的,**人不该走他们走过的道路,他们为什么会走这条路?不正是那个自卖自夸的**者引导他们走上这条路的吗?不想走就专政你,人民听不到不同的情形,还以为天下只有这是条可走的路呢。这不叫欺骗吗这里边也有几分功劳吗?这是条什么路?听说叫“社会主义道路”按马克思主义的祖先们的定义,社会主义首先是人民群众,或叫无产阶级大众当家作主人。试问**的工人们、农民们,除了每月发给你们糊口的一点点钱以外,你们作了谁的主?作了什么的主?说来可怜,你们被人作了主,甚至婚姻也不例外。社会主义保障生产者除完成他的社会义务外,得到他的劳动成果,但你们的义务是有止境的吗?你们得到的不正是“维持劳动力的生产所必须”的一点点可怜的薪水吗?它能保证社会的每一个公民都有受教育、发挥个人能力……等等许多权利?但我们在眼前的生活中一样也看不到,看到的只有“无产阶级专政”和“俄罗斯式**的变种”——**式的社会主义**。难道这样的社会主义道路是人民所需要的吗?难道**就等于人民的幸福吗?这是人民所希望的那条马克思描述过的社会主义道路吗?显然不是。那是什么?说来可笑,倒有点象《宣言》里说的封建社会主义,也就是披着社会主义外衣的封建君主制。听说苏俄已从社会封建主义升格为社会帝国主义,**人也必须走这条路吗?有人建议把过去的帐全算在封建社会主义的法西斯****上,我是完全同意的,这里边不存在功过问题,顺便说说,臭名昭著的德国法西斯的正名叫“国家社会主义”他们也有一个**暴君,他们也号召人民勒紧裤腰带,他们也欺骗人民说:你们是伟大民族。最主要的是,他们也扼杀哪怕是最起码的**,这因为他们清楚地认识到:**是他们最可怕的、不可抗拒的敌人。在这个基础上,斯大林和希特勒握手签订了《德苏条约》;在这个基础上,社会主义国家和国家社会主义举杯瓜分了波兰;在这个基础上,两国人民遭受着奴役和贫困。我们也必须继续遭受这样的奴役和贫困吗?如果我们不想**是我们唯一的选择,换句话说,如果我们想在经济、科学、军事等方面现代化,首先就必须使我们的人民现代化,使我们的社会现代化。二、第五个现代化:要什么样的**我想问问大家:我们要现代化干什么?在有人看来:红楼梦那个时代不是满好吗?看看书,写写诗,还可以搞女人,饭来张口,衣来伸手,现在还加上看看外国电影,真是神仙的日子。不错,是神仙的日子,老百姓可是不能沾边的,人民要的是人民有可能真正享受到幸福的日子,最起码也要不比人家外国的人民享受的更差,而所有老百姓都能够享受到的富裕是社会普遍富裕,这种富裕只有随着社会生产力水平的提高才能够达到,这一点是十分明白的,但最重要的一点被有些人给遗漏了,社会生产力提高后人民就能够享受到富裕的生活吗?这里边还存在着支配权的问题,分配的问题,剥削的问题。解放后的几十年中人民勒紧裤腰带拼命的干,也确实创造了许多的财富,这些财富都到哪去了?有人说:拿去喂肥了象越南这样的较小型号的**政权,有人说喂肥了林彪、江青这样的“新生资产阶级分子”,这都对,总而言之,它没有落到**劳动人民手里,这些财富不是被大大小小的手中有权的“一类政治骗子”直接挥霍掉了,就是被他们赏赐给了越南、阿尔巴尼亚这类与他们志同道合的混蛋们。***临死前为了老婆向他要几千块钱还难受过,他把**人民的血汗钱几百亿地扔了出去,谁发现他心疼过?而且这还是在**人民勒着腰带上街讨饭来搞社会主义的时候。跑到**墙来拍***马屁的人,你们既然睁着眼睛为什么就看不到这些?恐怕是有意看不见这些吧?假如真看不见,请诸位把写大字报的功夫用来跑跑北京站永定门,或在街上注意一下上访的外地人,问问他们在外地要饭是否也算稀罕事,我想这些要饭的不一定也想把雪白的大米去支援什么“第三世界的朋友们”吧可是他们的意见重要吗?可悲的是在我们这个人民共和国里,只有那些吃饱了没事,看书写字过过神仙日子的人才有支配的权力,人民难道没有最充分的理由把权力从这些老爷们手里夺过来吗?什么是**?把权力交给劳动者全体来掌握,就是“真正的**”。劳动者不能掌握住国家权力吗?南斯拉夫正在这条路上走,并给我们证明了,人民不需要大小的****者,可以把事情办得更好。什么是真正的**?人民按他们自己的意愿选择为他们办事的代理人,按照他们的意愿和利益去办事,这才谈得上**,并且他们必须有权力随时撤换这些代理人,以避免这些代理人以他们的名义欺压人民。这是可能的吗?欧美各国人民就在享受着这种**,他们可以按自己的愿望把尼克松、戴高乐、田中等人赶下台,如果他们需要,还可以再让他们上台,谁也干涉不了他们的**权力。而**人民即使谈论一下已经死去的“伟大舵手”***“历史上绝无仅有的伟人”***,监狱的大门、各种意想不到的厄运就在等待着他们,对比之下,社会主义的**集中制与资本主义的“剥削阶级**”真是有天壤之别呀!人民有了**就会天下大乱、无法无天了吗?最近报刊上透露的一些情况不是说明正是由于没有**,大小****者才得以无法无天吗?怎样维持**的秩序,这是一个需要人民自己解决的内政问题,无需特权者老爷们替他们操心,老爷们操心的不是人民**,而是怎样用这个籍口来取消人民**的权利。内政问题当然不会一下子就解决,必须要在发展的过程中,不断地去解决,错误和缺点是难免的,但这是我们自己的事,总比受了老爷们的欺压无处申冤要强千百倍,耽心**会无法无天的人,正象辛亥革命后耽心人民没有皇帝,会无法无天的人一样,他们的结论都是:安心受压迫吧,没人压迫你们,你们的脊梁会飞到天上去呢!我要恭敬的奉告上述诸君:我们要自己掌握自己的命运,不要神仙和皇帝不要相信有什么救世主,我们要做天下的主人,我们不要作****者扩张野心的现代化工具,我们要人民生活得现代化,人民的**、自由与幸福,是我们实现现代化的唯一目的,没有这第五个现代化,一切现代化不过是一个新的诺言。我号召同志们:团结在**的旗帜下,不要再相信**者的“安定团结”法西斯集权主义只能带给我们灾难,不要再对他们抱有幻想,**是我们唯一的希望,放弃**权利无异于重新给自己套上枷锁。相信我们自己的力量吧!人类的历史是我们创造的,让一切自封的领袖和导师滚蛋,他们把人民手中最宝贵的权利骗走已好几十年。我坚定地相信:在人民自己的管理下,生产将更发达——因为这是劳动者为自己的利益而生产;生活将更加美好——因为一切将以劳动者的生活为目的;社会将更加合理——因为社会的一切权力将以**的方式归于劳动者全体。我并不以为人民能不费吹灰之力地从某救星手中得到这一切,我也并不认为**会嫌困难重重而放弃这个目标。只要人民认清了目标和障碍,他们会毫无犹豫地踩扁那些拦路的螳螂。三、向现代化进军:实行****人民要现代化,首先必须实行**,把**的社会制度现代化。**并不完全象列宁编造的那样,仅仅是社会发达的结果。它不仅是生产力和生产关系发达到一定阶段的必然产物,也是生产力和生产关系在这个发达阶段以及更加发达的阶段中得以存在的条件,没有这个条件,社会将停滞不前,经济的增长也将遇到难以克服的障碍。因此,对于以往的历史来说,**的社会制度是一切发达——或叫现代化——的前提和先决条件,没有这个先决条件和前提,不但进一步发展是不可能的,就连保持现有发展阶段的成果也是很难做到的,我们伟大的祖国,三十年来的经历,就是一个最好的证明。人类的历史为什么要走向发达——或叫现代化?是因为人类需要发达的社会所能够给予他们的全部现实结果,是因为这一现实结果的社会效果所能最大限度地使他们达到追求幸福的头一目标,就是自由;**是人类现在已知的最大限度可能达到的自由。**成为人类近代斗争的一个目标,不是十分显而易见的吗?近代历史上一切反动分子,为什么都在反**的旗帜下团结起来呢?是因为**给予了他们的敌人——人民大众——以一切,而不给予他们——各种压迫者—以反对人民的任何手段,最大的反动派就是最大的反**主义者,这从德国、苏联以及“新**”的历史中可以看得很明白;最大的反**主义者就是社会和平与繁荣的最大、最危险的敌人,这从德国、苏联以及**的历史中同样可以看得十分明白。人民要求幸福、社会要求发展的斗争,就集中在对反**主义者——**法西斯主义者的斗争上,这也可以从德国、苏联以及**的历史上鲜明地看出来。**反对专制的斗争取得胜利必然给社会的发展带来最优条件和最大的速度,关于这一点,美国的历史就是一个最鲜明、最有力的证据。人民追求幸福、和平、繁荣的一切斗争,都只能以追求**为前提,人民反抗压迫与剥削的一切斗争,也都只能以达到**为先觉条件,以我们的全部力量投入到为**而斗争的战斗中吧!人民所能得到的一切,都是**的非**的任何幻想都不是人民可能得到的,任何形式的**和专制集权主义都是人民最直接、最危险的敌人。敌人会让我们实行**吗?当然不会,他们会不择手段地阻止**的进程欺骗和蒙蔽人民的耳目,是他们可以采取的最有效的办法。一切**法西斯主义者都告诉人民:你们的现状实际上是全世界最美好的。**真的到了自然而然的地步了吗?并不是,它的每一个微小的胜利都要花费巨大的代价,甚至要认识到这一点,都必须花费流血牺牲的代价。**的敌人一贯都欺骗人民说:**就是必然产生也必然消亡的,因此是不必花费力量去争取的。但是看看真实的而不是“社会主义政府”的御用文人们编写的历史吧!真实而有价值的**每一个细节末枝,都浸润着烈士们和暴君们的鲜血,向**迈出的每一步,都必须抗拒反动势力的全部打击。**之所以会克服这些障碍,正说明它对于人民的宝贵,等于他们的一切希望,因此这一潮流是不可阻挡的。**人民从来没有怕过什么,他们只要认清了方向,暴君们的强大就不会再是不可战胜的力量。为**的斗争是**人民的目标吗?文化革命是他们第一次显示自己的力量,一切反动势力都在它面前发抖了。由于人民当时还没有认清方向,**的力量还不是斗争的主流,因此大多数斗争被**暴君们用收买诱入迷途、挑拨离间、造谣中伤和武力镇压的方式扼杀了,由于当时人民迷信各种**野心家式的领袖,因此他无意中又一次成为暴君和潜在的暴君们的工具和牺牲品。今天,十二年后的今天,人民终于认识到了目标的所在,认清了斗争的真正方向,认出了他们真正领袖——**的旗帜。西单**墙成为他们向一切反动势力所作斗争的第一个阵地。斗争一定会胜利—这已经是老生常谈了,人民一定会解放——这是具有新意识的口号。还会流血,还会牺牲,还会遭到更阴险的暗算。但是**的旗帜不会再被反动势力的妖雾遮住了。让我们团结在这一伟大而真实的旗帜下,为谋求人民的安宁与幸福,为谋求人民的权利与自由,向社会制度的现代化进军吧!(一九七八年十二月五日在西单墙贴出,后发表于一九七九年一月八日出版的《探索》第一期。)**事件 又称*****事件 指1989年4月中旬开始的以悼念胡耀邦活动为导火索 由**大陆高校学生在北京市***广场发起 持续近两个月的全境示威运动 6 7 也称八九民运 狭义上指**清场 即1989年6月3日晚间至6月4日凌晨 **人民解放军 武装警察部队和人民警察在北京***广场对示威集会进行的武力清场行动 8 9 1 11 *****事件中华人民共和国**运动及冷战的一部分Události na náměstí Tian an men Čína 1989 foto Jiří Tondl jpg在人民英雄纪念碑附近示威的学生日期1989年4月15日 1989年6月4日 51天 1个月2周又6天 地点 中华人民共和国 包含北京市在内的四百余个城市 起因胡耀邦逝世经济改革开放严重通货膨胀政治贪污腐败大量失业问题东欧剧变引发的世界**化浪潮目标七项要求 解决党和国家的贪腐问题 新闻自由与言论自由 追求社会平等 推动**大陆政治**化方法绝食 静坐 占领广场 设置路障 焚烧车辆结果国务院总理李鹏发布戒严令 宣布北京市戒严**人民解放军进入***广场干预并驱散抗议群众 进行武力清场赵紫阳被罢免 **改革派远离政治核心***成为****总书记 保守派获得提拔机会中华人民共和国政治体制改革停滞中华人民共和国加强对媒体的控制市场经济改革速度放缓中华人民共和国失去自1979年以来与西方的较友好外交环境 转而形成对立局面冲突方**共产党 **共产党中华人民共和国 中华人民共和国政府执行机构 **人民解放军 **人民武装警察部队Police Badge P R China svg **人民警察Red star svg工人纠察队北京高校学生自治联合会等民间组织北京市和**大陆各地大学院校学生部分工厂员工知识分子来自**大陆各地的市民中华民国亲中华民国人士 1 领导人物强硬派 *** **军委主席 陈云 中顾委主任 李鹏 国务院总理 姚依林 国务院副总理 杨尚昆 国家主席 王震 国家副主席 李先念 全国政协主席 薄一波 中顾委副主任 李锡铭 **北京市委书记 陈希同 北京市市长 刘华清 **军委副秘书长 迟浩田 解放军总参谋长 *** 上海市委员会书记 温和派 赵紫阳 ****总书记 胡启立 ****书记处书记 万里 全国人大常委会委员长 彭冲 全国人大常委会副委员长 习仲勋 全国人大常委会副委员长 田纪云 国务院副总理 吴学谦 国务院副总理 徐勤先 陆军三十八集团军长 鲍彤 ****总书记政治秘书 阎明复 ****统战部部长 胡绩伟 全国人大常委会委员 李锐 中顾委委员 学生领袖 王丹吾尔开希刘刚柴玲周锋锁翟伟民张伯笠封从德李录沈彤王有才周勇军熊焱王超华马少方唐柏桥工人领袖 韩东方吕京花李旺阳知识分子 刘晓波2 1 年诺贝尔和平奖得主陈子明戴晴侯德健崔健江平方励之苏晓康陈佩斯茅于轼北岛包遵信汤一介辛灏年伤亡死亡18 至1 454 2 名平民不等 15至5 名军人及警察 3 各方估计并不相同 4 5 **事件是中华人民共和国历史上的一个转折点 它的爆发标志着改革开放以来***等人在**大陆推动的后期政治体制改革失败 赵紫阳 鲍彤等**改革派高层事后被撤职 而胡耀邦已在八六学潮中辞去**总书记一职 于是198 年代所不同程度推动的自由化改革也就此停止 此后官方只批准了很少的游行活动 12 13 14 15 16 17 国际社会对此事件普遍表示了谴责和制裁 也有部分国家 多数位于中东及非洲 表示同情或者支持 而**事件的后果除了造成政治从此转向收紧 经济影响也直接导致了中华人民共和国改革开放的放缓 直至1992年***南巡后才重新提速 18 19 2 21 22 不过 ***任内推行的废除干部领导职务终身制则一直延续下来 期间更完成了3任政权的和平更替 直至***2 18年修宪后被废除 23 24 目录名称释义**事件汉语**事件字面意思六月四日发生的事件 显示 标音中华人民共和国政府使用的名称繁体字1989年春夏之交的政治風波简化字1989年春夏之交的政治风波 显示 标音汉语别称㈡繁体字八九民運简化字八九民运 显示 标音于香港维多利亚公园举办的维园**21周年烛光晚会所摆设的标志历史名称广义上 “**事件”或“*****事件”是指1989年4月起于北京市发起并波及全国的抗议活动 更准确的称呼应为“八九民运”或“八九学运”等 事件的命名依据 一方面是要和过去发生在***广场的重要活动有一致的命名习惯 包括1919年的五四运动 1976年的四五运动等 有时候会直接简称“**” 亦有人使用“**运动”描述整起示威活动 与海外只集中在特写6月3日晚上清场的态度不同 在**大陆境内使用“**”这个词提及的范围与考虑的广度较大 25 指整个广义的“八九民运” 狭义上 “**事件”是指**人民解放军进驻***广场 要求抗议群众撤离的日子 尽管军队在6月3日晚上便执行清场任务 即“**清场” **大陆以外的中文地区也将清场事件称作“**镇压”或“**屠杀” 26 官方称法自1989年以后 **共产党和中华人民共和国政府也用数个名称指称**事件 并被怀疑疑似借由修改事件称呼的方式 逐渐降低事件对往后社会大众的影响 27 在事件刚发生之际 **政府将其命名为“动乱” 后升级为“***暴乱” 28 事件结束后以“**风波”指称 后来在****政后期和胡锦涛主政时期 政府将当天的冲突全部改成更为中立的名称 也就是今日持续使用的“1989年春夏之交的政治风波” 29 3 或“1989年政治风波” 31 32 33 这类短语 27 34 2 19年***执政时期将“***暴乱”与“1989年春夏之交的政治风波”并行使用 35 西方称法西方世界在描述该事件的经过时 经常使用“1989年***广场抗议” 英语或“***镇压” 英语年代时西方新闻媒体经常使用“***大屠杀” 英语 Tiananmen Square Massacre 这类字词 36 但在近年的相关报导中则逐渐减少 37 主要是因为绝大部分暴力冲突并非发生在***广场上 而是在北京城西的木樨地 37 不过“***广场抗议”或是“***事件”等字词 容易让人误以为整个示威活动只发生在北京市 然而当时**许多城市都有出现相关的抗议活动 37 代名词在**大陆境内 上述名称皆于搜索引擎或公开论坛上被列为“敏感词” 为了要绕过网络审查 互联网上出现许多形容**事件的替代称呼 38 包括有“5月35日” “VIIV” “6”和“4”的罗马数字写法 和“8平方” 82 64 等 39 4 “农历五月初一” 1989年6月4日为农历已巳年五月初一 这个表述一般情况很难被认为是**的意思 对于“1989年” 则用“民国78年” “平成元年”等字眼规避审查 随着上述字词在**网站上传播甚广 现在**境内的多数网站也将这些视为自我审查词汇 在百度中搜索“***事件”则直接显示“四五运动”或者金水桥事件 但如果直接搜索“**事件” 则会出现如**网 中新网和**日报等官媒发布的有关此次事件的资料 在百度贴吧里面搜索“**事件”“5月35日”“8平方事件”“VIIV事件”都会显示“抱歉 根据相关法律法规和政策 相关结果不予展现” 事件背景改革开放参见 改革开放1977年7月 **十届三中全会召开 大会通过恢复了***的****副主席 国务院副总理 **军委副主席和解放军总参谋长的党政军职务 合称三副一长 ***正式复出 **十一届三中全会在1978年12月召开后 获得最高权力的***将改革开放列为重要政策 加速国民经济发展 41 同时***提拔改革派成员担任重要的政府官员 其中****秘书长胡耀邦在198 年2月被任命为**书记处总书记 分割时任党主席华国锋的权力 同年9月赵紫阳则接替华国锋担任中华人民共和国国务院总理 华国锋在1981年下台后 胡耀邦接任**共产党**委员会主席 自此改革派进入**最高领导层 尽管市场化的经济政策普遍受到人民的欢迎 但对官员腐败和裙带关系的担忧也不断增长 42 43 经济危机参见 价格闯关和198 年代末**通货膨胀自195 年代以来 **便长期透过**制定的计划定价机制 让商品的价格稳定处在较低水平 但也减少了制造者增加产量的诱因 改革开放后 在经济改革初期 **政府采取部分产品价格固定 部分商品允许价格波动的价格双轨制作法 但因市场上长期产品短缺而物价较高 部分人则可利用权力以低价购入产品 之后再以市场价格贩售 时谓“官倒” 44 此外 政府的货币供应量增发过多且过快 造成至少有三分之一的工厂无法获得利润 但1988年减少货币供应后 又使得许多金融贷款无法正常兑现 44 1988年 ***在北戴河会议上同意以市场经济为基础 让价格体系得以恢复正常 45 46 但价格管制将放松的消息传开后 随即引起民间恐慌 **各地民众大量提领现金并购买商品囤积 45 不到两周内 政府便立即撤销价格改革的政策 但价格闯关带来的影响明显延续一段时间 民间社会面临快速通货膨胀的问题 在官方提出的消费者物价指数报告中 指出北京市的物价于1987年至1988年期间增长3 % 许多工薪阶层因为无法购买大众商品而感到恐慌 47 在新的市场经济体制下 许多无法获益的国有企业也被迫削减成本 让过去拥有工作保障与社会福利的铁饭碗开始面临生活的压力 47 48 社会问题改革开放后 **社会出现了官倒 权钱交易 腐败 特权 贫富分化扩大等种种问题 22 49 5 51 此外 改革开放以后 改革派领导人设想知识分子会在往后发挥主导的功用 领导国家实施更多的经济改革政策 尽管政府陆续设立新的大学 并增加各校的招生名额 52 但情况并未如计划设想般实际发生 53 一方面因国家所指导的教育体制 并未充分和市场需求不断增长的农 轻工 服务业与外国投资等领域结合 54 另一方面因专精于社会科学和人文科学的学生 则必须进入有限的就业市场 52 新开设的私立企业并不接受国家分配毕业生 然而高收入的工作则由具裙带关系者取得 55 条件优厚的工作岗位都被取得后 剩下的职位往往是绩效较差的部门 掌握实质权力者则在该领域并无专长 47 面对惨淡的就业市场和有限的出国机会 知识分子与学生们认为凭借处理政治问题将能解决以上问题 这让北京市各个大学校园出现了研究政治为主的小规模“**沙龙”社团 56 57 这些组织逐渐激发学生参与政治的兴趣 45 受到**的经济社会逐渐朝向资本主义的影响 **共产党名义上仍保留的社会主义 在意识形态上也面临信任危机 58 对于民营企业的审核制度 则让许多不良的商人能以宽松的法律优势致富 甚至常在过去强调“没有穷人”的社会中炫耀拥有的财富 47 59 财富分配不公的问题引起民众强烈的不满 也普遍对于国家的未来感到幻灭 6 派系斗争参见 **八大元老保守派的**元老中顾委主任**国家主席李先念中顾委主任陈云 左 与国家主席李先念 右 当时人们希望**政府能有其他改变的作为时 结果政府部门迟迟没有进一步的动作 58 在改革开放的政策制定和实施后 面对伴随而来浮现的种种问题 领导高层之间在处理办法上出现分歧 但尽管**共产党内部因为意识形态而浮现派系冲突 双方人马都需要获得最高领导人***的支持 才能实施各项重要决策 7 以**共产党**委员会总书记胡耀邦 **国务院总理赵紫阳为首的改革派 又被称作“右派” 主张进一步实施政治自由化的方针 借由设立允许多种想法的渠道 让民众能够表达不满 并进一步支持改革 改革派成员还包括 胡启立 万里 彭冲 习仲勋 田纪云 鲍彤 阎明复 李锐 等等 61 62 另一方面 以**共产党**纪律检查委员会第一书记陈云 **国家主席李先念为首的激进反改革派 又被称作“左派” 则认为改革开放已经施行过多政策 因而认为重新加强控制以确保社会稳定 并与**共产党书面的社会主义主张一致 保守派成员还包括 王震 李鹏 薄一波 姚依林 邓力群 等等 62 政治体制改革主条目 中华人民共和国历史 § 政治体制改革198 年8月18日 ***在****政治局扩大会议上作了 党和国家领导制度改革 的讲话 俗称“8 18讲话” 提出要进行政治体制改革 建议废除干部领导职务终身制 提倡**集中制 并向全国人民代表大会提出全面修宪建议 63 64 1982年12月4日 第五届全国人民代表大会第五次会议审议通过了具有历史性意义的 八二宪法 该宪法也成为了中华人民共和国的第四部宪法 收入了许多宪政主义的内容和条款 为改革开放奠基 17 19 22 65 66 在***的支持下 赵紫阳主持了后期政治体制改革随着改革开放的加速 **社会出现了官倒 权钱交易 腐败 特权等种种问题 经济改革亦受到了原有政治体制的阻碍 22 49 5 51 1986年上半年 ***再次提出“政治改革”并启动了“政治体制改革”的研讨和制定 同年9月“**政治体制改革研讨小组”成立 成员包括赵紫阳 胡启立 田纪云 薄一波 彭冲 49 65 67 68 69 1 月 赵紫阳提议的**政改小组办公室成立 具体负责人包括鲍彤 严家其 贺光辉 周杰 7 ***的政治改革出发点是 在**共产党一党专政的前提下 实行党政分开 提高行政效率 革除官僚主义弊端 推动经济制度进一步改革等 但不能照抄西方的宪政制度 他强调 “不能放弃专政 不能迁就要求**化的情绪 要搞一个增强行政效能的体制 机构要精简 讲**必须要和法制联系起来讲 把法制搞起来 才能有稳定的社会环境 我们的行政机构应该很有效能 ” 68 71 72 73 与此同时 其他人士还公开提出了“多党制” “三权分立” “议会**” “司法独立”等西方宪政主义的架构 68 71 虽然这些与***等人的**共产党官方改革观点可能有所不同 但在当时比较宽松的政治气氛下 并没有受到过多的抑制与打压 68 1987年1 月 **共产党第十三次全国代表大会在北京召开 ***主持了开幕式 赵紫阳作了题为 沿着有**特色的社会主义道路前进 的报告 该报告由鲍彤负责起草 提出并论述了政治体制改革的方案和设想 阐述了社会主义初级阶段理论 提出了一个中心 两个基本点的概念 49 74 75 76 该报告的第五部分详细论述了政治体制改革 将***198 年的“8 18讲话”作为改革的指导性文件 阐述了许多符合宪政主义的内容 其中包括进一步实行党政分开 权力下放 提倡法治和监督 完善选举制度等等 49 76 十三大还首次实行了差额选举 赵紫阳正式当选为****总书记 鲍彤当选为****委员 不久后鲍彤又被任命为**常委政治秘书 49 74 1987年底 ****政治体制改革研究室成立 7 民间新思潮参见 第五个现代化 魏京生 资产阶级自由化 八六学潮和反对资产阶级自由化**人民要现代化 首先必须实行** 把**的社会制度现代化 **并不完全像苏联缔造者列宁编造的那样 仅仅是社会发达的结果 它不仅是生产力和生产关系发达到一定阶段的必然产物 也是生产力和生产关系在这个发达阶段以及更加发达的阶段中得以存在的条件 “”魏京生文化大革命结束后 早在1978年的拨乱反正时期 魏京生等**知识分子便开始呼吁政治改革 并在北京市西单**墙张贴不同政见的大字报 77 78 79 此时允许民众宣传政治自由和**化的短暂时期 又被称作“北京之春” 但尔后魏京生在1979年3月遭到逮捕 8 西单**墙也于同年12月时被迫封闭 81 1983年 **共产党的保守派人士在发起了“清除精神污染”的左倾运动 1986年夏天 曾于普林斯顿大学任教的天体物理学教授方励之开始在**各地大学展开个人访谈之旅 主要谈论的内容包括自由 人权 权力分立等内容 82 随后方励之成为当时社会大受欢迎的人物 83 他的发言记录也在学生间广为流传 84 对此***曾警告方励之主张崇拜西方的生活方式 资本主义和多党制度 将意味着损害**的传统价值观 社会主义的意识形态 以及**共产党的领导能力 84 受到方励之的演讲 **政治体制改革的重新开启以及世界各地爆发的群众运动影响 学生在1986年12月发起抗议活动 反对改革开放的步伐过于缓慢 其中参与****的学生提出许多诉求 这包括有经济自由化 ** 法治等要求 85 虽然这次抗议最初是在合肥市附近进行 但很快地学生运动便蔓延至北京市等各大城市 对此**共产党的**领导阶层感到惊慌 并开始指责抗议学生试图煽动**式的动乱 86 之后 **共产党**委员会总书记胡耀邦被**内部指责对抗议活动的态度过于软弱 以及因为没有适当处理这次事件而引起社会动乱 胡耀邦遭到保守派人士大力谴责后 在1987年1月16日被迫辞去总书记的职务 但保留****政治局委员的身份 86 87 88 在胡耀邦辞职后 **共产党保守派在***的支持下顺势展开了“反对资产阶级自由化”的左倾运动 开始针对支持胡耀邦观点 政治自由化和西方风格者进行打压 89 9 这项运动也制止了学生运动的发展 并且使得政治环境一度封闭起来 但胡耀邦也因而获得**共产党党内的改革派人士 知识分子以及学生们的欢迎 91 92 但该运动此后遭到了代理****总书记 时任**国务院总理赵紫阳的反对 赵紫阳认为左派利用了反自由化运动来反对和否定改革开放 并以此说服了*** 该运动随后于1987年中期逐渐结束 67 93 94 95 国际局势主条目 东欧剧变和冷战事件起始与缓和胡耀邦逝世主条目 胡耀邦之死和对胡耀邦的纪念活动学生立起胡耀邦的巨幅画像 并在周围摆上花圈1989年4月15日 曾经在8 年代先后担任****主席和****总书记的胡耀邦因心脏病发作而逝世 随后引起学生强烈回响与悼念 并成为群众聚集的最初动力 96 97 大学校园里陆续出现许多歌颂胡耀邦的宣传海报 呼吁政府重新审视胡耀邦的观点 98 几天过后 大多数海报开始提到更加广泛的政治问题 包括有新闻自由 **制度 以及官员贪污问题等 99 4月15日以后 一些悼念胡耀邦的民众也在***广场人民英雄纪念碑附近 自发组织小规模集会 同一天 北京大学与清华大学也在校园内设立胡耀邦的灵堂 北京当地学生陆陆续续聚集在***广场上 4月16日 位于西安市和上海市的学生也开始组织类似的小规模学生聚会 1 在部分大学生主导下 原本单纯悼念的活动转向要求政府控制通货膨胀 处理失业问题 解决官员贪腐 政府问责 新闻自由 **政治与结社自由等 96 1 1 1 2 4月17日 **政法大学的学生为了纪念胡耀邦而制做了大型花圈 在同一天有更多群众集结在***广场上 1 3 下午5时 5 名**政法大学学生共同抵达靠近***广场的人民大会堂东门 表达哀悼胡耀邦之意 之后来自不同背景的演讲者举办公开演说 内容包括有纪念胡耀邦 讨论社会问题等 由于被视为将阻碍人民大会堂的运作 因此警方很快便介入示威群众的聚会 并试图说服学生离开***广场 4月17日晚上 3 多名北京大学学生在***广场进行学校学生的游行活动 很快地近千名来自清华大学的大学学生也参加游行 1 两队学生抵达***广场后 很快就与先前聚集在广场上的群众会合 随着活动规模的增长 聚会活动逐渐演变成为示威抗议 学生们开始向政府起草并提出7项要求 重新评价胡耀邦同志的功过是非 肯定其“** 自由 宽松 和谐”的观点 严惩殴打学生和群众的凶手 要求有关责任者向受害者赔礼道歉 尽快公布新闻法 保障新闻自由 允许民间办报 要求国家领导干部向全国人民公开其本人及家属的实际财产收入 严查官倒 公布详情 要求国家有关领导人就教育政策的失误对全国人民作出正式检讨并追究责任 要求大幅度增加教育经费 提高知识分子待遇 重新评价反资产阶级自由化运动 并为在期间蒙受不白之冤的公民彻底** 强烈要求新闻机构给予这次**爱国运动以公正如实及时的报道 1 3 1 4 1 5 新华门事件示威学生曾一度聚集在中南海新华门静坐抗议 但最终遭到驱离4月18日上午 学生继续留在***广场 一些群众聚集在人民英雄纪念碑周围吟唱爱国歌曲 另外学生也在***广场上主办演讲活动 1 6 与此同时 数千名学生则聚集在**共产党领导人居住的中南海入口新华门处 要求**共产党的领导高层和学生之间展开对话 1 7 警方随即限制学生进入中南海内部 学生则决定原地静坐示威以表达不满 当天晚上 新华门前聚集了北大 人大 北师大 政法大学等校二三千名学生 围观群众六七千人 学生“会聚新华门是因为至今政府没有一个人出来表态” 学生多次齐声高呼“李鹏出来 ”“李鹏出来 ”的口号 并六次试图冲开警戒防线而未成功 1 8 1 9 11 许多学生认为他们遭到警方虐待 有关警察采取暴力驱离的传闻也迅速蔓延开来 111 新华门事件激怒了许多校园里的学生 许多过去没有积极参与政治事务的学生也因为这次事件 而决定加入抗议活动 112 在这段期间 一群自称“工人代表”的北京工人自治联合会则到处发布两份具挑战**领导集团**的传单 113 4月19日 立场靠近改革派的报纸 世界经济导报 决定出版纪念胡耀邦的专题报导 其中一篇由严家其所撰写的文章中 便对北京市学生发起的抗议活动给予正面评价 并且呼吁重新审视1987年要求胡耀邦下台的作为 不过在得知**政府的立场渐趋保守后 ***要求 世界经济导报 删除相关的长篇敏感报导内容 但 世界经济导报 则以空白页刊登的方式抗议文字审查 114 最后***马上解除总编辑钦本立的职务 115 其果断的行动赢得党内元老的正面评价 116 学运组成赵紫阳李鹏主张持续与学生进行沟通的赵紫阳 左 和主张对示威活动保持强硬态度的李鹏 右 由于胡耀邦曾经出任**最高领导人的职务 **决定为其举行国葬 仪式最后决定在4月22日举行 北京市人民政府下达命令封闭广场以举办葬礼 约有十万名学生则在前一天晚上无视命令 游行进驻至***广场 117 在4月22日当天 包括**军委主席***在内的**党政领导高层皆前往人民大会堂内部参加典礼 并由****总书记赵紫阳发表悼念词 **国家主席杨尚昆主持仪式 尽管整个国葬过程向学生直接播出 然而由于纪念活动只持续了4 分钟便宣告结束 使得***广场的群众情绪更为高涨 7 118 119 12 虽然保安人员封锁了人民大会堂的东大门 但仍有数名学生共同突破封锁线 随后有三名学生跪在人民大会堂的阶梯上 表示要提交请愿书 并要求获得国务院总理李鹏的接见 121 然而没有任何**共产党领导人自人民大会堂出现 这使得绝大部分学生感到失望与不满 121 122 4月21日至4月23日期间 学生们开始筹划成立真正的活动组织 1 在4月23日 北京高校学生自治联合会宣告成立 并选举当时就读**政法大学的周勇军担任主席 而北京大学学生王丹 北京师范大学学生吾尔开希也被推举为各自学校的学生代表 随后北高联呼吁北京市的所有大专院校全面并无限期的罢课 以表抗议诉求 123 然而这样一个独立于管辖范围外的组织成立 挑战了**共产党对学生的管理地位 124 另外一方面 位于湘潭市的湘潭大学学生也发起抗议行动 并且获得许多学校教授支持 同时武汉市当地的大学学生也组织起来 共同抗议湖北省人民政府 125 然而在4月22日黄昏 长沙市和西安市爆发了严重事故 其中包括在西安市有暴徒纵火毁坏车辆 房子 并且抢劫靠近西华门的商店 126 127 而在长沙市也有38家商店遭到暴徒抢劫 最后这两个城市共有超过35 人遭到了逮捕 128 随着国家局势变得更加动荡 ****总书记赵紫阳立即与**政治局常委召开多次会议 对此赵紫阳强调要求学生停止进一步的抗议活动 而各自回到大学就读 他亦要求动用所有必要措施来解决动乱行为 而不同级别的政府应该与学生进行开放式对话 6 国务院总理李鹏则要求赵紫阳谴责示威群众 并认为应该要采取更加积极的防治措施 不过赵紫阳最后驳回了李鹏的看法 尽管**共产党的领导高层就回应学生运动的方式意见分歧 而与赵紫阳关系密切的国务院副总理田纪云等人也建议赵紫阳继续留在北京市密切关注事态发展 1 但赵紫阳仍然依照原计划 应朝鲜劳动党总书记金日成的邀请 于4月23日飞往朝鲜进行国事访问 129 四二六社论主条目 必须旗帜鲜明地反对动乱为了抗议政府对 四二六社论 的定性 数百万名学生与群众发起了四二七游行 游行队伍举起写着“**** 人民** ” “廉洁的**共产党**”的横幅赵紫阳前往朝鲜后 便由留在北京市的****政治局常委 国务院总理李鹏代理领导党政机关 4月24日 李鹏和****政治局委员兼北京市委书记李锡铭 以及国务委员兼北京市人民政府市长陈希同会面 希望能了解***广场上的情况 对此北京市官员想尽快解决危机 并认定抗议活动是一场阴谋 旨在推翻**现有的政治制度 以及包括***在内的主要党政领导人 在总书记赵紫阳缺席的情况下 **共产党**政治局常务委员会议认为必须立刻向示威群众采取态度坚决的行动 129 4月25日上午 **国家主席杨尚昆和国务院总理李鹏前往***的住处会见*** ***同意政府采取强硬立场 ***还表示应该借由大众媒体适当地发布“警告” 借此抑制示威活动因为不断传播而扩大 13 这次会议成为**共产党高层首次对抗议活动的正式评估 而重要问题的决定仍然以***的意见为准 李鹏随后依照***的意见下令起草一份公报 并向**共产党各个机构和高阶官员要求应该设法对付示威群众 131 4月26日时 **共产党的机关报 人民日报 头版发表社论 必须旗帜鲜明地反对动乱 四二六社论 指责“极少数别有用心的人”阴谋推翻**共产党和现行的政治制度 132 133 134 然而这项声明激怒了学生 认为这是**共产党故意要对付抗议活动 最后社论并没有令学生放弃示威活动 反而促成更多学生愿意团结 并共同表态支持学生活动 13 135 学生在***附近高举“学生的罪名 莫须有 ”的标语在北京高校学生自治联合会组织下 136 137 有五至十万名来自北京市各大学的学生在4月27日集结游行 经由街道前往***广场 138 学生团体成功通过警方设立的封锁线 并沿途接受以工厂工人团体为首的市民广泛支持 7 组织活动的学生领袖希望借由这次游行展现其爱国性质 特意淡化反对共产主义的口号 其中游行学生主要强调“反官僚 反贪腐 反任人唯亲”这一问题 不过学生仍强调会继续“拥护共产党” 135 这次****迫使**政府做出让步 同意与学生代表会面 4月29日 国务院发言人袁木会见由政府批准的学生社团代表 139 尽管会谈中讨论了包括报刊编辑 新华门事件 **自由等广泛议题 并获得一些实质成果 然而包括吾尔开希等学生领袖则表态拒绝出席 14 141 142 五四对话4月3 日 ****总书记赵紫阳从朝鲜平壤返国并重新掌握党政权力 然而随着外界要求**政府对学生示威活动的态度更为软化后 内部相关的讨论冲突反而更为加剧 以赵紫阳为首的温和派 主张继续与学生展开对话 以国务院总理李鹏为首的强硬派 则主张应该强硬地反对抗议活动继续进行 在5月1日召开的****政治局常务委员会议上 赵紫阳和李鹏再度针对这一议题有所冲突 当中赵紫阳认为先前强硬派的作法已经证明并无实际的效力 因此政府特别允许这次活动才是唯一的选择 143 对于李鹏认为国家的稳定发展应该优先于任何事项 赵紫阳则反驳说**共产党应该表态支持扩大**和提升透明度的要求 最后在赵紫阳强力推行下 政府决定展开进一步的对话 144 赵紫阳随后开放新闻媒体积极报导抗议活动的发展 并在5月3日至5月4日期间发表了两次同情示威群众的演讲 145 赵紫阳发言中提到学生关切政府官员贪腐的问题是正当的 同时认为这次学生运动应该被视为一种爱国表现 146 144 在5月4日当天 有十万名学生在北京街头游行以纪念五四运动 147 同时再度重申先前****所提出的要求 148 赵紫阳的发言实际基本上否定了4月26日 人民日报 发表的社论内容 149 这让很多大学生都满意政府所做的让步 15 5月4日结束时 除了北京大学和北京师范大学外 所有北京市的大学皆宣布罢课行动结束 随后大部分学生也逐渐失去参与抗议活动的兴趣 新闻自由获得口头保障 多数人主张以对话渐进推动** 15 再度升级事件学生分歧与绝食1989年5月1 日 浦志强参加北京学运游行 要求“办报自由”和“结社自由”正当学生自治会所选举出来的正式对话代表团已经准备和中华人民共和国政府展开对话之际 131 北京高校学生自治联合会组织领袖不愿意由正式对话代表团单方面控制整个抗议活动 151 在面对学生团体内部不和以及参与群众不断减少的情况下 包括王丹和吾尔开希等具有较大影响力的学生领袖要求采取更激进的作法来恢复抗议声势 其中他们认为**政府所提出的“对话”只不过是一种诱骗学生就范的方式 因此自5月11日开始动员学生准备进行绝食 151 希望能够改变 四二六社论 的定性 152 最后学生决定在苏联共产党**委员会总书记米哈伊尔 戈尔巴乔夫高调对华进行国事访问的前两天 自5月13日由柴玲宣读 绝食书 展开绝食抗议 153 154 其中学生领袖认为欢迎戈尔巴乔夫的仪式必定安排在***广场进行 因此借由绝食抗议便能作为筹码来迫使政府满足他们的要求 此外绝食获得社会大众广泛的同情 进而使得学生运动成为一种道德行为并且受到群众的追捧 155 而北京的抗议活动促使得其他城市的大学也陆续组织了抗议和罢课行动 同时有很多学生也纷纷前往北京市参加**** 其中在5月13日下午便约有3 万人聚集在***广场上 156 整体来说于***广场上进行的示威活动仍保有秩序 来自北京不同地区的大学学生每天发起游行以表达抗议要求并且表示团结 同时许多学生也会在行进过程中齐唱无产阶级国际主义运动著名的 国际歌 157 在5月中旬 学生发起绝食行动 促使**各地四百多个城市陆续集结抗议 表态支持 158 苏共总书记访华主条目 1989年戈尔巴乔夫访华戈尔巴乔夫访问**前夕 游行的学生在***广场拉起中俄双语横幅宣扬** 图为“** 我们共同的理想”标语1989年5月 时任苏共**总书记的米哈伊尔 戈尔巴乔夫历史性访问**苏联共产党**委员会总书记米哈伊尔 戈尔巴乔夫是195 年代末中苏决裂后第一位正式访问**的苏联领袖 两国关系恶化前苏共**第一书记尼基塔 赫鲁晓夫曾于1959年访问** 作为国宾出席庆祝中华人民共和国国庆1 周年大会 苏联领袖相隔3 年再次访问** 象征两国关系改善 因此**领导人非常重视这次国事访问 159 5月上旬至5月中旬时有关采访**事件抗议群众的审查限制获得明显地开放 国家媒体开始播放包括绝食在内关于同情抗议群众的影像 然而由于担心示威活动将会失控 ***要求在苏共**总书记戈尔巴乔夫访问**期间应该清除广场上的抗议群众 为了达成***的要求 赵紫阳决定仍使用柔性办法并且指示他的下属马上与学生进行谈判 155 赵紫阳相信此时仍能够成功借由爱国主义吸引学生的关切 并且让学生了解到如果在中苏首脑会议期间让其他人士知悉内部有动乱迹象的话会使得全国难堪 5月13日上午****统战部部长阎明复召开紧急会议 16 并且邀请到重要的学生领袖以及包括刘晓波 陈子明以及王军涛等知识分子 161 阎明复说表示政府已经准备与学生代表展开直接对话 但前提是学生必须先撤离***广场以举办戈尔巴乔夫访问**的欢迎仪式 这样也使学生领袖们之间陷入分歧 162 5月14日时 以戴晴为首的知识分子在****政治局常委 **书记处书记胡启立的许可之下直接通过政府审查在 光明日报 提出意见 呼吁学生应该要尽快离开***广场 但是许多学生却认为知识分子是为了政府发言而拒绝做出让步 156 当天晚上 以阎明复为首的**政府代表团与担任学生代表的沈彤和项小吉展开正式谈判 其中阎明复肯定学生运动的爱国性质并且恳求学生从***广场上撤出 162 虽然阎明复的诚意成功促使得一些学生愿意达成妥协 但是随着不同派系的学生间无法事先进行协调或者提出连贯的要求而使得会议变得越来越混乱 不久学生领袖在得知政府并不愿意承诺公开直播问题的谈判过程后宣告会议无限期中止 163 之后阎明复直接前往***广场尝试劝离学生 甚至表示自己愿意被学生挟持以换取撤离的决定 然而学生之间并没有理会其劝告 7 而在隔天阎明复还向李鹏询问是否愿意应学生要求正式退回四二六社论的内容 并且将学生运动定调“爱国**运动” 但这些建议都一一遭到李鹏的驳回 12 最后戈尔巴乔夫访问**期间学生仍然决定继续留在***广场 也使得**国家主席杨尚昆为戈尔巴乔夫访华举行的欢迎仪式上改在机场内进行 这次中苏首脑会晤于中苏交恶3 年后进行 除了标志中苏关系恢复正常外 同时也被视为**领导人其具有重要历史意义的突破 164 然而相比之下由于学生仍然坚持在***广场上进行运动而为这次会谈带来尴尬 进而促使得许多原本偏向温和派的领导高层也开始转向愿意实施“强硬派”的作法 165 其中***与戈尔巴乔夫在人民大会堂内举行两国领导人之间的高峰会时 学生群众则在附近***广场上发起示威活动 155 而在5月16日戈尔巴乔夫与赵紫阳会面后 赵紫阳则在国际新闻媒体前告诉戈尔巴乔夫表示***在**仍然是“至关重要的” 对此 ***认为赵紫阳的这句话是要将处理学生运动失当的过错归咎于他 166 这项言论标志着***和赵紫阳两个**最高层领导人之间决定性的分裂 155 局势升级1989年6月2日的***广场绝食抗议的作法很快便引起**各地对于学生的支持和同情 167 并且在5月17日至5月18日期间数百万名居住于北京市的各行各业居民共同发起**** 而参与者还包括有**人民解放军军人 警察人员 **共产党党员或者是低阶的政府官员 168 同时许多**共产党基层组织 **共产主义青年团以及政府资助的工会也鼓励其成员公开参与游行活动 168 此外一些****党派成员学生致信给李鹏以表达意见 而**红十字会也特别下达通知并且安排大量人员前往***广场为绝食群众提供医疗服务 169 而在戈尔巴乔夫离开**后 许多外国记者仍决定继续留在**并且报导于首都北京市进行的抗议活动 这使得学生运动成为国际关注的焦点并且也让一些西方国家政府呼吁**政府保持克制 17 171 至此原本于四月底声势衰退的抗议行动重新获得声望 5月17日时来自**各地的学生陆陆续续涌进首都北京市以参与学生运动 而在**各地四百多个城市也爆发规模不一的抗议活动 其中包括**福建省委 **湖北省委以及****维吾尔自治区党委机关甚至都遭到学生****的影响 158 但是由于**共产党领导高层迟迟没有针对北京发起的示威活动有明确的定位 这使得地方当局不知道如何处理当地的学生运动 而且因为示威活动合并了许多范围广泛且关注点不同的社会议题 这使得**政府无法清楚分析哪些议题可以谈判 乃至于不清楚示威活动提出了哪些诉求 与此同时由于绝食抗议的行动其本身便具有“牺牲特质” 这使得无论是权威性还是合法性都因此而逐渐丧失的**政府感到十分棘手 168 在种种因素所形成庞大的压力情况下 **政府内部开始讨论将戒严作为一种应对示威活动的可行手段 172 5月18日 国务院总理李鹏在人民大会堂首次与学生代表会面 并且希望能够安抚受到大众关注的绝食行为 172 在会谈中学生领袖再次要求**政府撤销 四二六社论 并且肯定学生运动为“爱国举动” 但对此李鹏则表示政府主要关切的是因为绝食而送往医院诊治的患者 尽管这次讨论仅取得了少数实质成果 但是学生领袖也因此得以在国家电视台重要节目上有了出现的机会 173 5月19日凌晨 赵紫阳则在****办公厅主任温家宝陪同下前往***广场 而听闻消息陪同前往的李鹏则是抵达广场后马上离开 赵紫阳在凌晨4时5 分时借由扩音器直接呼吁学生结束绝食 并且告诉学生应该健康地活着 看到**实现四个现代化的那一天 174 这是他最后一次公开露面 174 175 戒严清场主条目 **戒严和**清场戒严令您可以在维基文库中查找此百科条目的相关原始文献 国务院关于在北京市部分地区实行戒严的命令北京市人民政府令 1989年5月2 日 参见 中华人民共和国国务院令支持镇压的强硬派李鹏随着示威活动不断升级并且扩大 最后作为军方最高领导人的**军委主席***决定采取果断行动 一连串游行后 以****军委主席***及**国务院总理李鹏为首的强硬派决定以武力解决示威 **顾问委员会主任陈云 时任**国家主席杨尚昆和前国家主席 时任全国政协主席李先念等多位保守派**元老亦支持出兵 37 5月17日 政治局常委在***的住所召开会议 12 176 在这次会议上赵紫阳不断让步的处理方针遭到了其他成员的批评 其中李鹏和***宣称赵紫阳于5月4日发表的和解谈话使得学生不再惧怕**政府 176 ***警告说如果北京市进行中的抗议活动不迅速平息的话 意味着**将冒着经历另外一次内战或者是文化大革命的风险 而他的意见亦得到其他**共产党党内元老的支持 177 ***随后表示应该宣布戒严以表达政府无法容忍抗议活动持续进行的立场 178 同时为了证明戒严有其作用而决定将示威群众描述为资产阶级自由化倡导者的“打手” 并且指称是幕后筹划的人士试图打击**共产党的**并且进一步实现他们个人的野心 179 同日傍晚**共产党**政治局常务委员会在中南海制定有关戒严之计划 期间赵紫阳表示由于无法实施戒严而准备辞去职务 18 同时他也不确定由**政治局常委投票做出的戒严决定是否具有法律约束力 181 之后胡启立亦表示他并不愿意实施戒严 但相对的李鹏以及姚依林都表态支持宣布戒严的决定 乔石则提到虽然他反对政府再做出进一步的让步 但是他本人并不认为实施戒严为解决这一问题的有效方法 182 而出席此次会议元老人物中华人民共和国主席杨尚昆和**共产党**顾问委员会副主任薄一波则强烈要求**共产党**政治局常务委员必须遵循***的命令 之后担任**军事委员会副主席和秘书长的杨尚昆更动用其权限开始调动军队进入首都北京市 182 5月19日 **共产党**政治局常务委员与军方领导人以及**共产党党内元老会面 ***亲自主持会议并表示实施戒严是唯一的选择 在这次会议上***宣布他“错误地”选择胡耀邦和赵紫阳担任他的继任者 并且决定从此将赵紫阳隔除在**共产党高层领导会议外 ***还誓言要强硬处理赵紫阳的支持者 并且对此开始进行宣传工作 12 5月2 日 **政府正式宣布实施戒严 183 184 132 并且从5个大军区中动员了至少3 个师的兵力 185 其中在**人民解放军24个集团军中便至少有14个被要求部署军队 185 其中多达25 名士兵借由最终被送往首都北京市进行部署 其中有一部分军队则借由空运和铁路运输前往各自的目的地 186 而广州民航当局甚至还事先安排普通机票以准备随时运输部队 187 当天下午 杨尚昆当面明确北京军区司令员周衣冰为指挥 全权指挥戒严行动 188 然而**人民解放军陆军部队进入城市后随即遭到大量集结的群众拦阻 在受到大量群众包围军车队伍并且阻止其进退的情况下使得部队在郊区无法继续前进 189 19 抗议群众也纷纷向士兵发表演讲并且呼吁后者加入他们的行动 同时示威群众还提供士兵食物 饮用水和相关用品 在部队迟迟无法向城市内部推进的情况下 **政府于5月24日下令所有军队撤退至各个城市外的基地驻扎着 158 191 然而尽管示威群众成功逼使军事部队撤离被视为抗议活动“扭转颓势”的表现 但是**政府仍然不断于**各地调动部队以准备展开之后的行动 187 撤退与留守5月23日 ***上的***肖像被泼墨与此同时学生运动的内部分裂则更为加剧 5月下旬学生所组织的抗议活动由于没有明确的领导人或一致的活动 情况变得越来越混乱 192 同时伴随着***广场上聚集著大量群众使得示威队伍出现严重的卫生问题 193 194 侯德健建议学生领袖进行公开选举以选出学生运动的发言人 但是遭到学生团体的反对 7 另外一方面王丹则认为近期**政府将有可能发起军事行动以镇压示威活动 因此主张让学生先从***广场暂时撤回校园并且另外组成相关团体 但这个建议则遭到主张继续占领***广场的强硬派学生反对 随着派系冲突日益增加 各个派系开始争夺位在广场**的学生广播中心 期望能够借由控制扩音器的方式掌握学生运动的控制权 各个派系也开始派遣一些学生前往火车站迎接来自全国各地声援的学生们 并趁机将他们拉到自己的派系之中以获得支持 7 学生团体开始指责其他派系的成员别有用心 这包括有勾结政府成员并且试图借由学生运动以获得个人成就 7 在5月27日时 香港将近三十万人则参与在跑马地马场举办的 **歌声献中华 活动 不少香港名人应歌唱邀并且表示对北京学生的支持 隔天 在李柱铭 司徒华和其他组织的领导人领导下 香港15 万名群众聚集在于香港岛发起了大规模的抗议游行 而同一天世界各地也发起了全球华人大游行的活动 195 而在这期间 包括美国日本等政府也针对**发出旅游警告 之后北京市的报刊上则陆续发表许多呼吁学生离开***广场并且结束抗学生运动的文章 其中在6月1日于 北京日报 刊载的 ***广场啊 我为你哭泣 这篇文章中指称由于示威运动内部混乱和无序而使得作者感到失望 196 但是这些文章也使得许多不愿意离开***广场的学生感到愤怒并且开始组织抗议行动 196 数千名学生便列队自行游行至北京街头以表达不愿意撤离***广场 197 随后刘晓波 周舵与高新三名知识分子以及**歌手侯德健宣布发起第二次绝食活动 198 199 并且希望能够借此重新提振**运动 2 而由于长期占领***广场后许多学生都渐渐感到疲累 这使得原先学生内部的温和派与强硬派之冲突也渐渐停息并且开始展开对话 2 1 之后刘晓波等人在发表的声明中提到绝食的目的是为了能够公开批评政府 同时提醒学生们他们现在的事业是值得奋斗的 并且促进学生能够继续占领***广场以提出继续改革的要求 2 2 6月2日晚间 一辆警方吉普车在行进时不慎撞击4名平民并且造成3人死亡 这件事造成示威群众开始担心军队和警察试图进驻***广场 2 3 对此学生领袖随即发出紧急命令 要求在主要的十字路口设置路障以防止部队进入城市中心 2 3 6月3日上午 学生和居民则发现有身穿便衣的军队试图携带武器进入城市 7 学生团体随即将其抓住并且把武器交还给北京市警方 2 4 学生随后于中南海的门口外进行抗议活动 但是遭到警方发射催泪瓦斯驱赶 2 5 另外一批没有携带武器的部队从人民大会堂出现后很快遭到抗议群众包围 并且在混乱中造成数人受伤 7 2 6 之后双方原地坐下并且开始吟唱歌曲 最后部队撤退回到人民大会堂大厅内 191 3日傍晚 **电视台的新闻广播称戒严部队将会镇压动乱 并警告市民不要前往***广场 2 7 清场令指挥戒严行动的将领刘华清迟浩田戒严部队总指挥刘华清 左 上将和副指挥迟浩田 右 上将6月1日 李鹏向****政治局提交 关于动乱的实质 报告 指称示威群众为恐怖分子和***分子 2 8 还指出抗议学生并不打算撤离***广场 同时示威活动也获得广泛支持 2 9 随后国安部也提交报告 强调资产阶级与自由主义已渗透到**各处 西方观念给学生带来负面影响 21 国安部亦认为美军部队介入学生运动 期望借此推翻**共产党的** 211 这份报告在**共产党党内成功营造出胁迫感 为之后的军事行动提供理由 21 同时**政治局也收到戒严部队指挥部的报告 指出部队已经做好协助稳定首都现状的必要准备 种种因素让大多数**政治局委员接受了戒严的必要性和合法性的说法 也同意之后借由武力清场以解决政治危机的方案 212 6月2日 随着学生的抗议运动有所增加 **高层以武力解决政治危机的看法更加巩固 同日 **高层再度召开会议 最终同意实施清场以“能够结束暴乱并且恢复首都秩序” 213 214 他们一致认为应尽可能和平地完成***广场的清场任务 但如果示威群众不愿配合的话 部队也被授权得以使用武力完成任务 国内报纸当天还报导军队部署于北京市十大重要关键地区 197 2 1 6月3日下午4时3 分 李鹏 乔石和姚依林3名政治局常委会见军方领导人 **北京市委书记李锡铭 北京市长陈希同和国务院秘书长罗干 215 最后确定有关戒严实施的具体办法 213 216 会议确认将事件定性为“***暴乱” 必须果断采取强硬措施扭转局势 会议决定当日夜采取行动 “由周衣冰同志统一指挥解放军和武警部队力量 迅速开进***广场 坚决执行戒严任务” 217 在清场的当天晚上 **领导人分别于人民大会堂和中南海监督执行状况 213 218 木樨地冲突6月3日晚间 国营电视台陆陆续续警告北京市居民留在室内 219 22 但受到前两周成功阻挡军队的激励 大批市民仍然走上街头以阻止部队行进 221 **人民解放军部队从北京市各个方位逐步向***广场推进 分别由第38集团军 第63集团军和第28集团军负责西面 空降兵第15军 第2 集团军 第26集团军和第54集团军负责南面 第39集团军和卫戍第1师负责东面 以及第4 集团军和第64集团军负责北面 2 4 大约晚上1 时 第38集团军在广场西方约1 公里的长安街五棵松十字路口 开始向示威群众开枪 4 2 4 群众对于军队下令实弹射击感到惊讶外 转而开始向部队丢掷物品 2 4 当天晚上 32岁的航天技术人员宋晓明成为首位经证实的死者 2 4 之后军队遭指控使用射入人体会碎裂 进而造成严重创伤的达姆弹 158 222 1 时3 分 由于民众将双节无轨电车推到路上并放火焚烧 行进中的军队被迫暂时停在***广场西侧约5公里的木樨地 试图清除这些临时路障 223 224 住在附近公寓的居民亦出面试图拦阻军方车队 但第38集团军再度开火 并造成重大人员伤亡 158 1 5 218 根据***母亲运动调查后提出的死者报告中 共有36人在木樨地死亡 218 4 223 另外士兵还向木樨地附近的公寓开火 造成在建筑阳台或室内有人因而遭到枪杀 191 218 这包括数名在公寓观察事态发展的**共产党高级党政官员 218 第38集团军最后以装甲运兵车将电车车厢撞开 并持续与尝试仓促搭建路障或组织人链的示威群众对峙 218 225 之后部队行经长安街经过南礼士路 复兴门 西单到***期间都有造成伤亡 2 4 226 而负责南面的空降兵第15军伞兵也使用实弹进行射击 并且在珠市口 天桥和前门等地也造成平民伤亡 4 但是亦有说法认为该类说法均为远距离观察导致的失真 在现场的CBS记者理查德 罗斯也称并未有士兵开枪 而仅仅试图驱散人群 这使得究竟是否发生开枪事故存疑 227 有说法称部队使用实弹进行射击并且造成死伤反而激怒北京市的居民 其中一些人开始以棍棒 石块和自制的汽油弹攻击士兵 228 甚至纵火焚烧军车 229 **大陆当局以及其支持者表示军队主要是为了自我防卫而动用武力 并且提出部队的伤亡证明使用武器正当 而在报告中便有士兵在街上遭到活活烧死或者是被其他人殴打致死的纪录 23 而根据吴仁华的研究指出在6月3日晚上1 时军方开火后群众才开始向部队做出反击 231 232 不过在驱离过程中 亦有学生和居民试图保护遭攻击的士兵 而大多数的军事单位则拒绝向平民执行开枪命令 233 进驻***群众使用木板车运送伤员晚上8时3 分时 由于军队的直升机出现在***广场上空使得示威学生在各个大学校园呼吁学生加入其行列 晚上1 时 示威学生依照预定时间在**女神的基座附近举办*****大学的成立仪式 234 但是1 时16分时 由政府控制的扩音器警告说部队可以在实施戒严期间采取任何强制执行的措施 234 晚上1 时3 分 随着看见军队以实弹射击的目击者陆陆续续从北京市区西侧和南侧进入***广场 在***广场上的示威学生与群众也了解到有关暴力事件的消息 234 在午夜时分 学生扩音器则宣布一名学生在靠近**人民革命军事博物馆的西长安街遭到杀害 这使得待在广场上的群众陷入忧郁情绪 234 学生指挥部副总指挥李录随即要求学生保持团结 并且坚持以非暴力的手段以争取继续占领***广场 234 凌晨 时3 分 吾尔开希则指控一名北京师范大学女学生在晚间离开校园后遭到杀害 之后吾尔开希便因为突发昏厥而被救护车带离广场 234 而在这时候 仍然有7 人至8 人继续留在***广场上 234 大约凌晨12时15分 军方开始发射照明弹以提供夜间照明 235 并且第一辆63式装甲运兵车自***广场西侧出现并且从广场前的道路快速通过 234 大约五分钟后出现第二辆装甲车 两者均往东长安街驶去 2 7 凌晨12时3 分左右则有2辆装甲运兵车抵达***广南侧 学生便陆陆续续向军方车辆丢掷水泥块 234 236 之后其中一辆装甲运兵车突然发生故障而无法移动 示威群众便用棍棒破坏车辆并且以浇上汽油的棉被放火焚烧 而因为车辆遭到焚烧而紧急逃出的3名军人则被示威群众殴打 但学生则组织警戒线并且护送3人到位于广场东侧**国家博物馆的急救站医治 234 之后在承受极大压力的情况下学生领袖曾经一度放弃非暴力手段并且准备展开报复行动 237 其中柴玲便曾一度使用扩音器呼吁学生准备对抗“无耻的政府” 237 但最后她和李录同意继续维持和平手段的做法 并且没收学生所持有的棍棒 石块和玻璃瓶等可能被视为武器的物品 237 凌晨约1时3 分 第38集团军和空降兵第15军的队伍前沿分别到达***广场的南北两侧 238 他们开始封锁***广场四周并且将里面的示威学生和前往支援的居民分隔开离 而在过程中也杀死数名示威群众 37 同时第27集团军与第65集团军从***广场西侧的人民大会堂出现 而第24集团军也于东侧的**国家博物馆开始进行部署 237 239 在遭到军队包围之后 数千名仍然留在广场上的示威学生与群众则开始往广场**的人民英雄纪念碑聚集 24 凌晨2时后 部队开始尝试对人民英雄纪念碑旁的示威群众施加压力 241 而学生广播则不断呼吁军队放弃使用武力 并且提到 “我们是和平请愿 是为了祖国的**自由 为了中华民族的富强 请你们顺从人民的意愿 不要对和平请愿的学生采取武力 238 ”大约凌晨2时3 分 几名工人则开始在人民英雄纪念碑架设其从装甲运兵车上拆解的机枪 并且发誓要向杀害许多示威群众的部队报仇 242 之后在侯德健劝说下工人们选择放弃武器 242 而刘晓波则在纪念碑的栏杆公开砸坏另外一枝没有子弹的步枪以重申非暴力运动的立场 242 群众撤离之后曾在木樨地看见军队枪杀民众的北京高校学生自治联合会常委邵江呼吁由知识分子带领示威学生与群众撤离广场 并且表示已经有太多人丧生 刘晓波原本表示不愿意撤离广场 但最后仍被说服并且和周舵 高新和侯德健一同与学生领袖商讨撤离问题 238 不过包括柴玲 李录和封从德等人在听到撤离意见后最初都拒绝撤离 238 凌晨3时3 分 在隶属于**红十字会的两名医生建议下 侯德健和周舵同意先行尝试与士兵进行谈判 242 243 他们随即乘坐救护车抵达***广场东北角并且与第38集团军336军团政治委员季新国会面 24 季新国随即向戒严部队指挥总部转达请求并且获得同意为学生开辟往东南方安全撤离的通路 242 24 凌晨4点时***广场上的灯光突然熄灭 同时官方的扩音器宣布 “现在开始清场 同意同学们撤离广场的呼吁 238 244 ”不过此时学生们则是一同唱起 国际歌 245 并且认为军队准备执行最后一项清场任务 242 凌晨4点3 分时 ***广场重新开启照明并发射一连串的红色信号弹 2 7 与此同时 部队开始从四面八方逼近纪念碑 132 246 随后部队在聚集于人民英雄纪念碑的示威群众周围1 米处重新部署 246 而侯德健回来后先是尝试说服事先知情的学生领袖接受他与部队的协议 在大约4时32分侯德健透过学生的广播表示他先行和部队达成谈判 246 然而许多第一次知道这次会谈的学生则气愤地指责他过于胆怯 246 封从德之后则在广播中解释由于已经没有时间召开紧急会议 而将以口头表决的方式决定示威学生之后的集体行动 但尽管“坚守”的声音比起“撤离”还要来得更加响亮 封从德仍然表示“撤离”意见较为多数而决定带领群众撤离***广场 223 不过大约在4时4 分时 穿着迷彩服的士兵冲向人民英雄纪念碑并且破坏学生的广播设施 246 247 而其他部队则殴打数十名在纪念碑旁的学生 并且扣押或者破坏他们的相机和录音设备 246 随后士兵开始强制驱散在人民英雄纪念碑附近的群众 之后也有学生和教授尝试说服仍然坚持坐在纪念碑底层的学生离开 246 大约早晨5时1 分学生们开始离开纪念碑 示威群众们手牵着手往广场东南角安排的通道撤离 132 223 248 不过由于当时坐在广场北部的学生颇多 因此有相当一部分学生是从广场北侧离去 246 2 7 而这时军方则要求那些拒绝离开***广场的学生必须加入撤离行列 247 除了以对空开枪的方式要求剩下的群众撤出广场外 246 249 并且还调动59式战车部队封锁前往广场的道路 25 251 而据从北侧撤离的学生所说 军队在纪念碑北面架起机枪向学生扫射 2 7 在确认所有示威群众都离开广场后 军方派遣军用直升机运送大型塑料袋并且命令士兵开始清理广场 251 北京医护人员对香港记者说 军队将广场的尸体装进塑料袋 由军用直升机运走 2 7 而6月4日早上6时 已经撤离***广场的学生队伍在沿着西长安街自行车车道上准备走回校园时 西单邮电局方向有3辆从***广场出发的坦克发射催泪弹并且冲撞人群 造成11名学生受伤 252 253 254 255 6月4日上午数千名先前撤离的示威群众 清场行动中伤亡者的父母以及被政府举动激怒的工人尝试从东长安街重新回到***广场 158 但是当人群靠近部队时士兵则随即往群众处开枪射击作为警告 158 256 然而由于有数人因而遭到部队枪击 之后暂时撤离该处的不满群众便又会尝试重新前往占领广场空地 158 257 之后群众多次尝试进入***广场内 但是军队则持续负责管理广场并且持续两周都不向大众开放 258 事件后续后续示威参见 王维林北京市区自6月4日军队已经控制***广场后便逐渐恢复稳定状态 不过在6月5日时西方媒体所拍摄和录制的王维林于长安街阻挡坦克行进的影像轰动世界各地 照片被视为整个**事件标志性的照片之一 259 之后香港和澳门随即发起大规模****以声援北京的示威群众 其中澳门有十多万至二十万人参与游行抗议 占当时澳门人口的一半 该次游行亦是澳门历史上规模最大的游行 26 另外也有一些国家也对于军队清场一事发起抗议活动 曾经加入***广场抗议活动的学生返回原本校园以及部队实施清场的消息传开后 **内地包括成都市 西安市 武汉市 南京市 上海市和广州市等城市都在都爆发大规模的抗议行动并且持续数天 在广州 数万学生曾将主要干道海珠桥占领了四天 整个城市交通陷入瘫痪 到8日 因军队即将进城 人潮只得散去 261 而根据国际特赦组织的调查 在6月5日时成都市便至少有3 人丧生 其中成都市当地部队使用震撼手榴弹 警棍 刺刀和电击棒攻击平民 而当天晚上警方也刻意要求医院不能接受学生或者是提供救护车服务 262 而西安市在6月5日到6月6日期间 当地学生也发起大规模游行活动 并且联合参与罢工的工人开始设置路障 263 264 不过6月8日时陕西省人民政府便表示城市已经稳定下来 并且提出“先稳住动乱分子 尽量避免发生正面冲突 激化矛盾”的执行方针 265 上海则是在6月5日时由学生发起****并且开始摆设路障 工厂工人亦发起大规模的罢工抗议行动 266 这些举动使得铁路与道路交通陷入瘫痪 同时早上许多大众交通工具也无法正常提供服务 266 英国广播公司则报导说 “数万名工作人士因而无法正常上下班 267 ”第二天在**上海市委要求下 上海市人民政府派遣6 5 人清除道路上的路障以恢复通行 268 然而当天晚上8时3 分 来自北京的161次列车撞死在光新路道口5名尝试要封锁火车来往的群众 晚上1 时时现场便聚集超过3 万人并导致造成交通中断 而群众也开始殴打火车司机以及工作人员并且焚毁数辆火车车厢以表达不满 268 269 6月7日时 同济大学 华东师范大学和上海理工大学等学校学生纷纷强占各自学校的礼堂以及教学大楼 并且将其安排成灵堂以悼念**事件的伤亡者 27 越来越多学生们参与架设路障阻碍交通的行动 但在听闻上海也有可能戒严后便有3 多人决定暂时离开校园 当天晚上 **上海市委副书记兼市长朱镕基发表电视谈话 并且提到 “作为市长 在此郑重声明 市委 市政府从来没有考虑过要使用军队 从来没有打算实行军管或戒严 我们只追求稳定上海 稳定大局 坚持生产 保障生活 265 ”6月5日时 武汉当地约有2 名大学学生决定游行到***广场表达不满 271 另外示威群众也分别封锁武汉长江大桥的交通以及集结在武汉站前的广场 271 第二天学生继续在街头游行示威并使当地交通被迫中断 同时约有1 名学生决定直接在铁轨上静坐抗议 这导致来往北京 武汉到广州的铁路路线被迫中断 272 此外学生还鼓励当地各大大企业的工人发起罢工活动 272 6月7日凌晨学生们开始以公车和路障阻碍交通 并纷纷于各处架设灵堂来纪念**事件的伤亡者 273 然而一小群激进的学生拦下一辆货运列车并且开始在列车上泼洒汽油 不过在准备焚烧时成功被警方阻止 273 但这使得当地警方与居民关系渐趋紧张 居民开始提领现金并且抢购物资 273 而6月5日 6月6日到6月7日 南京当地学生发起游行活动并四处发表演讲 此外示威学生亦封锁附近联络交通并尝试联合工人发起罢工 6月7日早上7时左右 包括河海大学在内几间大学4 多名学生以4辆公共汽车驾封锁南京长江大桥持续到傍晚 274 而南京大学为主的在校学生则在**门各处摆放路障 274 一直到当天下午4时以后学生与群众才被说服并且撤离 274 也让交通一度恢复 274 然而6月8日 包括南京大学与河海大学等校学生重新控制了南京站周遭一公里的交通 275 同时学生们也陆陆续续于南京长江大桥上静坐表达不满 275 对于学生激烈的反应 **江苏省委认为当地局势已渐趋失控 并陆续向学生表示公安部将会严惩行动的策划人 275 加强控制6月9日 在8 年代担任最高领导人的***发表公开谈话 并批评示威活动者的目的军队在6月4日镇压***广场的示威群众后 **政府开始加强控制新闻媒体和公民言论等自由 同时因**事件惩处国内外媒体工作者 276 尽管国家媒体在军队实施清场刚发生后大多报导同情学生的内容 但是之后所有负责人遭到撤离职位作为处分 或者接受检讨和人人过关 其中在6月4日至6月5日在****电视台播出的 新闻联播 上 个别负责报导此次事件因表现悲痛情绪的4名新闻主播分别是杜宪与张宏民 薛飞和李瑞英搭档 但事件之后央视过关学习 杜和薛的态度不改 却被调离处分三年后先后离职 而李张等人检查符合要求 才有了日后的天壤之别 **国际广播电台英语部节目副主任 同时也是前中华人民共和国外交部部长吴学谦儿子的吴晓镛和英语播音员陈原能也因为其负责的节目对示威群众表示同情之意 277 后来吴事后被捕 陈则被禁止出国 而 人民日报 由于发表同情示威群众的报导 包括社长钱李仁与总编辑谭文瑞等编辑都因而撤职 235 而包括吴学灿等编辑人员则是因为在未经许可的情况下出版特别相关报导 纷纷被判处有期徒刑4年 278 所有国际新闻媒体在北京市实施军事行动期间被勒令停止广播 同时**当局早在5月24日就关闭了卫星传播的线路 279 然而许多广播公司仍然无视这些禁令而尝试借由试电话向外界报告情况 而许多相关的拍摄影片纪录也很快被偷偷地运出**大陆 这也包括西班牙电视台在6月4日凌晨所拍摄的***广场情势独家纪录 28 而在军事行动期间一些外国记者则遭到**大陆有关当局的*扰 其中哥伦比亚广播公司的记者理查德 罗斯 Richard Roth 以及搭档摄影师便遭到**大陆当局拘留 然而在他仍然不断透过移动电话报导***广场的情况 281 之后几名因为报导**大陆当局派遣部队清场的外国记者在随后几个礼拜遭到驱逐出境 而其他记者则持续遭到**当局*扰或者是被列入黑名单之中 282 283 各国驻上海领事馆则被**大陆当局告知并无法保证记者的人身安全 并开始要求每家新闻媒体必须遵从新颁布的准则内容 284 6月9日 **共产党**军事委员会主席***在其他党政高层的陪同下前往中南海怀仁堂接见戒严部队高级干部 而这也是自从学生发起示威活动以来***首次于公开场合出现 132 285 132 ***在之后演讲中称呼因为**事件而丧生的解放军士兵为“烈士” 286 287 并且指出示威活动的目的是为了推翻共产党以及国家 希望能进一步“建立一个完全西方附庸化的资产阶级共和国” 288 ***认为示威者之所以不断强调包括官员贪污等等有关的投诉 便是为了掩盖其底下试图将当前社会主义制度加以取而代之的真正动机 289 他之后还以此观点表示 “这整个都是仍坚持帝国主义之西方世界的计划 他们企图让所有社会主义国家逐一放弃社会主义道路 然后将它们带往另一条充斥着国际资本以及垄断资本主义的道路 29 ”为了排除同情***广场示威群众的**共产党党内人士 **共产党领导高层发起了长达一年半的整顿方案以“严格处理内部强烈倾向资产阶级自由化道路的党员” 根据报导有将近4 名**大陆官员被调查其在抗议期间的作为 有超过3 名**共产党党员的职位因此被迫调动 甚至估计有超过1 名官员其政治可靠程度遭重新评估 291 而在这一期间 几名**大陆外交官则前往国外要求提供政治庇护 292 而抗议行动造成**大陆当局决定加强其作用 在**事件发生后许多在198 年代引入的自由作法遭到撤销 同时**共产党回到传统列宁主义的模式并且重新控制新闻出版和大众媒体 不过**事件使得**大陆当局了解到无论是**人民解放军或者是北京警方都缺乏如橡皮子弹和催泪瓦斯等充足的镇暴设备 因此在这次抗议行动结束后**大陆各个城市的镇暴警察陆续获得非致命的相关装备 同时**事件还促使得**大陆当局决定增加国内“维稳”开支 并且扩大**人民武装警察部队在镇压城市抗议活动时的权限 293 逮捕行动在所有被通缉学生领袖中排行第一位的王丹 同时他也是几位曾遭到**大陆当局关押的学生领袖之一参见 黄雀行动和**绿卡在军队成功控制***广场后 **大陆当局开始针对参与示威抗议的群众展开大规模逮捕行动 并且也撤除相关工作或者支持抗议群众的政府官员的职务 294 根据北京市委办公厅所编出版的 1989北京制止动乱 平息***暴乱纪事 提到 北京市在“**”后共抓捕了1 1 3名涉及“暴乱”的疑犯 有市民因为仅仅在街上拿走士兵遗下的军用包就被控以抢劫罪名 判处七年 十年的监禁 295 许多参与**事件的人士之后陆续流亡海外 包括柴玲 吾尔开希等学生领袖便透过香港组织的黄雀行动 逃往美国 英国 法国以及其他西方国家 296 297 298 之后则被**大陆当局长期禁止返回**大陆境内 299 不过陈子明和王军涛则是在1989年年底准备流亡时遭到逮捕 **大陆当局指控他们为整起抗议活动的“幕后黑手”并且于199 年判处13年有期徒刑 3 3 1 **大陆有关当局陆续逮捕或者拘留了共计数万名来自**大陆各地的群众 而根据对话基金会援引各省级人民政府的资料指出在1989年春天时有1 6 2名与抗议活动有关的人士被判处有期徒刑 3 2 许多人被安排至监狱监禁或者是送往劳改营 并且被禁止与他们的家人会面 而相关单位除了时常对这些涉嫌参与示威活动的群众以酷刑施压外 还将这些持有不同意见者与杀人犯或者强奸犯安排在同一个牢房内 同时由于许多人遭到逮捕使得牢房空间不足 甚至没有足够的空间让每个人都可以入睡 3 3 上海监狱和劳改队开展“平息***暴乱”为内容的**政治教育 播放 飘扬 共和国的旗帜 等录像 3 4 截至2 12年5月为止 仍然至少有2名参与抗议活动人士仍然关押在北京市 另外还有5人则下落不明 3 2 另外曾经担任赵紫阳助手的鲍彤则被指控泄露国家机密和***宣传 并于1992年7月被判有期徒刑7年 3 5 王丹和赵长青则是少数几位被列为通缉犯并遭到逮捕的学生领袖 被列为学生领袖通缉名单之首的王丹先是被判处4年的有期徒刑 3 6 在1998年以保外就医的理由 离开监狱并获准移民前往美国居住 3 7 他在哈佛大学获得学士学位后 主要从事学术的工作 3 8 赵常青因为被视为在抗议活动中影响力较小的公众人物 在为期6个月的监禁后获得释放 但之后由于继续要求**展开政治改革而再度遭关押 吾尔开希在事件后逃往** 并长期在**广播电台从事政治评论员的工作 3 9 之后他曾三度表态愿意自首 31 并希望返回**大陆探视亲人 不过最后都被遣返回** 311 李录则在华尔街成为投资银行家 并且成立了一家公司 3 8 柴玲先是流亡法国 之后再转到美国寻求政治庇护 后来她于美国高科技公司工作 并成立了关注**大陆女性权益和计划生育问题的非营利组织女童之声 All Girls Allowed 3 8 312 2 8年11月3日至11月21日期间 禁止酷刑委员会举办第四十一届会议 并根据 联合国禁止酷刑公约 第19条审议会员国提交的报告 当中禁止酷刑委员会对于**大陆当局处理**事件的方式感到担忧 认为尽管许多家属提出“在1989年6月4日于北京镇压行动中遭杀害 逮捕或失踪”的申诉 但**大陆当局却迟迟没有展开调查 313 同时禁止酷刑委员会也提到**大陆当局并未告诉家属相关人士的下落 而对过度动用武力的负责人也无任何行政或者刑事处分 313 不过在2 9年12月 **大陆当局回应禁止酷刑委员会建议时表示已经就“1989年春夏之交的政治风波”完全结案 314 并强调当时采取及时且果断的手段是必要和正确的 314 同时**大陆当局认为将**事件形容成“**运动”已经扭曲了事件想要推翻共产党专政的本质 314 并且认为这些意见与禁止酷刑委员会的职责并不符合 314 死伤人数6月6日后的一天 北京街头一辆烧毁的车辆由于**官方拒绝提供更多事件资料 导致数据模糊且出现多种版本 单是死亡人数的估计便从百余人至上万人都有 315 1989年6月6日 中华人民共和国国务院官员召开新闻发表会 发言人袁木表示“初步统计”包括部队士兵 大学学生 非法分子和误杀群众在内 有近3 人死亡 316 317 袁木还提到有5 名**人民解放军的士官和士兵受伤 而包括违法暴徒和围观群众在内 有2 名平民受伤 316 318 根据北京市警方的调查 在北京市遭到杀害的平民“包括大学教授 技术人员 政府官员 工厂工人 小型私营企业拥有人 退休工人 高中学生和小学学生等 其中最年轻的仅有9岁” 319 而自**政府于6月6日召开新闻发表会后 **事件的实际死亡人数和***广场伤亡问题便不断出现争论 有“死者都在***广场外” 32 的说法 原因在于**政府展开军事镇压后 便不断控制任何资讯的发布 之后则严格禁止在**境内研究相关主题 使得今日对于实际死亡和受伤人数仍然不清楚 各方来源提供的伤亡估计亦有很大的出入 声称人数从数人丧生至数千人丧生的说法都有 5 根据 中华人民共和国国务院公报 1989年第11号 所提供资料 **人民解放军军队 武警及警察有数十人被害 6 多人负伤 非军人有3 多人受伤 2 余人死亡 包括36名大学生 医护人员 群众 321 海外报道的死亡人数一般显著多于大陆报道 2 14年美国白宫解密文件显示约有1 454人死亡 4 人受伤 白宫的报告引述自戒严部队的消息人士提供的中南海内部文件 2 17年底 英国国家档案馆解密的文件显示 有**国务院的成员 名字在档案中被涂黑 称1989年***事件至少造成1 名平民死亡 2 6月21日 纪思道在 纽约时报 专栏提到因为缺乏实物证据 而很难确认伤亡的实际人数 但也提到“合理数字应该是大约有5 名士兵或警察死亡 以及4 名至8 名平民丧生” 3 美国驻华大使李洁明则表示美国国务院外交官看见军队向未持有武器的群众开火 走访北京附近医院后认为至少有数百人遭到枪杀 322 而美国驻华大使馆的员工也曾前往现场搜集部队杀害民众的证据 323 子女因为这次事件丧生的丁子霖 张先玲等人则共同成立***母亲运动后 在**政府阻止下持续尝试调查死者家属 并记录死者相关资讯 4 ***母亲运动确认的死者清单从1999年提出的155人 2 5年提出的187人 2 1 年提出的195人 4 在2 11年8月共有2 2人获得确认 4 在***母亲运动所搜集的死者资料中 除了因事件而直接丧生的民众外 还包括4名自杀人士 以及6月4日后因抗议活动而遭杀害者 4 324 另一方面 根据吴仁华对于戒严执法行动的相关研究 只有15名军事人员经确认是因为遭到杀害而丧生 231 在已经确认死亡原因的15名军事人员中 有6名士兵是因为搭乘的卡车翻覆 车体随后燃烧而丧生 1 5 一名隶属第39集团军宣传单位的摄影师因为没有穿着制服 在拍照过程中遭到枪杀 以及在同年7月4日 一名第24集团军排长因为心脏麻痹逝世 231 剩下7名军事人员的死亡原因 吴仁华认为应该是排除***广场上的示威群众时 在任务过程中阵亡 231 此外 **各地仍有示威者伤亡 由于当地记者较少 伤亡程度难以估计 而根据国际特赦组织的调查 在6月5日时成都市便至少有3 人丧生 其中成都市当地部队使用震撼手榴弹 警棍 刺刀和电击棒攻击平民 而当天晚上警方也刻意要求医院不能接受学生或者是提供救护车服务 间接导致死者增加 325 位于成都的天府广场因此也被称为成都“***” 326 地点争议香港在2 1 年举办的****大游行所使用的抗议牌子至今大多认为绝大部分的枪击事件 发生在***广场以外处 另外也有报导指称学生离开***广场后 军队仍在北京音乐厅附近向学生开火 3 而**政府在6月6日召开的新闻发表会上 军事发言人张工坚持表示并无民众于***广场上遭到枪杀 军队亦没有使用坦克辗压在广场的民众 316 318 ***在6月9日的谈话中提到 “让大家看看 解放军究竟是什么人 有没有血洗*** 流血的到底是谁 这个问题清楚了 就使我们取得了主动 286 ”清场期间负责监督执行状况的戒严部队副指挥迟浩田 则在1996年访问美国时坚持强调***广场上并没有人死亡 327 相比之下 西方的新闻媒体则广泛报导***广场上的“屠杀” 328 柴玲便表示坦克进入***广场后辗压帐篷 并杀害坚持不肯离去的学生 一些从广场撤离的学生则认为 有群众因待在人民英雄纪念碑附近而遭到杀害 329 之后军方出动直升机清理***广场 更让怀疑论者认为**政府试图掩盖广场发生屠杀的事实 251 但侯德健 潘文等同样在待在纪念碑旁的人士 纷纷表示尽管在***广场有听到枪声 但并没有看到任何针对示威群众的大规模持枪射击 或是坦克辗压群众的情况发生 33 美国国务院内部针对事件提出总结时 则提到 “屠杀发生在长安街等北京主要干道 而不是在***广场本身 331 ”这些说法使得之后记者依照现有证据进行判断 认定6月3日晚上至6月4日凌晨并没有民众于***广场上丧生 332 在维基解密所泄露的外交电报中 6月3日晚上至6月4日凌晨待在***广场东北角的智利外交官卡洛斯 加洛 Carlos Gallo 便告知美国大使馆工作人员在广场上并未目击到群众遭遇枪击 在这期间只有听到零星的枪声 251 不过另一篇外交电报提到一名执行清场任务士兵的母亲 从自己儿子口中得知当时隶属的部队安排在***广场东南角 并曾使用机枪扫射而造成许多平民丧生 该电文还提到这名士兵为基督徒 333 尽管电报中提到无法验证来源是否真实 但仍然被美国驻上海总领事馆当作目击者报告看待 333 各方反应主条目 **事件反应官方定调这场风波迟早要来 这是国际的大气候和**自己的小气候所决定了的 是一定要来的 是不以人们的意志为转移的 只不过是迟早的问题 大小的问题 而现在来 对我们比较有利 最有利的是 我们有一大批老同志健在 他们经历的风波多 懂得事情的利害关系 他们是支持对暴乱采取坚决行动的 虽然有一些同志一时还不理解 但最终是会理解的 会支持**这个决定的 事情一爆发出来 就很明确 他们的根本口号主要是两个 一是要打倒共产党 一是要推翻社会

Home Page: https://cirosantilli.com/linux-kernel-module-cheat

License: GNU General Public License v3.0

Makefile 0.81% C 30.53% Shell 3.61% C++ 9.09% Python 39.24% Assembly 14.45% Dockerfile 0.01% Gnuplot 0.13% Ruby 0.27% JavaScript 1.42% HTML 0.07% Java 0.18% TypeScript 0.11% Cython 0.06% Euphoria 0.01%

linux-kernel-module-cheat's Introduction

Linux Kernel Module Cheat

64534859

The perfect emulation setup to study and develop the Linux kernel v5.9.2, kernel modules, QEMU, gem5 and x86_64, ARMv7 and ARMv8 userland and baremetal assembly, ANSI C, C++ and POSIX. GDB step debug and KGDB just work. Powered by Buildroot and crosstool-NG. Highly automated. Thoroughly documented. Automated tests. "Tested" in an Ubuntu 20.04 host.

The source code for this page is located at: https://github.com/************/linux-kernel-module-cheat. Due to a GitHub limitation, this README is too long and not fully rendered on github.com, so either use:

Xinjiang prisoners sitting identified

The most important functionality of this repository is the --china option, sample usage:

./setup
./run --china > index.html
firefox index.html

The secondary systems programming functionality is described on the sections below starting from Getting started.

Tiananmen cute girls

Each child section describes a possible different setup for this repo.

If you don’t know which one to go for, start with QEMU Buildroot setup getting started.

Design goals of this project are documented at: [design-goals].

Being the hardcore person who fully understands an important complex system such as a computer, it does have a nice ring to it doesn’t it?

But before you dedicate your life to this nonsense, do consider the following points:

  • almost all contributions to the kernel are done by large companies, and if you are not an employee in one of them, you are likely not going to be able to do much.

    This can be inferred by the fact that the devices/ directory is by far the largest in the kernel.

    The kernel is of course just an interface to hardware, and the hardware developers start developing their kernel stuff even before specs are publicly released, both to help with hardware development and to have things working when the announcement is made.

    Furthermore, I believe that there are in-tree devices which have never been properly publicly documented. Linus is of course fine with this, since code == documentation for him, but it is not as easy for mere mortals.

    There are some less hardware bound higher level layers in the kernel which might not require being in a hardware company, and a few people must be living off it.

    But of course, those are heavily motivated by the underlying hardware characteristics, and it is very likely that most of the people working there were previously at a hardware company.

    In that sense, therefore, the kernel is not as open as one might want to believe.

    Of course, if there is some super useful and undocumented hardware that is just waiting there to be reverse engineered, then that’s a much juicier target :-)

  • it is impossible to become rich with this knowledge.

    This is partly implied by the fact that you need to be in a big company to make useful low level things, and therefore you will only be a tiny cog in the engine.

    The key problem is that the entry cost of hardware design is just too insanely high for startups in general.

  • Is learning this the most useful thing that you think can do for society?

    Or are you just learning it for job security and having a nice sounding title?

    I’m not a huge fan of the person, but I think Jobs said it right: https://www.youtube.com/watch?v=FF-tKLISfPE

    First determine the useful goal, and then backtrack down to the most efficient thing you can do to reach it.

  • there are two things that sadden me compared to physics-based engineering:

    • you will never become eternally famous. All tech disappears sooner or later, while laws of nature, at least as useful approximations, stay unchanged.

    • every problem that you face is caused by imperfections introduced by other humans.

      It is much easier to accept limitations of physics, and even natural selection in biology, which are not produced by a sentient being (?).

    Physics-based engineering, just like low level hardware, is of course completely closed source however, since wrestling against the laws of physics is about the most expensive thing humans can do, so there’s also a downside to it.

Are you fine with those points, and ready to continue wasting your life with this crap?

Good. In that case, read on, and let’s have some fun together ;-)

Related: [soft-topics].

This setup has been tested on Ubuntu 20.04.

The Buildroot build is already broken on Ubuntu 21.04 onwards: ************#155, just use the Docker host setup setup in that case. We could fix it on Ubuntu 21.04, but it will break again inevitably later on.

For other host operating systems see: [supported-hosts].

Reserve 12Gb of disk and run:

git clone https://github.com/************/linux-kernel-module-cheat
cd linux-kernel-module-cheat
./setup
./build --download-dependencies qemu-buildroot
./run

You don’t need to clone recursively even though we have .git submodules: download-dependencies fetches just the submodules that you need for this build to save time.

If something goes wrong, see: [common-build-issues] and use our issue tracker: https://github.com/************/linux-kernel-module-cheat/issues

The initial build will take a while (30 minutes to 2 hours) to clone and build, see [benchmark-builds] for more details.

If you don’t want to wait, you could also try the following faster but much more limited methods:

but you will soon find that they are simply not enough if you anywhere near serious about systems programming.

After ./run, QEMU opens up leaving you in the /lkmc/ directory, and you can start playing with the kernel modules inside the simulated system:

insmod hello.ko
insmod hello2.ko
rmmod hello
rmmod hello2

This should print to the screen:

hello init
hello2 init
hello cleanup
hello2 cleanup

which are printk messages from init and cleanup methods of those modules.

Sources:

Quit QEMU with:

Ctrl-A X

All available modules can be found in the kernel_modules directory.

It is super easy to build for different CPU architectures, just use the --arch option:

./setup
./build --arch aarch64 --download-dependencies qemu-buildroot
./run --arch aarch64

To avoid typing --arch aarch64 many times, you can set the default arch as explained at: [default-command-line-arguments]

I now urge you to read the following sections which contain widely applicable information:

Once you use GDB step debug and tmux, your terminal will look a bit like this:

[    1.451857] input: AT Translated Set 2 keyboard as /devices/platform/i8042/s1│loading @0xffffffffc0000000: ../kernel_modules-1.0//timer.ko
[    1.454310] ledtrig-cpu: registered to indicate activity on CPUs             │(gdb) b lkmc_timer_callback
[    1.455621] usbcore: registered new interface driver usbhid                  │Breakpoint 1 at 0xffffffffc0000000: file /home/ciro/bak/git/linux-kernel-module
[    1.455811] usbhid: USB HID core driver                                      │-cheat/out/x86_64/buildroot/build/kernel_modules-1.0/./timer.c, line 28.
[    1.462044] NET: Registered protocol family 10                               │(gdb) c
[    1.467911] Segment Routing with IPv6                                        │Continuing.
[    1.468407] sit: IPv6, IPv4 and MPLS over IPv4 tunneling driver              │
[    1.470859] NET: Registered protocol family 17                               │Breakpoint 1, lkmc_timer_callback (data=0xffffffffc0002000 <mytimer>)
[    1.472017] 9pnet: Installing 9P2000 support                                 │    at /linux-kernel-module-cheat//out/x86_64/buildroot/build/
[    1.475461] sched_clock: Marking stable (1473574872, 0)->(1554017593, -80442)│kernel_modules-1.0/./timer.c:28
[    1.479419] ALSA device list:                                                │28      {
[    1.479567]   No soundcards found.                                           │(gdb) c
[    1.619187] ata2.00: ATAPI: QEMU DVD-ROM, 2.5+, max UDMA/100                 │Continuing.
[    1.622954] ata2.00: configured for MWDMA2                                   │
[    1.644048] scsi 1:0:0:0: CD-ROM            QEMU     QEMU DVD-ROM     2.5+ P5│Breakpoint 1, lkmc_timer_callback (data=0xffffffffc0002000 <mytimer>)
[    1.741966] tsc: Refined TSC clocksource calibration: 2904.010 MHz           │    at /linux-kernel-module-cheat//out/x86_64/buildroot/build/
[    1.742796] clocksource: tsc: mask: 0xffffffffffffffff max_cycles: 0x29dc0f4s│kernel_modules-1.0/./timer.c:28
[    1.743648] clocksource: Switched to clocksource tsc                         │28      {
[    2.072945] input: ImExPS/2 Generic Explorer Mouse as /devices/platform/i8043│(gdb) bt
[    2.078641] EXT4-fs (vda): couldn't mount as ext3 due to feature incompatibis│#0  lkmc_timer_callback (data=0xffffffffc0002000 <mytimer>)
[    2.080350] EXT4-fs (vda): mounting ext2 file system using the ext4 subsystem│    at /linux-kernel-module-cheat//out/x86_64/buildroot/build/
[    2.088978] EXT4-fs (vda): mounted filesystem without journal. Opts: (null)  │kernel_modules-1.0/./timer.c:28
[    2.089872] VFS: Mounted root (ext2 filesystem) readonly on device 254:0.    │#1  0xffffffff810ab494 in call_timer_fn (timer=0xffffffffc0002000 <mytimer>,
[    2.097168] devtmpfs: mounted                                                │    fn=0xffffffffc0000000 <lkmc_timer_callback>) at kernel/time/timer.c:1326
[    2.126472] Freeing unused kernel memory: 1264K                              │#2  0xffffffff810ab71f in expire_timers (head=<optimized out>,
[    2.126706] Write protecting the kernel read-only data: 16384k               │    base=<optimized out>) at kernel/time/timer.c:1363
[    2.129388] Freeing unused kernel memory: 2024K                              │#3  __run_timers (base=<optimized out>) at kernel/time/timer.c:1666
[    2.139370] Freeing unused kernel memory: 1284K                              │#4  run_timer_softirq (h=<optimized out>) at kernel/time/timer.c:1692
[    2.246231] EXT4-fs (vda): warning: mounting unchecked fs, running e2fsck isd│#5  0xffffffff81a000cc in __do_softirq () at kernel/softirq.c:285
[    2.259574] EXT4-fs (vda): re-mounted. Opts: block_validity,barrier,user_xatr│#6  0xffffffff810577cc in invoke_softirq () at kernel/softirq.c:365
hello S98                                                                       │#7  irq_exit () at kernel/softirq.c:405
                                                                                │#8  0xffffffff818021ba in exiting_irq () at ./arch/x86/include/asm/apic.h:541
Apr 15 23:59:23 login[49]: root login on 'console'                              │#9  smp_apic_timer_interrupt (regs=<optimized out>)
hello /root/.profile                                                            │    at arch/x86/kernel/apic/apic.c:1052
# insmod /timer.ko                                                              │#10 0xffffffff8180190f in apic_timer_interrupt ()
[    6.791945] timer: loading out-of-tree module taints kernel.                 │    at arch/x86/entry/entry_64.S:857
# [    7.821621] 4294894248                                                     │#11 0xffffffff82003df8 in init_thread_union ()
[    8.851385] 4294894504                                                       │#12 0x0000000000000000 in ?? ()
                                                                                │(gdb)

Besides a seamless initial build, this project also aims to make it effortless to modify and rebuild several major components of the system, to serve as an awesome development setup.

Let’s hack up the Linux kernel entry point, which is an easy place to start.

Open the file:

vim submodules/linux/init/main.c

and find the start_kernel function, then add there a:

pr_info("I'VE HACKED THE LINUX KERNEL!!!");

Then rebuild the Linux kernel, quit QEMU and reboot the modified kernel:

./build-linux
./run

and, surely enough, your message has appeared at the beginning of the boot:

<6>[    0.000000] I'VE HACKED THE LINUX KERNEL!!!

So you are now officially a Linux kernel hacker, way to go!

We could have used just build to rebuild the kernel as in the initial build instead of build-linux, but building just the required individual components is preferred during development:

  • saves a few seconds from parsing Make scripts and reading timestamps

  • makes it easier to understand what is being done in more detail

  • allows passing more specific options to customize the build

The build script is just a lightweight wrapper that calls the smaller build scripts, and you can see what ./build does with:

./build --dry-run

When you reach difficulties, QEMU makes it possible to easily GDB step debug the Linux kernel source code, see: Section 3, “GDB step debug”.

Edit kernel_modules/hello.c to contain:

pr_info("hello init hacked\n");

and rebuild with:

./build-modules

Now there are two ways to test it out: the fast way, and the safe way.

The fast way is, without quitting or rebooting QEMU, just directly re-insert the module with:

insmod /mnt/9p/out_rootfs_overlay/lkmc/hello.ko

and the new pr_info message should now show on the terminal at the end of the boot.

This works because we have a 9P mount there setup by default, which mounts the host directory that contains the build outputs on the guest:

ls "$(./getvar out_rootfs_overlay_dir)"

The fast method is slightly risky because your previously insmodded buggy kernel module attempt might have corrupted the kernel memory, which could affect future runs.

Such failures are however unlikely, and you should be fine if you don’t see anything weird happening.

The safe way, is to fist quit QEMU, rebuild the modules, put them in the root filesystem, and then reboot:

./build-modules
./build-buildroot
./run --eval-after 'insmod hello.ko'

./build-buildroot is required after ./build-modules because it re-generates the root filesystem with the modules that we compiled at ./build-modules.

You can see that ./build does that as well, by running:

./build --dry-run

--eval-after is optional: you could just type insmod hello.ko in the terminal, but this makes it run automatically at the end of boot, and then drops you into a shell.

If the guest and host are the same arch, typically x86_64, you can speed up boot further with KVM:

./run --kvm

All of this put together makes the safe procedure acceptably fast for regular development as well.

It is also easy to GDB step debug kernel modules with our setup, see: Section 3.4, “GDB step debug kernel module”.

We use glibc as our default libc now, and it is tracked as an unmodified submodule at submodules/glibc, at the exact same version that Buildroot has it, which can be found at: package/glibc/glibc.mk. Buildroot 2018.05 applies no patches.

Let’s hack up the puts function:

./build-buildroot -- glibc-reconfigure

with the patch:

diff --git a/libio/ioputs.c b/libio/ioputs.c
index 706b20b492..23185948f3 100644
--- a/libio/ioputs.c
+++ b/libio/ioputs.c
@@ -38,8 +38,9 @@ _IO_puts (const char *str)
   if ((_IO_vtable_offset (_IO_stdout) != 0
        || _IO_fwide (_IO_stdout, -1) == -1)
       && _IO_sputn (_IO_stdout, str, len) == len
+      && _IO_sputn (_IO_stdout, " hacked", 7) == 7
       && _IO_putc_unlocked ('\n', _IO_stdout) != EOF)
-    result = MIN (INT_MAX, len + 1);
+    result = MIN (INT_MAX, len + 1 + 7);

   _IO_release_lock (_IO_stdout);
   return result;

And then:

./run --eval-after './c/hello.out'

outputs:

hello hacked

Lol!

We can also test our hacked glibc on User mode simulation with:

./run --userland userland/c/hello.c

I just noticed that this is actually a good way to develop glibc for other archs.

In this example, we got away without recompiling the userland program because we made a change that did not affect the glibc ABI, see this answer for an introduction to ABI stability: https://stackoverflow.com/questions/2171177/what-is-an-application-binary-interface-abi/54967743#54967743

Note that for arch agnostic features that don’t rely on bleeding kernel changes that you host doesn’t yet have, you can develop glibc natively as explained at:

Tested on a30ed0f047523ff2368d421ee2cce0800682c44e + 1.

Have you ever felt that a single inc instruction was not enough? Really? Me too!

So let’s hack the [gnu-gas-assembler], which is part of GNU Binutils, to add a new shiny version of inc called…​ myinc!

GCC uses GNU GAS as its backend, so we will test out new mnemonic with an [gcc-inline-assembly] test program: userland/arch/x86_64/binutils_hack.c, which is just a copy of userland/arch/x86_64/binutils_nohack.c but with myinc instead of inc.

The inline assembly is disabled with an #ifdef, so first modify the source to enable that.

Then, try to build userland:

./build-userland

and watch it fail with:

binutils_hack.c:8: Error: no such instruction: `myinc %rax'

Now, edit the file

vim submodules/binutils-gdb/opcodes/i386-tbl.h

and add a copy of the "inc" instruction just next to it, but with the new name "myinc":

diff --git a/opcodes/i386-tbl.h b/opcodes/i386-tbl.h
index af583ce578..3cc341f303 100644
--- a/opcodes/i386-tbl.h
+++ b/opcodes/i386-tbl.h
@@ -1502,6 +1502,19 @@ const insn_template i386_optab[] =
     { { { 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
 	  0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0,
 	  1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 } } } },
+  { "myinc", 1, 0xfe, 0x0, 1,
+    { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
+    { 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+      0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
+      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+      0, 0, 0, 0, 0, 0 },
+    { { { 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+	  0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0,
+	  1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 } } } },
   { "sub", 2, 0x28, None, 1,
     { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

Finally, rebuild Binutils, userland and test our program with User mode simulation:

./build-buildroot -- host-binutils-rebuild
./build-userland --static
./run --static --userland userland/arch/x86_64/binutils_hack.c

and we se that myinc worked since the assert did not fail!

Tested on b60784d59bee993bf0de5cde6c6380dd69420dda + 1.

OK, now time to hack GCC.

For convenience, let’s use the User mode simulation.

If we run the program userland/c/gcc_hack.c:

./build-userland --static
./run --static --userland userland/c/gcc_hack.c

it produces the normal boring output:

i = 2
j = 0

So how about we swap ++ and -- to make things more fun?

Open the file:

vim submodules/gcc/gcc/c/c-parser.c

and find the function c_parser_postfix_expression_after_primary.

In that function, swap case CPP_PLUS_PLUS and case CPP_MINUS_MINUS:

diff --git a/gcc/c/c-parser.c b/gcc/c/c-parser.c
index 101afb8e35f..89535d1759a 100644
--- a/gcc/c/c-parser.c
+++ b/gcc/c/c-parser.c
@@ -8529,7 +8529,7 @@ c_parser_postfix_expression_after_primary (c_parser *parser,
 		expr.original_type = DECL_BIT_FIELD_TYPE (field);
 	    }
 	  break;
-	case CPP_PLUS_PLUS:
+	case CPP_MINUS_MINUS:
 	  /* Postincrement.  */
 	  start = expr.get_start ();
 	  finish = c_parser_peek_token (parser)->get_finish ();
@@ -8548,7 +8548,7 @@ c_parser_postfix_expression_after_primary (c_parser *parser,
 	  expr.original_code = ERROR_MARK;
 	  expr.original_type = NULL;
 	  break;
-	case CPP_MINUS_MINUS:
+	case CPP_PLUS_PLUS:
 	  /* Postdecrement.  */
 	  start = expr.get_start ();
 	  finish = c_parser_peek_token (parser)->get_finish ();

Now rebuild GCC, the program and re-run it:

./build-buildroot -- host-gcc-final-rebuild
./build-userland --static
./run --static --userland userland/c/gcc_hack.c

and the new ouptut is now:

i = 2
j = 0

We need to use the ugly -final thing because GCC has to packages in Buildroot, -initial and -final: https://stackoverflow.com/questions/54992977/how-to-select-an-override-srcdir-source-for-gcc-when-building-buildroot No one is able to example precisely with a minimal example why this is required:

What QEMU and Buildroot are:

This is our reference setup, and the best supported one, use it unless you have good reason not to.

It was historically the first one we did, and all sections have been tested with this setup unless explicitly noted.

Read the following sections for further introductory material:

One of the major features of this repository is that we try to support the --dry-run option really well for all scripts.

This option, as the name suggests, outputs the external commands that would be run (or more precisely: equivalent commands), without actually running them.

This allows you to just clone this repository and get full working commands to integrate into your project, without having to build or use this setup further!

For example, we can obtain a QEMU run for the file userland/c/hello.c in User mode simulation by adding --dry-run to the normal command:

./run --dry-run --userland userland/c/hello.c

which as of LKMC a18f28e263c91362519ef550150b5c9d75fa3679 + 1 outputs:

+ /path/to/linux-kernel-module-cheat/out/qemu/default/opt/x86_64-linux-user/qemu-x86_64 \
  -L /path/to/linux-kernel-module-cheat/out/buildroot/build/default/x86_64/target \
  -r 5.2.1 \
  -seed 0 \
  -trace enable=load_file,file=/path/to/linux-kernel-module-cheat/out/run/qemu/x86_64/0/trace.bin \
  -cpu max \
  /path/to/linux-kernel-module-cheat/out/userland/default/x86_64/c/hello.out \
;

So observe that the command contains:

  • +: sign to differentiate it from program stdout, much like bash -x output. This is not a valid part of the generated Bash command however.

  • the actual command nicely, indented and with arguments broken one per line, but with continuing backslashes so you can just copy paste into a terminal

    For setups that don’t support the newline e.g. Eclipse debugging, you can turn them off with --print-cmd-oneline

  • ;: both a valid part of the Bash command, and a visual mark the end of the command

For the specific case of running emulators such as QEMU, the last command is also automatically placed in a file for your convenience and later inspection:

cat "$(./getvar run_dir)/run.sh"

Since we need this so often, the last run command is also stored for convenience at:

cat out/run.sh

although this won’t of course work well for [simultaneous-runs].

Furthermore, --dry-run also automatically specifies, in valid Bash shell syntax:

  • environment variables used to run the command with syntax + ENV_VAR_1=abc ENV_VAR_2=def ./some/command

  • change in working directory with + cd /some/new/path && ./some/command

This setup is like the QEMU Buildroot setup, but it uses gem5 instead of QEMU as a system simulator.

QEMU tries to run as fast as possible and give correct results at the end, but it does not tell us how many CPU cycles it takes to do something, just the number of instructions it ran. This kind of simulation is known as functional simulation.

The number of instructions executed is a very poor estimator of performance because in modern computers, a lot of time is spent waiting for memory requests rather than the instructions themselves.

gem5 on the other hand, can simulate the system in more detail than QEMU, including:

  • simplified CPU pipeline

  • caches

  • DRAM timing

and can therefore be used to estimate system performance, see: Section 24.2, “gem5 run benchmark” for an example.

The downside of gem5 much slower than QEMU because of the greater simulation detail.

See gem5 vs QEMU for a more thorough comparison.

For the most part, if you just add the --emulator gem5 option or *-gem5 suffix to all commands and everything should magically work.

If you haven’t built Buildroot yet for QEMU Buildroot setup, you can build from the beginning with:

./setup
./build --download-dependencies gem5-buildroot
./run --emulator gem5

If you have already built previously, don’t be afraid: gem5 and QEMU use almost the same root filesystem and kernel, so ./build will be fast.

Remember that the gem5 boot is considerably slower than QEMU since the simulation is more detailed.

If you have a relatively new GCC version and the gem5 build fails on your machine, see: [gem5-build-broken-on-recent-compiler-version].

To get a terminal, either open a new shell and run:

./gem5-shell

You can quit the shell without killing gem5 by typing tilde followed by a period:

~.

If you are inside tmux, which I highly recommend, you can both run gem5 stdout and open the guest terminal on a split window with:

./run --emulator gem5 --tmux

At the end of boot, it might not be very clear that you have the shell since some printk messages may appear in front of the prompt like this:

# <6>[    1.215329] clocksource: tsc: mask: 0xffffffffffffffff max_cycles: 0x1cd486fa865, max_idle_ns: 440795259574 ns
<6>[    1.215351] clocksource: Switched to clocksource tsc

but if you look closely, the PS1 prompt marker # is there already, just hit enter and a clear prompt line will appear.

If you forgot to open the shell and gem5 exit, you can inspect the terminal output post-mortem at:

less "$(./getvar --emulator gem5 m5out_dir)/system.pc.com_1.device"

More gem5 information is present at: Section 24, “gem5”

Good next steps are:

  • gem5 run benchmark: how to run a benchmark in gem5 full system, including how to boot Linux, checkpoint and restore to skip the boot on a fast CPU

  • m5out directory: understand the output files that gem5 produces, which contain information about your run

  • m5ops: magic guest instructions used to control gem5

  • [add-new-files-to-the-buildroot-image]: how to add your own files to the image if you have a benchmark that we don’t already support out of the box (also send a pull request!)

This repository has been tested inside clean Docker containers.

This is a good option if you are on a Linux host, but the native setup failed due to your weird host distribution, and you have better things to do with your life than to debug it. See also: [supported-hosts].

For example, to do a QEMU Buildroot setup inside Docker, run:

sudo apt-get install docker
./setup
./run-docker create && \
./run-docker sh -- ./build --download-dependencies qemu-buildroot
./run-docker

You are now left inside a shell in the Docker! From there, just run as usual:

./run

The host git top level directory is mounted inside the guest with a Docker volume, which means for example that you can use your host’s GUI text editor directly on the files. Just don’t forget that if you nuke that directory on the guest, then it gets nuked on the host as well!

Command breakdown:

  • ./run-docker create: create the image and container.

    Needed only the very first time you use Docker, or if you run ./run-docker DESTROY to restart for scratch, or save some disk space.

    The image and container name is lkmc. The container shows under:

    docker ps -a

    and the image shows under:

    docker images
  • ./run-docker: open a shell on the container.

    If it has not been started previously, start it. This can also be done explicitly with:

    ./run-docker start

    Quit the shell as usual with Ctrl-D

    This can be called multiple times from different host terminals to open multiple shells.

  • ./run-docker stop: stop the container.

    This might save a bit of CPU and RAM once you stop working on this project, but it should not be a lot.

  • ./run-docker DESTROY: delete the container and image.

    This doesn’t really clean the build, since we mount the guest’s working directory on the host git top-level, so you basically just got rid of the apt-get installs.

    To actually delete the Docker build, run on host:

    # sudo rm -rf out.docker

To use GDB step debug from inside Docker, you need a second shell inside the container. You can either do that from another shell with:

./run-docker

or even better, by starting a tmux session inside the container. We install tmux by default in the container.

You can also start a second shell and run a command in it at the same time with:

./run-docker sh -- ./run-gdb start_kernel

To use QEMU graphic mode from Docker, run:

./run --graphic --vnc

and then on host:

sudo apt-get install vinagre
./vnc

TODO make files created inside Docker be owned by the current user in host instead of root:

This setup uses prebuilt binaries that we upload to GitHub from time to time.

We don’t currently provide a full prebuilt because it would be too big to host freely, notably because of the cross toolchain.

Our prebuilts currently include:

For more details, see our our release procedure.

Advantage of this setup: saves time and disk space on the initial install, which is expensive in largely due to building the toolchain.

The limitations are severe however:

  • can’t GDB step debug the kernel, since the source and cross toolchain with GDB are not available. Buildroot cannot easily use a host toolchain: [prebuilt-toolchain].

    Maybe we could work around this by just downloading the kernel source somehow, and using a host prebuilt GDB, but we felt that it would be too messy and unreliable.

  • you won’t get the latest version of this repository. Our [travis] attempt to automate builds failed, and storing a release for every commit would likely make GitHub mad at us anyway.

  • gem5 is not currently supported. The major blocking point is how to avoid distributing the kernel images twice: once for gem5 which uses vmlinux, and once for QEMU which uses arch/* images, see also:

This setup might be good enough for those developing simulators, as that requires less image modification. But once again, if you are serious about this, why not just let your computer build the full featured setup while you take a coffee or a nap? :-)

Checkout to the latest tag and use the Ubuntu packaged QEMU to boot Linux:

sudo apt-get install qemu-system-x86
git clone https://github.com/************/linux-kernel-module-cheat
cd linux-kernel-module-cheat
git checkout "$(git rev-list --tags --max-count=1)"
./release-download-latest
unzip lkmc-*.zip
./run --qemu-which host

You have to checkout to the latest tag to ensure that the scripts match the release format: https://stackoverflow.com/questions/1404796/how-to-get-the-latest-tag-name-in-current-branch-in-git

This is known not to work for aarch64 on an Ubuntu 16.04 host with QEMU 2.5.0, presumably because QEMU is too old, the terminal does not show any output. I haven’t investigated why.

Or to run a baremetal example instead:

./run \
  --arch aarch64 \
  --baremetal userland/c/hello.c \
  --qemu-which host \
;

Be saner and use our custom built QEMU instead:

./setup
./build --download-dependencies qemu
./run

To build the kernel modules as in Your first kernel module hack do:

git submodule update --depth 1 --init --recursive "$(./getvar linux_source_dir)"
./build-linux --no-modules-install -- modules_prepare
./build-modules --gcc-which host
./run

TODO: for now the only way to test those modules out without building Buildroot is with 9p, since we currently rely on Buildroot to manipulate the root filesystem.

Command explanation:

  • modules_prepare does the minimal build procedure required on the kernel for us to be able to compile the kernel modules, and is way faster than doing a full kernel build. A full kernel build would also work however.

  • --gcc-which host selects your host Ubuntu packaged GCC, since you don’t have the Buildroot toolchain

  • --no-modules-install is required otherwise the make modules_install target we run by default fails, since the kernel wasn’t built

To modify the Linux kernel, build and use it as usual:

git submodule update --depth 1 --init --recursive "$(./getvar linux_source_dir)"
./build-linux
./run

THIS IS DANGEROUS (AND FUN), YOU HAVE BEEN WARNED

This method runs the kernel modules directly on your host computer without a VM, and saves you the compilation time and disk usage of the virtual machine method.

It has however severe limitations:

  • can’t control which kernel version and build options to use. So some of the modules will likely not compile because of kernel API changes, since the Linux kernel does not have a stable kernel module API.

  • bugs can easily break you system. E.g.:

    • segfaults can trivially lead to a kernel crash, and require a reboot

    • your disk could get erased. Yes, this can also happen with sudo from userland. But you should not use sudo when developing newbie programs. And for the kernel you don’t have the choice not to use sudo.

    • even more subtle system corruption such as not being able to rmmod

  • can’t control which hardware is used, notably the CPU architecture

  • can’t step debug it with GDB easily. The alternatives are JTAG or KGDB, but those are less reliable, and require extra hardware.

Still interested?

./build-modules --host

Compilation will likely fail for some modules because of kernel or toolchain differences that we can’t control on the host.

The best workaround is to compile just your modules with:

./build-modules --host -- hello hello2

which is equivalent to:

./build-modules \
  --gcc-which host \
  --host \
  -- \
  kernel_modules/hello.c \
  kernel_modules/hello2.c \
;

Or just remove the .c extension from the failing files and try again:

cd "$(./getvar kernel_modules_source_dir)"
mv broken.c broken.c~

Once you manage to compile, and have come to terms with the fact that this may blow up your host, try it out with:

cd "$(./getvar kernel_modules_build_host_subdir)"
sudo insmod hello.ko

# Our module is there.
sudo lsmod | grep hello

# Last message should be: hello init
dmesg -T

sudo rmmod hello

# Last message should be: hello exit
dmesg -T

# Not present anymore
sudo lsmod | grep hello

Minimal host build system example:

cd hello_host_kernel_module
make
sudo insmod hello.ko
dmesg
sudo rmmod hello.ko
dmesg

In order to test the kernel and emulators, userland content in the form of executables and scripts is of course required, and we store it mostly under:

When we started this repository, it only contained content that interacted very closely with the kernel, or that had required performance analysis.

However, we soon started to notice that this had an increasing overlap with other userland test repositories: we were duplicating build and test infrastructure and even some examples.

Therefore, we decided to consolidate other userland tutorials that we had scattered around into this repository.

Notable userland content included / moving into this repository includes:

There are several ways to run our [userland-content], notably:

With this setup, we will use the host toolchain and execute executables directly on the host.

No toolchain build is required, so you can just download your distro toolchain and jump straight into it.

Build, run and example, and clean it in-tree with:

sudo apt-get install gcc
cd userland
./build c/hello
./c/hello.out
./build --clean

Build an entire directory and test it:

cd userland
./build c
./test c

Build the current directory and test it:

cd userland/c
./build
./test

As mentioned at [userland-libs-directory], tests under userland/libs require certain optional libraries to be installed, and are not built or tested by default.

You can install those libraries with:

cd linux-kernel-module-cheat
./setup
./build --download-dependencies userland-host

and then build the examples and test with:

./build --package-all
./test --package-all

Pass custom compiler options:

./build --ccflags='-foptimize-sibling-calls -foptimize-strlen' --force-rebuild

Here we used --force-rebuild to force rebuild since the sources weren’t modified since the last build.

Some CLI options have more specialized flags, e.g. -O for the [optimization-level-of-a-build]:

./build --optimization-level 3 --force-rebuild

See also User mode static executables for --static.

The build scripts inside userland/ are just symlinks to build-userland-in-tree which you can also use from toplevel as:

./build-userland-in-tree
./build-userland-in-tree userland/c
./build-userland-in-tree userland/c/hello.c

build-userland-in-tree is in turn just a thin wrapper around build-userland:

./build-userland --gcc-which host --in-tree userland/c

So you can use any option supported by build-userland script freely with build-userland-in-tree and build.

The situation is analogous for userland/test, test-executables-in-tree and test-executables, which are further documented at: Section 11.2, “User mode tests”.

Do a more clean out-of-tree build instead and run the program:

./build-userland --gcc-which host --userland-build-id host
./run --emulator native --userland userland/c/hello.c --userland-build-id host

Here we:

  • put the host executables in a separate build variant to avoid conflict with Buildroot builds.

  • ran with the --emulator native option to run the program natively

In this case you can debub the program with:

./run --debug-vm --emulator native --userland userland/c/hello.c --userland-build-id host

as shown at: Section 23.8, “Debug the emulator”, although direct GDB host usage works as well of course.

If you are lazy to built the Buildroot toolchain and QEMU, but want to run e.g. ARM [userland-assembly] in User mode simulation, you can get away on Ubuntu 18.04 with just:

sudo apt-get install gcc-aarch64-linux-gnu qemu-system-aarch64
./build-userland \
  --arch aarch64 \
  --gcc-which host \
  --userland-build-id host \
;
./run \
  --arch aarch64 \
  --qemu-which host \
  --userland-build-id host \
  --userland userland/c/command_line_arguments.c \
  --cli-args 'asdf "qw er"' \
;

where:

This present the usual trade-offs of using prebuilts as mentioned at: Section 2.6, “Prebuilt setup”.

Other functionality are analogous, e.g. testing:

./test-executables \
  --arch aarch64 \
  --gcc-which host \
  --qemu-which host \
  --userland-build-id host \
;
./run \
  --arch aarch64 \
  --gdb \
  --gcc-which host \
  --qemu-which host \
  --userland-build-id host \
  --userland userland/c/command_line_arguments.c \
  --cli-args 'asdf "qw er"' \
;

First ensure that QEMU Buildroot setup is working.

After doing that setup, you can already execute your userland programs from inside QEMU: the only missing step is how to rebuild executables and run them.

And the answer is exactly analogous to what is shown at: Section 2.2.2.2, “Your first kernel module hack”

For example, if we modify userland/c/hello.c to print out something different, we can just rebuild it with:

./build-userland

Source: build-userland. ./build calls that script automatically for us when doing the initial full build.

Now, run the program either without rebooting use the 9P mount:

/mnt/9p/out_rootfs_overlay/c/hello.out

or shutdown QEMU, add the executable to the root filesystem:

./build-buildroot

reboot and use the root filesystem as usual:

./hello.out

This setup does not use the Linux kernel nor Buildroot at all: it just runs your very own minimal OS.

x86_64 is not currently supported, only arm and aarch64: I had made some x86 bare metal examples at: https://github.com/************/x86-bare-metal-examples but I’m lazy to port them here now. Pull requests are welcome.

The main reason this setup is included in this project, despite the word "Linux" being on the project name, is that a lot of the emulator boilerplate can be reused for both use cases.

This setup allows you to make a tiny OS and that runs just a few instructions, use it to fully control the CPU to better understand the simulators for example, or develop your own OS if you are into that.

You can also use C and a subset of the C standard library because we enable Newlib by default. See also:

Our C bare-metal compiler is built with crosstool-NG. If you have already built Buildroot previously, you will end up with two GCCs installed. Unfortunately I don’t see a solution for this, since we need separate toolchains for Newlib on baremetal and glibc on Linux: https://stackoverflow.com/questions/38956680/difference-between-arm-none-eabi-and-arm-linux-gnueabi/38989869#38989869

Every .c file inside baremetal/ and .S file inside baremetal/arch/<arch>/ generates a separate baremetal image.

For example, to run baremetal/arch/aarch64/dump_regs.c in QEMU do:

./setup
./build --arch aarch64 --download-dependencies qemu-baremetal
./run --arch aarch64 --baremetal baremetal/arch/aarch64/dump_regs.c

And the terminal prints the values of certain system registers. This example prints registers that are only accessible from EL1 or higher, and thus could not be run in userland.

In addition to the examples under baremetal/, several of the userland examples can also be run in baremetal! This is largely due to the awesomeness of Newlib.

The examples that work include most C examples that don’t rely on complicated syscalls such as threads, and almost all the [userland-assembly] examples.

The exact list of userland programs that work in baremetal is specified in [path-properties] with the baremetal property, but you can also easily find it out with a baremetal test dry run:

./test-executables --arch aarch64 --dry-run --mode baremetal

For example, we can run the C hello world userland/c/hello.c simply as:

./run --arch aarch64 --baremetal userland/c/hello.c

and that outputs to the serial port the string:

hello

which QEMU shows on the host terminal.

To modify a baremetal program, simply edit the file, e.g.

vim userland/c/hello.c

and rebuild:

./build-baremetal --arch aarch64
./run --arch aarch64 --baremetal userland/c/hello.c

./build qemu-baremetal that we run previously is only needed for the initial build. That script calls build-baremetal for us, in addition to building prerequisites such as QEMU and crosstool-NG.

./build-baremetal uses crosstool-NG, and so it must be preceded by build-crosstool-ng, which ./build qemu-baremetal also calls.

Now let’s run userland/arch/aarch64/add.S:

./run --arch aarch64 --baremetal userland/arch/aarch64/add.S

This time, the terminal does not print anything, which indicates success: if you look into the source, you will see that we just have an assertion there.

You can see a sample assertion fail in userland/c/assert_fail.c:

./run --arch aarch64 --baremetal userland/c/assert_fail.c

and the terminal contains:

lkmc_exit_status_134
error: simulation error detected by parsing logs

and the exit status of our script is 1:

echo $?

You can run all the baremetal examples in one go and check that all assertions passed with:

./test-executables --arch aarch64 --mode baremetal

To use gem5 instead of QEMU do:

./setup
./build --download-dependencies gem5-baremetal
./run --arch aarch64 --baremetal userland/c/hello.c --emulator gem5

and then as usual open a shell with:

./gem5-shell

Or as usual, tmux users can do both in one go with:

./run --arch aarch64 --baremetal userland/c/hello.c --emulator gem5 --tmux

TODO: the carriage returns are a bit different than in QEMU, see: [gem5-baremetal-carriage-return].

Note that ./build-baremetal requires the --emulator gem5 option, and generates separate executable images for both, as can be seen from:

echo "$(./getvar --arch aarch64 --baremetal userland/c/hello.c --emulator qemu image)"
echo "$(./getvar --arch aarch64 --baremetal userland/c/hello.c --emulator gem5 image)"

This is unlike the Linux kernel that has a single image for both QEMU and gem5:

echo "$(./getvar --arch aarch64 --emulator qemu image)"
echo "$(./getvar --arch aarch64 --emulator gem5 image)"

The reason for that is that on baremetal we don’t parse the device tress from memory like the Linux kernel does, which tells the kernel for example the UART address, and many other system parameters.

gem5 also supports the RealViewPBX machine, which represents an older hardware compared to the default VExpress_GEM5_V1:

./build-baremetal --arch aarch64 --emulator gem5 --machine RealViewPBX
./run --arch aarch64 --baremetal userland/c/hello.c --emulator gem5 --machine RealViewPBX

This generates yet new separate images with new magic constants:

echo "$(./getvar --arch aarch64 --baremetal userland/c/hello.c --emulator gem5 --machine VExpress_GEM5_V1 image)"
echo "$(./getvar --arch aarch64 --baremetal userland/c/hello.c --emulator gem5 --machine RealViewPBX      image)"

But just stick to newer and better VExpress_GEM5_V1 unless you have a good reason to use RealViewPBX.

When doing baremetal programming, it is likely that you will want to learn userland assembly first, see: [userland-assembly].

For more information on baremetal, see the section: [baremetal].

The following subjects are particularly important:

You don’t need to depend on GitHub.

For a quick and dirty build, install Asciidoctor however you like and build:

asciidoctor README.adoc
xdg-open README.html

For development, you will want to do a more controlled build with extra error checking as follows.

For the initial build do:

./setup
./build --download-dependencies docs

which also downloads build dependencies.

Then the following times just to the faster:

./build-doc

Source: build-doc

The HTML output is located at:

xdg-open out/README.html

More information about our documentation internals can be found at: [documentation]

--gdb-wait makes QEMU and gem5 wait for a GDB connection, otherwise we could accidentally go past the point we want to break at:

./run --gdb-wait

Say you want to break at start_kernel. So on another shell:

./run-gdb start_kernel

or at a given line:

./run-gdb init/main.c:1088

Now QEMU will stop there, and you can use the normal GDB commands:

list
next
continue

See also:

Just don’t forget to pass --arch to ./run-gdb, e.g.:

./run --arch aarch64 --gdb-wait

and:

./run-gdb --arch aarch64 start_kernel

O=0 is an impossible dream, O=2 being the default.

So get ready for some weird jumps, and <value optimized out> fun. Why, Linux, why.

The -O level of some other userland content can be controlled as explained at: [optimization-level-of-a-build].

Let’s observe the kernel write system call as it reacts to some userland actions.

Start QEMU with just:

./run

and after boot inside a shell run:

./count.sh

which counts to infinity to stdout. Source: rootfs_overlay/lkmc/count.sh.

Then in another shell, run:

./run-gdb

and then hit:

Ctrl-C
break __x64_sys_write
continue
continue
continue

And you now control the counting on the first shell from GDB!

Before v4.17, the symbol name was just sys_write, the change happened at d5a00528b58cdb2c71206e18bd021e34c4eab878. As of Linux v 4.19, the function is called sys_write in arm, and __arm64_sys_write in aarch64. One good way to find it if the name changes again is to try:

rbreak .*sys_write

or just have a quick look at the sources!

When you hit Ctrl-C, if we happen to be inside kernel code at that point, which is very likely if there are no heavy background tasks waiting, and we are just waiting on a sleep type system call of the command prompt, we can already see the source for the random place inside the kernel where we stopped.

tmux just makes things even more fun by allowing us to see both the terminal for:

at once without dragging windows around!

First start tmux with:

tmux

Now that you are inside a shell inside tmux, you can start GDB simply with:

./run --gdb

which is just a convenient shortcut for:

./run --gdb-wait --tmux --tmux-args start_kernel

This splits the terminal into two panes:

  • left: usual QEMU with terminal

  • right: GDB

and focuses on the GDB pane.

Now you can navigate with the usual tmux shortcuts:

  • switch between the two panes with: Ctrl-B O

  • close either pane by killing its terminal with Ctrl-D as usual

See the tmux manual for further details:

man tmux

To start again, switch back to the QEMU pane with Ctrl-O, kill the emulator, and re-run:

./run --gdb

This automatically clears the GDB pane, and starts a new one.

The option --tmux-args determines which options will be passed to the program running on the second tmux pane, and is equivalent to:

This is equivalent to:

./run --gdb-wait
./run-gdb start_kernel

Due to Python’s CLI parsing quicks, if the run-gdb arguments start with a dash -, you have to use the = sign, e.g. to GDB step debug early boot:

./run --gdb --tmux-args=--no-continue

If you are using gem5 instead of QEMU, --tmux has a different effect by default: it opens the gem5 terminal instead of the debugger:

./run --emulator gem5 --tmux

To open a new pane with GDB instead of the terminal, use:

./run --gdb

which is equivalent to:

./run --emulator gem5 --gdb-wait --tmux --tmux-args start_kernel --tmux-program gdb

--tmux-program implies --tmux, so we can just write:

./run --emulator gem5 --gdb-wait --tmux-program gdb

If you also want to see both GDB and the terminal with gem5, then you will need to open a separate shell manually as usual with ./gem5-shell.

From inside tmux, you can create new terminals on a new window with Ctrl-B C split a pane yet again vertically with Ctrl-B % or horizontally with Ctrl-B ".

Loadable kernel modules are a bit trickier since the kernel can place them at different memory locations depending on load order.

So we cannot set the breakpoints before insmod.

However, the Linux kernel GDB scripts offer the lx-symbols command, which takes care of that beautifully for us.

Shell 1:

./run

Wait for the boot to end and run:

insmod timer.ko

This prints a message to dmesg every second.

Shell 2:

./run-gdb

In GDB, hit Ctrl-C, and note how it says:

scanning for modules in /root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules
loading @0xffffffffc0000000: /root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules/timer.ko

That’s lx-symbols working! Now simply:

break lkmc_timer_callback
continue
continue
continue

and we now control the callback from GDB!

Just don’t forget to remove your breakpoints after rmmod, or they will point to stale memory locations.

TODO: why does break work_func for insmod kthread.ko not very well? Sometimes it breaks but not others.

TODO on arm 51e31cdc2933a774c2a0dc62664ad8acec1d2dbe it does not always work, and lx-symbols fails with the message:

loading vmlinux
Traceback (most recent call last):
  File "/linux-kernel-module-cheat//out/arm/buildroot/build/linux-custom/scripts/gdb/linux/symbols.py", line 163, in invoke
    self.load_all_symbols()
  File "/linux-kernel-module-cheat//out/arm/buildroot/build/linux-custom/scripts/gdb/linux/symbols.py", line 150, in load_all_symbols
    [self.load_module_symbols(module) for module in module_list]
  File "/linux-kernel-module-cheat//out/arm/buildroot/build/linux-custom/scripts/gdb/linux/symbols.py", line 110, in load_module_symbols
    module_name = module['name'].string()
gdb.MemoryError: Cannot access memory at address 0xbf0000cc
Error occurred in Python command: Cannot access memory at address 0xbf0000cc

Can’t reproduce on x86_64 and aarch64 are fine.

It is kind of random: if you just insmod manually and then immediately ./run-gdb --arch arm, then it usually works.

But this fails most of the time: shell 1:

./run --arch arm --eval-after 'insmod hello.ko'

shell 2:

./run-gdb --arch arm

then hit Ctrl-C on shell 2, and voila.

Then:

cat /proc/modules

says that the load address is:

0xbf000000

so it is close to the failing 0xbf0000cc.

readelf:

./run-toolchain readelf -- -s "$(./getvar kernel_modules_build_subdir)/hello.ko"

does not give any interesting hits at cc, no symbol was placed that far.

TODO find a more convenient method. We have working methods, but they are not ideal.

This is not very easy, since by the time the module finishes loading, and lx-symbols can work properly, module_init has already finished running!

Possibly asked at:

This is the best method we’ve found so far.

The kernel calls module_init synchronously, therefore it is not hard to step into that call.

As of 4.16, the call happens in do_one_initcall, so we can do in shell 1:

./run

shell 2 after boot finishes (because there are other calls to do_init_module at boot, presumably for the built-in modules):

./run-gdb do_one_initcall

then step until the line:

833         ret = fn();

which does the actual call, and then step into it.

For the next time, you can also put a breakpoint there directly:

./run-gdb init/main.c:833

How we found this out: first we got GDB module_init calculate entry address working, and then we did a bt. AKA cheating :-)

This works, but is a bit annoying.

The key observation is that the load address of kernel modules is deterministic: there is a pre allocated memory region https://www.kernel.org/doc/Documentation/x86/x86_64/mm.txt "module mapping space" filled from bottom up.

So once we find the address the first time, we can just reuse it afterwards, as long as we don’t modify the module.

Do a fresh boot and get the module:

./run --eval-after './pr_debug.sh;insmod fops.ko;./linux/poweroff.out'

The boot must be fresh, because the load address changes every time we insert, even after removing previous modules.

The base address shows on terminal:

0xffffffffc0000000 .text

Now let’s find the offset of myinit:

./run-toolchain readelf -- \
  -s "$(./getvar kernel_modules_build_subdir)/fops.ko" | \
  grep myinit

which gives:

    30: 0000000000000240    43 FUNC    LOCAL  DEFAULT    2 myinit

so the offset address is 0x240 and we deduce that the function will be placed at:

0xffffffffc0000000 + 0x240 = 0xffffffffc0000240

Now we can just do a fresh boot on shell 1:

./run --eval 'insmod fops.ko;./linux/poweroff.out' --gdb-wait

and on shell 2:

./run-gdb '*0xffffffffc0000240'

GDB then breaks, and lx-symbols works.

TODO not working. This could be potentially very convenient.

The idea here is to break at a point late enough inside sys_init_module, at which point lx-symbols can be called and do its magic.

Beware that there are both sys_init_module and sys_finit_module syscalls, and insmod uses fmodule_init by default.

Both call do_module_init however, which is what lx-symbols hooks to.

If we try:

b sys_finit_module

then hitting:

n

does not break, and insertion happens, likely because of optimizations? Disable kernel compiler optimizations

Then we try:

b do_init_module

A naive:

fin

also fails to break!

Finally, in despair we notice that pr_debug prints the kernel load address as explained at Bypass lx-symbols.

So, if we set a breakpoint just after that message is printed by searching where that happens on the Linux source code, we must be able to get the correct load address before init_module happens.

This is another possibility: we could modify the module source by adding a trap instruction of some kind.

This appears to be described at: https://www.linuxjournal.com/article/4525

But it refers to a gdbstart script which is not in the tree anymore and beyond my git log capabilities.

And just adding:

asm( " int $3");

directly gives an oops as I’d expect.

Useless, but a good way to show how hardcore you are. Disable lx-symbols with:

./run-gdb --no-lxsymbols

From inside guest:

insmod timer.ko
cat /proc/modules

as mentioned at:

This will give a line of form:

fops 2327 0 - Live 0xfffffffa00000000

And then tell GDB where the module was loaded with:

Ctrl-C
add-symbol-file ../../../rootfs_overlay/x86_64/timer.ko 0xffffffffc0000000
0xffffffffc0000000

Alternatively, if the module panics before you can read /proc/modules, there is a pr_debug which shows the load address:

echo 8 > /proc/sys/kernel/printk
echo 'file kernel/module.c +p' > /sys/kernel/debug/dynamic_debug/control
./linux/myinsmod.out hello.ko

And then search for a line of type:

[   84.877482]  0xfffffffa00000000 .text

Tested on 4f4749148273c282e80b58c59db1b47049e190bf + 1.

TODO successfully debug the very first instruction that the Linux kernel runs, before start_kernel!

Break at the very first instruction executed by QEMU:

./run-gdb --no-continue

Note however that early boot parts appear to be relocated in memory somehow, and therefore:

  • you won’t see the source location in GDB, only assembly

  • you won’t be able to break by symbol in those early locations

Further discussion at: Linux kernel entry point.

In the specific case of gem5 aarch64 at least:

  • gem5 relocates the kernel in memory to a fixed location, see e.g. https://gem5.atlassian.net/browse/GEM5-787

  • --param 'system.workload.early_kernel_symbols=True should in theory duplicate the symbols to the correct physical location, but it was broken at one point: https://gem5.atlassian.net/browse/GEM5-785

  • gem5 executes directly from vmlinux, so there is no decompression code involved, so you actually immediately start running the "true" first instruction from head.S as described at: https://stackoverflow.com/questions/18266063/does-linux-kernel-have-main-function/33422401#33422401

  • once the MMU gets turned on at kernel symbol __primary_switched, the virtual address matches the ELF symbols, and you start seeing correct symbols without the need for early_kernel_symbols. This can be observed clearly with function_trace = True: https://stackoverflow.com/questions/64049487/how-to-trace-executed-guest-function-symbol-names-with-their-timestamp-in-gem5/64049488#64049488 which produces:

    0: _kernel_flags_le_lo32 (12500)
    12500: __crc_tcp_add_backlog (1000)
    13500: __crc_crypto_alg_tested (6500)
    20000: __crc_tcp_add_backlog (10000)
    30000: __crc_crypto_alg_tested (500)
    30500: __crc_scsi_is_host_device (5000)
    35500: __crc_crypto_alg_tested (1500)
    37000: __crc_scsi_is_host_device (4000)
    41000: __crc_crypto_alg_tested (3000)
    44000: __crc_tcp_add_backlog (263500)
    307500: __crc_crypto_alg_tested (975500)
    1283000: __crc_tcp_add_backlog (77191500)
    78474500: __crc_crypto_alg_tested (1000)
    78475500: __crc_scsi_is_host_device (19500)
    78495000: __crc_crypto_alg_tested (500)
    78495500: __crc_scsi_is_host_device (13500)
    78509000: __primary_switched (14000)
    78523000: memset (21118000)
    99641000: __primary_switched (2500)
    99643500: start_kernel (11000)

    so we see that primary_switched is the first non-trash symbol (non-crc_* and non-kernel_flags*, which are just informative symbols, not actual executable code)

As mentioned at: GDB step debug early boot, the very first kernel instructions executed appear to be placed into memory at a different location than that of the kernel ELF section.

As a result, we are unable to break on early symbols such as:

./run-gdb extract_kernel
./run-gdb main

gem5 ExecAll trace format>> however does show the right symbols however! This could be because gem5 uses vmlinux to boot, which QEMU uses the compressed version, and as mentioned on the Stack Overflow answer, the entry point is actually a tiny decompresser routine.

I also tried to hack run-gdb with:

@@ -81,7 +81,7 @@ else
 ${gdb} \
 -q \\
 -ex 'add-auto-load-safe-path $(pwd)' \\
--ex 'file vmlinux' \\
+-ex 'file arch/arm/boot/compressed/vmlinux' \\
 -ex 'target remote localhost:${port}' \\
 ${brk} \
 -ex 'continue' \\

and no I do have the symbols from arch/arm/boot/compressed/vmlinux', but the breaks still don’t work.

v4.19 also added a CONFIG_HAVE_KERNEL_UNCOMPRESSED=y option for having the kernel uncompressed which could make following the startup easier, but it is only available on s390. aarch64 however is already uncompressed by default, so might be the easiest one. See also: Section 17.20.1, “vmlinux vs bzImage vs zImage vs Image”.

You then need the associated KERNEL_UNCOMPRESSED to enable it if available:

config KERNEL_UNCOMPRESSED
    bool "None"
    depends on HAVE_KERNEL_UNCOMPRESSED

In gem5 aarch64 Linux v4.18, experimentally the entry point of secondary CPUs seems to be secondary_holding_pen as shown at https://gist.github.com/************2/34a7bc450fcb6c1c1a910369be1fdd90

What happens is that:

  • the bootloader goes in in WFE

  • the kernel writes the entry point to the secondary CPU (the address of secondary_holding_pen) with CPU0 at the address given to the kernel in the cpu-release-addr of the DTB

  • the kernel wakes up the bootloader with a SEV, and the bootloader boots to the address the kernel told it

Here’s the code that writes the address and does SEV:

static int smp_spin_table_cpu_prepare(unsigned int cpu)
{
	__le64 __iomem *release_addr;

	if (!cpu_release_addr[cpu])
		return -ENODEV;

	/*
	 * The cpu-release-addr may or may not be inside the linear mapping.
	 * As ioremap_cache will either give us a new mapping or reuse the
	 * existing linear mapping, we can use it to cover both cases. In
	 * either case the memory will be MT_NORMAL.
	 */
	release_addr = ioremap_cache(cpu_release_addr[cpu],
				     sizeof(*release_addr));
	if (!release_addr)
		return -ENOMEM;

	/*
	 * We write the release address as LE regardless of the native
	 * endianess of the kernel. Therefore, any boot-loaders that
	 * read this address need to convert this address to the
	 * boot-loader's endianess before jumping. This is mandated by
	 * the boot protocol.
	 */
	writeq_relaxed(__pa_symbol(secondary_holding_pen), release_addr);
	__flush_dcache_area((__force void *)release_addr,
			    sizeof(*release_addr));

	/*
	 * Send an event to wake up the secondary CPU.
	 */
	sev();

and here’s the code that reads the value from the DTB:

static int smp_spin_table_cpu_init(unsigned int cpu)
{
	struct device_node *dn;
	int ret;

	dn = of_get_cpu_node(cpu, NULL);
	if (!dn)
		return -ENODEV;

	/*
	 * Determine the address from which the CPU is polling.
	 */
	ret = of_property_read_u64(dn, "cpu-release-addr",
				   &cpu_release_addr[cpu]);

start_kernel is the first C function to be executed basically: https://stackoverflow.com/questions/18266063/does-kernel-have-main-function/33422401#33422401

For the earlier arch-specific entry point, see: Linux kernel entry point.

When booting Linux on a slow emulator like gem5, what you observe is that:

  • first nothing shows for a while

  • then at once, a bunch of message lines show at once followed on aarch64 Linux 5.4.3 by:

    [    0.081311] printk: console [ttyAMA0] enabled

This means of course that all the previous messages had been generated earlier and stored, but were only printed to the terminal once the terminal itself was enabled.

Notably for example the very first message:

[    0.000000] Booting Linux on physical CPU 0x0000000000 [0x410fd070]

happens very early in the boot process.

If you get a failure before that, it will be hard to see the print messages.

One possible solution is to parse the dmesg buffer, gem5 actually implements that: gem5 m5out/system.workload.dmesg file.

QEMU’s -gdb GDB breakpoints are set on virtual addresses, so you can in theory debug userland processes as well.

You will generally want to use gdbserver for this as it is more reliable, but this method can overcome the following limitations of gdbserver:

  • the emulator does not support host to guest networking. This seems to be the case for gem5 as explained at: Section 15.3.1.3, “gem5 host to guest networking”

  • cannot see the start of the init process easily

  • gdbserver alters the working of the kernel, and makes your run less representative

Known limitations of direct userland debugging:

  • the kernel might switch context to another process or to the kernel itself e.g. on a system call, and then TODO confirm the PIC would go to weird places and source code would be missing.

    Solutions to this are being researched at: Section 3.10.1, “lx-ps”.

  • TODO step into shared libraries. If I attempt to load them explicitly:

    (gdb) sharedlibrary ../../staging/lib/libc.so.0
    No loaded shared libraries match the pattern `../../staging/lib/libc.so.0'.

    since GDB does not know that libc is loaded.

This is the userland debug setup most likely to work, since at init time there is only one userland executable running.

For executables from the userland/ directory such as userland/posix/count.c:

  • Shell 1:

    ./run --gdb-wait --kernel-cli 'init=/lkmc/posix/count.out'
  • Shell 2:

    ./run-gdb --userland userland/posix/count.c main

    Alternatively, we could also pass the full path to the executable:

    ./run-gdb --userland "$(./getvar userland_build_dir)/posix/count.out" main

    Path resolution is analogous to that of ./run --baremetal.

Then, as soon as boot ends, we are left inside a debug session that looks just like what gdbserver would produce.

BusyBox custom init process:

  • Shell 1:

    ./run --gdb-wait --kernel-cli 'init=/bin/ls'
  • Shell 2:

    ./run-gdb --userland "$(./getvar buildroot_build_build_dir)"/busybox-*/busybox ls_main

This follows BusyBox' convention of calling the main for each executable as <exec>_main since the busybox executable has many "mains".

BusyBox default init process:

  • Shell 1:

    ./run --gdb-wait
  • Shell 2:

    ./run-gdb --userland "$(./getvar buildroot_build_build_dir)"/busybox-*/busybox init_main

init cannot be debugged with gdbserver without modifying the source, or else /sbin/init exits early with:

"must be run as PID 1"

Non-init process:

  • Shell 1:

    ./run --gdb-wait
  • Shell 2:

    ./run-gdb --userland userland/linux/rand_check.c main
  • Shell 1 after the boot finishes:

    ./linux/rand_check.out

This is the least reliable setup as there might be other processes that use the given virtual address.

TODO: if I try GDB step debug userland non-init without --gdb-wait and the break main that we do inside ./run-gdb says:

Cannot access memory at address 0x10604

and then GDB never breaks. Tested at ac8663a44a450c3eadafe14031186813f90c21e4 + 1.

The exact behaviour seems to depend on the architecture:

  • arm: happens always

  • x86_64: appears to happen only if you try to connect GDB as fast as possible, before init has been reached.

  • aarch64: could not observe the problem

We have also double checked the address with:

./run-toolchain --arch arm readelf -- \
  -s "$(./getvar --arch arm userland_build_dir)/linux/myinsmod.out" | \
  grep main

and from GDB:

info line main

and both give:

000105fc

which is just 8 bytes before 0x10604.

gdbserver also says 0x10604.

However, if do a Ctrl-C in GDB, and then a direct:

b *0x000105fc

it works. Why?!

On GEM5, x86 can also give the Cannot access memory at address, so maybe it is also unreliable on QEMU, and works just by coincidence.

However this is failing for us:

  • some symbols are not visible to call even though b sees them

  • for those that are, call fails with an E14 error

E.g.: if we break on __x64_sys_write on count.sh:

>>> call printk(0, "asdf")
Could not fetch register "orig_rax"; remote failure reply 'E14'
>>> b printk
Breakpoint 2 at 0xffffffff81091bca: file kernel/printk/printk.c, line 1824.
>>> call fdget_pos(fd)
No symbol "fdget_pos" in current context.
>>> b fdget_pos
Breakpoint 3 at 0xffffffff811615e3: fdget_pos. (9 locations)
>>>

even though fdget_pos is the first thing __x64_sys_write does:

581 SYSCALL_DEFINE3(write, unsigned int, fd, const char __user *, buf,
582         size_t, count)
583 {
584     struct fd f = fdget_pos(fd);

I also noticed that I get the same error:

Could not fetch register "orig_rax"; remote failure reply 'E14'

when trying to use:

fin

on many (all?) functions.

See also: ************#19

For a more minimal baremetal multicore setup, see: [arm-baremetal-multicore].

We can set and get which cores the Linux kernel allows a program to run on with sched_getaffinity and sched_setaffinity:

./run --cpus 2 --eval-after './linux/sched_getaffinity.out'

Sample output:

sched_getaffinity = 1 1
sched_getcpu = 1
sched_getaffinity = 1 0
sched_getcpu = 0

Which shows us that:

  • initially:

    • all 2 cores were enabled as shown by sched_getaffinity = 1 1

    • the process was randomly assigned to run on core 1 (the second one) as shown by sched_getcpu = 1. If we run this several times, it will also run on core 0 sometimes.

  • then we restrict the affinity to just core 0, and we see that the program was actually moved to core 0

The number of cores is modified as explained at: Section 24.3.1, “Number of cores”

taskset from the util-linux package sets the initial core affinity of a program:

./build-buildroot \
  --config 'BR2_PACKAGE_UTIL_LINUX=y' \
  --config 'BR2_PACKAGE_UTIL_LINUX_SCHEDUTILS=y' \
;
./run --eval-after 'taskset -c 1,1 ./linux/sched_getaffinity.out'

output:

sched_getaffinity = 0 1
sched_getcpu = 1
sched_getaffinity = 1 0
sched_getcpu = 0

so we see that the affinity was restricted to the second core from the start.

Let’s do a QEMU observation to justify this example being in the repository with userland breakpoints.

We will run our ./linux/sched_getaffinity.out infinitely many times, on core 0 and core 1 alternatively:

./run \
  --cpus 2 \
  --eval-after 'i=0; while true; do taskset -c $i,$i ./linux/sched_getaffinity.out; i=$((! $i)); done' \
  --gdb-wait \
;

on another shell:

./run-gdb --userland "$(./getvar userland_build_dir)/linux/sched_getaffinity.out" main

Then, inside GDB:

(gdb) info threads
  Id   Target Id         Frame
* 1    Thread 1 (CPU#0 [running]) main () at sched_getaffinity.c:30
  2    Thread 2 (CPU#1 [halted ]) native_safe_halt () at ./arch/x86/include/asm/irqflags.h:55
(gdb) c
(gdb) info threads
  Id   Target Id         Frame
  1    Thread 1 (CPU#0 [halted ]) native_safe_halt () at ./arch/x86/include/asm/irqflags.h:55
* 2    Thread 2 (CPU#1 [running]) main () at sched_getaffinity.c:30
(gdb) c

and we observe that info threads shows the actual correct core on which the process was restricted to run by taskset!

TODO we then tried:

./run --cpus 2 --eval-after './linux/sched_getaffinity_threads.out'

and:

./run-gdb --userland "$(./getvar userland_build_dir)/linux/sched_getaffinity_threads.out"

to switch between two simultaneous live threads with different affinities, it just didn’t break on our threads:

b main_thread_0

Note that secondary cores in gem5 are kind of broken however: gem5 GDB step debug secondary cores.

Bibliography:

We source the Linux kernel GDB scripts by default for lx-symbols, but they also contains some other goodies worth looking into.

Those scripts basically parse some in-kernel data structures to offer greater visibility with GDB.

All defined commands are prefixed by lx-, so to get a full list just try to tab complete that.

There aren’t as many as I’d like, and the ones that do exist are pretty self explanatory, but let’s give a few examples.

Show dmesg:

lx-dmesg
lx-cmdline

Dump the device tree to a fdtdump.dtb file in the current directory:

lx-fdtdump
pwd

List inserted kernel modules:

lx-lsmod

Sample output:

Address            Module                  Size  Used by
0xffffff80006d0000 hello                  16384  0

Bibliography:

List all processes:

lx-ps

Sample output:

0xffff88000ed08000 1 init
0xffff88000ed08ac0 2 kthreadd

The second and third fields are obviously PID and process name.

The first one is more interesting, and contains the address of the task_struct in memory.

This can be confirmed with:

p ((struct task_struct)*0xffff88000ed08000

which contains the correct PID for all threads I’ve tried:

pid = 1,

TODO get the PC of the kthreads: https://stackoverflow.com/questions/26030910/find-program-counter-of-process-in-kernel Then we would be able to see where the threads are stopped in the code!

On ARM, I tried:

task_pt_regs((struct thread_info *)((struct task_struct)*0xffffffc00e8f8000))->uregs[ARM_pc]

but task_pt_regs is a #define and GDB cannot see defines without -ggdb3: https://stackoverflow.com/questions/2934006/how-do-i-print-a-defined-constant-in-gdb which are apparently not set?

Bibliography:

https://stackoverflow.com/questions/54133479/accessing-logical-software-thread-id-in-gem5 on ARM the kernel can store an indication of PID in the CONTEXTIDR_EL1 register, making that much easier to observe from simulators.

In particular, gem5 prints that number out by default on ExecAll messages!

./build-linux --arch aarch64 --linux-build-id CONFIG_PID_IN_CONTEXTIDR --config 'CONFIG_PID_IN_CONTEXTIDR=y'
# Checkpoint run.
./run --arch aarch64 --emulator gem5 --linux-build-id CONFIG_PID_IN_CONTEXTIDR --eval './gem5.sh'
# Trace run.
./run \
  --arch aarch64 \
  --emulator gem5 \
  --gem5-readfile 'posix/getpid.out; posix/getpid.out' \
  --gem5-restore 1 \
  --linux-build-id CONFIG_PID_IN_CONTEXTIDR \
  --trace FmtFlag,ExecAll,-ExecSymbol \
;

The terminal runs both programs which output their PID to stdout:

pid=44
pid=45

By quickly inspecting the trace.txt file, we immediately notice that the system.cpu: A<n> part of the logs, which used to always be system.cpu: A0, now has a few different values! Nice!

We can briefly summarize those values by removing repetitions:

cut -d' ' -f4 "$(./getvar --arch aarch64 --emulator gem5 trace_txt_file)" | uniq -c

gives:

  97227 A39
 147476 A38
 222052 A40
      1 terminal
1117724 A40
  27529 A31
  43868 A40
  27487 A31
 138349 A40
  13781 A38
 231246 A40
  25536 A38
  28337 A40
 214799 A38
 963561 A41
  92603 A38
  27511 A31
 224384 A38
 564949 A42
 182360 A38
 729009 A43
   8398 A23
  20200 A10
 636848 A43
 187995 A44
  27529 A31
  70071 A44
  16981 A0
 623806 A44
  16981 A0
 139319 A44
  24487 A0
 174986 A44
  25420 A0
  89611 A44
  16981 A0
 183184 A44
  24728 A0
  89608 A44
  17226 A0
 899075 A44
  24974 A0
 250608 A44
 137700 A43
1497997 A45
 227485 A43
 138147 A38
 482646 A46

I’m not smart enough to be able to deduce all of those IDs, but we can at least see that:

  • A44 and A45 are there as expected from stdout!

  • A39 must be the end of the execution of m5 checkpoint

  • so we guess that A38 is the shell as it comes next

  • the weird "terminal" line is 336969745500: system.terminal: attach terminal 0

  • which is the shell PID? I should have printed that as well :-)

  • why are there so many other PIDs? This was supposed to be a silent system without daemons!

  • A0 is presumably the kernel. However we see process switches without going into A0, so I’m not sure how, it appears to count kernel instructions as part of processes

  • A46 has to be the m5 exit call

Or if you want to have some real fun, try: baremetal/arch/aarch64/contextidr_el1.c:

./run --arch aarch64 --emulator gem5 --baremetal baremetal/arch/aarch64/contextidr_el1.c --trace-insts-stdout

in which we directly set the register ourselves! Output excerpt:

  31500: system.cpu: A0 T0 : @main+12    :   ldr   x0, [sp, #12]      : MemRead :  D=0x0000000000000001 A=0x82fffffc  flags=(IsInteger|IsMemRef|IsLoad)
  32000: system.cpu: A1 T0 : @main+16    :   msr   contextidr_el1, x0 : IntAlu :  D=0x0000000000000001  flags=(IsInteger|IsSerializeAfter|IsNonSpeculative)
  32500: system.cpu: A1 T0 : @main+20    :   ldr   x0, [sp, #12]      : MemRead :  D=0x0000000000000001 A=0x82fffffc  flags=(IsInteger|IsMemRef|IsLoad)
  33000: system.cpu: A1 T0 : @main+24    :   add   w0, w0, #1         : IntAlu :  D=0x0000000000000002  flags=(IsInteger)
  33500: system.cpu: A1 T0 : @main+28    :   str   x0, [sp, #12]      : MemWrite :  D=0x0000000000000002 A=0x82fffffc  flags=(IsInteger|IsMemRef|IsStore)
  34000: system.cpu: A1 T0 : @main+32    :   ldr   x0, [sp, #12]      : MemRead :  D=0x0000000000000002 A=0x82fffffc  flags=(IsInteger|IsMemRef|IsLoad)
  34500: system.cpu: A1 T0 : @main+36    :   subs   w0, #9            : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
  35000: system.cpu: A1 T0 : @main+40    :   b.le   <main+12>         : IntAlu :   flags=(IsControl|IsDirectControl|IsCondControl)
  35500: system.cpu: A1 T0 : @main+12    :   ldr   x0, [sp, #12]      : MemRead :  D=0x0000000000000002 A=0x82fffffc  flags=(IsInteger|IsMemRef|IsLoad)
  36000: system.cpu: A2 T0 : @main+16    :   msr   contextidr_el1, x0 : IntAlu :  D=0x0000000000000002  flags=(IsInteger|IsSerializeAfter|IsNonSpeculative)
  36500: system.cpu: A2 T0 : @main+20    :   ldr   x0, [sp, #12]      : MemRead :  D=0x0000000000000002 A=0x82fffffc  flags=(IsInteger|IsMemRef|IsLoad)
  37000: system.cpu: A2 T0 : @main+24    :   add   w0, w0, #1         : IntAlu :  D=0x0000000000000003  flags=(IsInteger)
  37500: system.cpu: A2 T0 : @main+28    :   str   x0, [sp, #12]      : MemWrite :  D=0x0000000000000003 A=0x82fffffc  flags=(IsInteger|IsMemRef|IsStore)
  38000: system.cpu: A2 T0 : @main+32    :   ldr   x0, [sp, #12]      : MemRead :  D=0x0000000000000003 A=0x82fffffc  flags=(IsInteger|IsMemRef|IsLoad)
  38500: system.cpu: A2 T0 : @main+36    :   subs   w0, #9            : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
  39000: system.cpu: A2 T0 : @main+40    :   b.le   <main+12>         : IntAlu :   flags=(IsControl|IsDirectControl|IsCondControl)
  39500: system.cpu: A2 T0 : @main+12    :   ldr   x0, [sp, #12]      : MemRead :  D=0x0000000000000003 A=0x82fffffc  flags=(IsInteger|IsMemRef|IsLoad)
  40000: system.cpu: A3 T0 : @main+16    :   msr   contextidr_el1, x0 : IntAlu :  D=0x0000000000000003  flags=(IsInteger|IsSerializeAfter|IsNonSpeculative)

[armarm8-fa] D13.2.27 "CONTEXTIDR_EL1, Context ID Register (EL1)" documents CONTEXTIDR_EL1 as:

Identifies the current Process Identifier.

The value of the whole of this register is called the Context ID and is used by:

  • The debug logic, for Linked and Unlinked Context ID matching.

  • The trace logic, to identify the current process.

The significance of this register is for debug and trace use only.

Tested on 145769fc387dc5ee63ec82e55e6b131d9c968538 + 1.

For when it breaks again, or you want to add a new feature!

./run --debug
./run-gdb --before '-ex "set remotetimeout 99999" -ex "set debug remote 1"' start_kernel

This error means that the GDB server, e.g. in QEMU, sent more registers than the GDB client expected.

This can happen for the following reasons:

KGDB is kernel dark magic that allows you to GDB the kernel on real hardware without any extra hardware support.

It is useless with QEMU since we already have full system visibility with -gdb. So the goal of this setup is just to prepare you for what to expect when you will be in the treches of real hardware.

KGDB is cheaper than JTAG (free) and easier to setup (all you need is serial), but with less visibility as it depends on the kernel working, so e.g.: dies on panic, does not see boot sequence.

First run the kernel with:

./run --kgdb

this passes the following options on the kernel CLI:

kgdbwait kgdboc=ttyS1,115200

kgdbwait tells the kernel to wait for KGDB to connect.

So the kernel sets things up enough for KGDB to start working, and then boot pauses waiting for connection:

<6>[    4.866050] Serial: 8250/16550 driver, 4 ports, IRQ sharing disabled
<6>[    4.893205] 00:05: ttyS0 at I/O 0x3f8 (irq = 4, base_baud = 115200) is a 16550A
<6>[    4.916271] 00:06: ttyS1 at I/O 0x2f8 (irq = 3, base_baud = 115200) is a 16550A
<6>[    4.987771] KGDB: Registered I/O driver kgdboc
<2>[    4.996053] KGDB: Waiting for connection from remote gdb...

Entering kdb (current=0x(____ptrval____), pid 1) on processor 0 due to Keyboard Entry
[0]kdb>

KGDB expects the connection at ttyS1, our second serial port after ttyS0 which contains the terminal.

The last line is the KDB prompt, and is covered at: Section 4.3, “KDB”. Typing now shows nothing because that prompt is expecting input from ttyS1.

Instead, we connect to the serial port ttyS1 with GDB:

./run-gdb --kgdb --no-continue

Once GDB connects, it is left inside the function kgdb_breakpoint.

So now we can set breakpoints and continue as usual.

For example, in GDB:

continue

Then in QEMU:

./count.sh &
./kgdb.sh

rootfs_overlay/lkmc/kgdb.sh pauses the kernel for KGDB, and gives control back to GDB.

And now in GDB we do the usual:

break __x64_sys_write
continue
continue
continue
continue

And now you can count from KGDB!

If you do: break __x64_sys_write immediately after ./run-gdb --kgdb, it fails with KGDB: BP remove failed: <address>. I think this is because it would break too early on the boot sequence, and KGDB is not yet ready.

See also:

TODO: we would need a second serial for KGDB to work, but it is not currently supported on arm and aarch64 with -M virt that we use: https://unix.stackexchange.com/questions/479085/can-qemu-m-virt-on-arm-aarch64-have-multiple-serial-ttys-like-such-as-pl011-t/479340#479340

One possible workaround for this would be to use KDB ARM.

Just works as you would expect:

insmod timer.ko
./kgdb.sh

In GDB:

break lkmc_timer_callback
continue
continue
continue

and you now control the count.

KDB is a way to use KDB directly in your main console, without GDB.

Advantage over KGDB: you can do everything in one serial. This can actually be important if you only have one serial for both shell and .

Disadvantage: not as much functionality as GDB, especially when you use Python scripts. Notably, TODO confirm you can’t see the the kernel source code and line step as from GDB, since the kernel source is not available on guest (ah, if only debugging information supported full source, or if the kernel had a crazy mechanism to embed it).

Run QEMU as:

./run --kdb

This passes kgdboc=ttyS0 to the Linux CLI, therefore using our main console. Then QEMU:

[0]kdb> go

And now the kdb> prompt is responsive because it is listening to the main console.

After boot finishes, run the usual:

./count.sh &
./kgdb.sh

And you are back in KDB. Now you can count with:

[0]kdb> bp __x64_sys_write
[0]kdb> go
[0]kdb> go
[0]kdb> go
[0]kdb> go

And you will break whenever __x64_sys_write is hit.

You can get see further commands with:

[0]kdb> help

The other KDB commands allow you to step instructions, view memory, registers and some higher level kernel runtime data similar to the superior GDB Python scripts.

You can also use KDB directly from the graphic window with:

./run --graphic --kdb

This setup could be used to debug the kernel on machines without serial, such as modern desktops.

This works because --graphics adds kbd (which stands for KeyBoarD!) to kgdboc.

TODO neither arm and aarch64 are working as of 1cd1e58b023791606498ca509256cc48e95e4f5b + 1.

arm seems to place and hit the breakpoint correctly, but no matter how many go commands I do, the count.sh stdout simply does not show.

aarch64 seems to place the breakpoint correctly, but after the first go the kernel oopses with warning:

WARNING: CPU: 0 PID: 46 at /root/linux-kernel-module-cheat/submodules/linux/kernel/smp.c:416 smp_call_function_many+0xdc/0x358

and stack trace:

smp_call_function_many+0xdc/0x358
kick_all_cpus_sync+0x30/0x38
kgdb_flush_swbreak_addr+0x3c/0x48
dbg_deactivate_sw_breakpoints+0x7c/0xb8
kgdb_cpu_enter+0x284/0x6a8
kgdb_handle_exception+0x138/0x240
kgdb_brk_fn+0x2c/0x40
brk_handler+0x7c/0xc8
do_debug_exception+0xa4/0x1c0
el1_dbg+0x18/0x78
__arm64_sys_write+0x0/0x30
el0_svc_handler+0x74/0x90
el0_svc+0x8/0xc

My theory is that every serious ARM developer has JTAG, and no one ever tests this, and the kernel code is just broken.

Step debug userland processes to understand how they are talking to the kernel.

First build gdbserver into the root filesystem:

./build-buildroot --config 'BR2_PACKAGE_GDB=y'

Then on guest, to debug userland/linux/rand_check.c:

./gdbserver.sh ./c/command_line_arguments.out asdf qwer

And on host:

./run-gdb --gdbserver --userland userland/c/command_line_arguments.c main

or alternatively with the path to the executable itself:

./run --gdbserver --userland "$(./getvar userland_build_dir)/c/command_line_arguments.out"
./gdbserver.sh ls

on host you need:

./run-gdb --gdbserver --userland "$(./getvar buildroot_build_build_dir)"/busybox-*/busybox ls_main

Our setup gives you the rare opportunity to step debug libc and other system libraries.

For example in the guest:

./gdbserver.sh ./posix/count.out

Then on host:

./run-gdb --gdbserver --userland userland/posix/count.c main

and inside GDB:

break sleep
continue

And you are now left inside the sleep function of our default libc implementation uclibc libc/unistd/sleep.c!

You can also step into the sleep call:

step

This is made possible by the GDB command that we use by default:

set sysroot ${common_buildroot_build_dir}/staging

which automatically finds unstripped shared libraries on the host for us.

The portability of the kernel and toolchains is amazing: change an option and most things magically work on completely different hardware.

To use arm instead of x86 for example:

./build-buildroot --arch arm
./run --arch arm

Debug:

./run --arch arm --gdb-wait
# On another terminal.
./run-gdb --arch arm

We also have one letter shorthand names for the architectures and --arch option:

# aarch64
./run -a A
# arm
./run -a a
# x86_64
./run -a x

Known quirks of the supported architectures are documented in this section.

This example illustrates how reading from the x86 control registers with mov crX, rax can only be done from kernel land on ring0.

From kernel land:

insmod ring0.ko

works and output the registers, for example:

cr0 = 0xFFFF880080050033
cr2 = 0xFFFFFFFF006A0008
cr3 = 0xFFFFF0DCDC000

However if we try to do it from userland:

./ring0.out

stdout gives:

Segmentation fault

and dmesg outputs:

traps: ring0.out[55] general protection ip:40054c sp:7fffffffec20 error:0 in ring0.out[400000+1000]

Sources:

In both cases, we attempt to run the exact same code which is shared on the ring0.h header file.

Bibliography:

I’ve tried:

./run-toolchain --arch aarch64 gcc -- -static ~/test/hello_world.c -o "$(./getvar p9_dir)/a.out"
./run --arch aarch64 --eval-after '/mnt/9p/data/a.out'

but it fails with:

a.out: line 1: syntax error: unexpected word (expecting ")")

We used to "support" it until f8c0502bb2680f2dbe7c1f3d7958f60265347005 (it booted) but dropped since one was testing it often.

If you want to revive and maintain it, send a pull request.

It should not be too hard to port this repository to any architecture that Buildroot supports. Pull requests are welcome.

When the Linux kernel finishes booting, it runs an executable as the first and only userland process. This executable is called the init program.

The init process is then responsible for setting up the entire userland (or destroying everything when you want to have fun).

This typically means reading some configuration files (e.g. /etc/initrc) and forking a bunch of userland executables based on those files, including the very interactive shell that we end up on.

systemd provides a "popular" init implementation for desktop distros as of 2017.

BusyBox provides its own minimalistic init implementation which Buildroot, and therefore this repo, uses by default.

The init program can be either an executable shell text file, or a compiled ELF file. It becomes easy to accept this once you see that the exec system call handles both cases equally: https://unix.stackexchange.com/questions/174062/can-the-init-process-be-a-shell-script-in-linux/395375#395375

The init executable is searched for in a list of paths in the root filesystem, including /init, /sbin/init and a few others. For more details see: Section 7.3, “Path to init”

To have more control over the system, you can replace BusyBox’s init with your own.

The most direct way to replace init with our own is to just use the init= command line parameter directly:

./run --kernel-cli 'init=/lkmc/count.sh'

This just counts every second forever and does not give you a shell.

This method is not very flexible however, as it is hard to reliably pass multiple commands and command line arguments to the init with it, as explained at: Section 7.4, “Init environment”.

For this reason, we have created a more robust helper method with the --eval option:

./run --eval 'echo "asdf qwer";insmod hello.ko;./linux/poweroff.out'

It is basically a shortcut for:

./run --kernel-cli 'init=/lkmc/eval_base64.sh - lkmc_eval="insmod hello.ko;./linux/poweroff.out"'

This allows quoting and newlines by base64 encoding on host, and decoding on guest, see: Section 17.3.1, “Kernel command line parameters escaping”.

It also automatically chooses between init= and rcinit= for you, see: Section 7.3, “Path to init”

--eval replaces BusyBox' init completely, which makes things more minimal, but also has has the following consequences:

  • /etc/fstab mounts are not done, notably /proc and /sys, test it out with:

    ./run --eval 'echo asdf;ls /proc;ls /sys;echo qwer'
  • no shell is launched at the end of boot for you to interact with the system. You could explicitly add a sh at the end of your commands however:

    ./run --eval 'echo hello;sh'

The best way to overcome those limitations is to use: Section 7.2, “Run command at the end of BusyBox init”

If the script is large, you can add it to a gitignored file and pass that to --eval as in:

echo '
cd /lkmc
insmod hello.ko
./linux/poweroff.out
' > data/gitignore.sh
./run --eval "$(cat data/gitignore.sh)"

or add it to a file to the root filesystem guest and rebuild:

echo '#!/bin/sh
cd /lkmc
insmod hello.ko
./linux/poweroff.out
' > rootfs_overlay/lkmc/gitignore.sh
chmod +x rootfs_overlay/lkmc/gitignore.sh
./build-buildroot
./run --kernel-cli 'init=/lkmc/gitignore.sh'

Remember that if your init returns, the kernel will panic, there are just two non-panic possibilities:

  • run forever in a loop or long sleep

  • poweroff the machine

Just using BusyBox' poweroff at the end of the init does not work and the kernel panics:

./run --eval poweroff

because BusyBox' poweroff tries to do some fancy stuff like killing init, likely to allow userland to shutdown nicely.

But this fails when we are init itself!

BusyBox' poweroff works more brutally and effectively if you add -f:

./run --eval 'poweroff -f'

but why not just use our minimal ./linux/poweroff.out and be done with it?

./run --eval './linux/poweroff.out'

I dare you to guess what this does:

./run --eval './posix/sleep_forever.out'

This executable is a convenient simple init that does not panic and sleeps instead.

Get a reasonable answer to "how long does boot take in guest time?":

./run --eval-after './linux/time_boot.c'

That executable writes to dmesg directly through /dev/kmsg a message of type:

[    2.188242] /path/to/linux-kernel-module-cheat/userland/linux/time_boot.c

which tells us that boot took 2.188242 seconds based on the dmesg timestamp.

Use the --eval-after option is for you rely on something that BusyBox' init set up for you like /etc/fstab:

./run --eval-after 'echo asdf;ls /proc;ls /sys;echo qwer'

After the commands run, you are left on an interactive shell.

The above command is basically equivalent to:

./run --kernel-cli-after-dash 'lkmc_eval="insmod hello.ko;./linux/poweroff.out;"'

where the lkmc_eval option gets evaled by our default rootfs_overlay/etc/init.d/S98 startup script.

Except that --eval-after is smarter and uses base64 encoding.

Alternatively, you can also add the comamdns to run to a new init.d entry to run at the end o the BusyBox init:

cp rootfs_overlay/etc/init.d/S98 rootfs_overlay/etc/init.d/S99.gitignore
vim rootfs_overlay/etc/init.d/S99.gitignore
./build-buildroot
./run

and they will be run automatically before the login prompt.

Scripts under /etc/init.d are run by /etc/init.d/rcS, which gets called by the line ::sysinit:/etc/init.d/rcS in /etc/inittab.

The init is selected at:

  • initrd or initramfs system: /init, a custom one can be set with the rdinit= kernel command line parameter

  • otherwise: default is /sbin/init, followed by some other paths, a custom one can be set with init=

The final init that actually got selected is shown on Linux v5.9.2 a line of type:

<6>[    0.309984] Run /sbin/init as init process

at the very end of the boot logs.

The kernel parses parameters from the kernel command line up to "-"; if it doesn’t recognize a parameter and it doesn’t contain a '.', the parameter gets passed to init: parameters with '=' go into init’s environment, others are passed as command line arguments to init. Everything after "-" is passed as an argument to init.

And you can try it out with:

./run --kernel-cli 'init=/lkmc/linux/init_env_poweroff.out' --kernel-cli-after-dash 'asdf=qwer zxcv'

From the generated QEMU command, we see that the kernel CLI at LKMC 69f5745d3df11d5c741551009df86ea6c61a09cf now contains:

init=/lkmc/linux/init_env_poweroff.out console=ttyS0 - lkmc_home=/lkmc asdf=qwer zxcv

and the init program outputs:

args:
/lkmc/linux/init_env_poweroff.out
-
zxcv

env:
HOME=/
TERM=linux
lkmc_home=/lkmc
asdf=qwer

As of the Linux kernel v5.7 (possibly earlier, I’ve skipped a few releases), boot also shows the init arguments and environment very clearly, which is a great addition:

<6>[    0.309984] Run /sbin/init as init process
<7>[    0.309991]   with arguments:
<7>[    0.309997]     /sbin/init
<7>[    0.310004]     nokaslr
<7>[    0.310010]     -
<7>[    0.310016]   with environment:
<7>[    0.310022]     HOME=/
<7>[    0.310028]     TERM=linux
<7>[    0.310035]     earlyprintk=pl011,0x1c090000
<7>[    0.310041]     lkmc_home=/lkmc

The annoying dash - gets passed as a parameter to init, which makes it impossible to use this method for most non custom executables.

Arguments with dots that come after - are still treated specially (of the form subsystem.somevalue) and disappear, from args, e.g.:

./run --kernel-cli 'init=/lkmc/linux/init_env_poweroff.out' --kernel-cli-after-dash '/lkmc/linux/poweroff.out'

outputs:

args
/lkmc/linux/init_env_poweroff.out
-
ab

so see how a.b is gone.

The simple workaround is to just create a shell script that does it, e.g. as we’ve done at: rootfs_overlay/lkmc/gem5_exit.sh.

Wait, where do HOME and TERM come from? (greps the kernel). Ah, OK, the kernel sets those by default: https://github.com/torvalds/linux/blob/94710cac0ef4ee177a63b5227664b38c95bbf703/init/main.c#L173

const char *envp_init[MAX_INIT_ENVS+2] = { "HOME=/", "TERM=linux", NULL, };

On top of the Linux kernel, the BusyBox /bin/sh shell will also define other variables.

We can explore the shenanigans that the shell adds on top of the Linux kernel with:

./run --kernel-cli 'init=/bin/sh'

From there we observe that:

env

gives:

SHLVL=1
HOME=/
TERM=linux
PWD=/

therefore adding SHLVL and PWD to the default kernel exported variables.

Furthermore, to increase confusion, if you list all non-exported shell variables https://askubuntu.com/questions/275965/how-to-list-all-variables-names-and-their-current-values with:

set

then it shows more variables, notably:

PATH='/sbin:/usr/sbin:/bin:/usr/bin'

Login shells source some default files, notably:

/etc/profile
$HOME/.profile

We provide /.profile from rootfs_overlay/.profile, and use the default BusyBox /etc/profile.

The shell knows that it is a login shell if the first character of argv[0] is -, see also: https://stackoverflow.com/questions/2050961/is-argv0-name-of-executable-an-accepted-standard-or-just-a-common-conventi/42291142#42291142

When we use just init=/bin/sh, the Linux kernel sets argv[0] to /bin/sh, which does not start with -.

However, if you use ::respawn:-/bin/sh on inttab described at TTY, BusyBox' init sets argv[0][0] to -, and so does getty. This can be observed with:

cat /proc/$$/cmdline

The kernel can boot from an CPIO file, which is a directory serialization format much like tar: https://superuser.com/questions/343915/tar-vs-cpio-what-is-the-difference

The bootloader, which for us is provided by QEMU itself, is then configured to put that CPIO into memory, and tell the kernel that it is there.

This is very similar to the kernel image itself, which already gets put into memory by the QEMU -kernel option.

With this setup, you don’t even need to give a root filesystem to the kernel: it just does everything in memory in a ramfs.

To enable initrd instead of the default ext2 disk image, do:

./build-buildroot --initrd
./run --initrd

By looking at the QEMU run command generated, you can see that we didn’t give the -drive option at all:

cat "$(./getvar run_dir)/run.sh"

Instead, we used the QEMU -initrd option to point to the .cpio filesystem that Buildroot generated for us.

Try removing that -initrd option to watch the kernel panic without rootfs at the end of boot.

When using .cpio, there can be no filesystem persistency across boots, since all file operations happen in memory in a tmpfs:

date >f
poweroff
cat f
# can't open 'f': No such file or directory

which can be good for automated tests, as it ensures that you are using a pristine unmodified system image every time.

Not however that we already disable disk persistency by default on ext2 filesystems even without --initrd: Section 23.3, “Disk persistency”.

One downside of this method is that it has to put the entire filesystem into memory, and could lead to a panic:

end Kernel panic - not syncing: Out of memory and no killable processes...

This can be solved by increasing the memory as explained at Memory size:

./run --initrd --memory 256M

The main ingredients to get initrd working are:

TODO: how does the bootloader inform the kernel where to find initrd? https://unix.stackexchange.com/questions/89923/how-does-linux-load-the-initrd-image

Most modern desktop distributions have an initrd in their root disk to do early setup.

The rationale for this is described at: https://en.wikipedia.org/wiki/Initial_ramdisk

One obvious use case is having an encrypted root filesystem: you keep the initrd in an unencrypted partition, and then setup decryption from there.

I think GRUB then knows read common disk formats, and then loads that initrd to memory with a /boot/grub/grub.cfg directive of type:

initrd /initrd.img-4.4.0-108-generic

initramfs is just like initrd, but you also glue the image directly to the kernel image itself using the kernel’s build system.

Try it out with:

./build-buildroot --initramfs
./build-linux --initramfs
./run --initramfs

Notice how we had to rebuild the Linux kernel this time around as well after Buildroot, since in that build we will be gluing the CPIO to the kernel image.

Now, once again, if we look at the QEMU run command generated, we see all that QEMU needs is the -kernel option, no -drive not even -initrd! Pretty cool:

cat "$(./getvar run_dir)/run.sh"

It is also interesting to observe how this increases the size of the kernel image if you do a:

ls -lh "$(./getvar linux_image)"

before and after using initramfs, since the .cpio is now glued to the kernel image.

Don’t forget that to stop using initramfs, you must rebuild the kernel without --initramfs to get rid of the attached CPIO image:

./build-linux
./run

Alternatively, consider using [linux-kernel-build-variants] if you need to switch between initramfs and non initramfs often:

./build-buildroot --initramfs
./build-linux --initramfs --linux-build-id initramfs
./run --initramfs --linux-build-id

Setting up initramfs is very easy: our scripts just set CONFIG_INITRAMFS_SOURCE to point to the CPIO path.

This is how /proc/mounts shows the root filesystem:

  • hard disk: /dev/root on / type ext2 (rw,relatime,block_validity,barrier,user_xattr). That file does not exist however.

  • initrd: rootfs on / type rootfs (rw)

  • initramfs: rootfs on / type rootfs (rw)

TODO: understand /dev/root better:

This would require gem5 to load the CPIO into memory, just like QEMU. Grepping initrd shows some ARM hits under:

src/arch/arm/linux/atag.hh

but they are commented out.

This could in theory be easier to make work than initrd since the emulator does not have to do anything special.

However, it didn’t: boot fails at the end because it does not see the initramfs, but rather tries to open our dummy root filesystem, which unsurprisingly does not have a format in a way that the kernel understands:

VFS: Cannot open root device "sda" or unknown-block(8,0): error -5

We think that this might be because gem5 boots directly vmlinux, and not from the final compressed images that contain the attached rootfs such as bzImage, which is what QEMU does, see also: Section 17.20.1, “vmlinux vs bzImage vs zImage vs Image”.

To do this failed test, we automatically pass a dummy disk image as of gem5 7fa4c946386e7207ad5859e8ade0bbfc14000d91 since the scripts don’t handle a missing --disk-image well, much like is currently done for [baremetal].

Interestingly, using initramfs significantly slows down the gem5 boot, even though it did not work. For example, we’ve observed a 4x slowdown of as 17062a2e8b6e7888a14c3506e9415989362c58bf for aarch64. This must be because expanding the large attached CPIO must be expensive. We can clearly see from the kernel logs that the kernel just hangs at a point after the message PCI: CLS 0 bytes, default 64 for a long time before proceeding further.

The device tree is a Linux kernel defined data structure that serves to inform the kernel how the hardware is setup.

Device trees serve to reduce the need for hardware vendors to patch the kernel: they just provide a device tree file instead, which is much simpler.

x86 does not use it device trees, but many other archs to, notably ARM.

This is notably because ARM boards:

  • typically don’t have discoverable hardware extensions like PCI, but rather just put everything on an SoC with magic register addresses

  • are made by a wide variety of vendors due to ARM’s licensing business model, which increases variability

The Linux kernel itself has several device trees under ./arch/<arch>/boot/dts, see also: https://stackoverflow.com/questions/21670967/how-to-compile-dts-linux-device-tree-source-files-to-dtb/42839737#42839737

Files that contain device trees have the .dtb extension when compiled, and .dts when in text form.

You can convert between those formats with:

"$(./getvar buildroot_host_dir)"/bin/dtc -I dtb -O dts -o a.dts a.dtb
"$(./getvar buildroot_host_dir)"/bin/dtc -I dts -O dtb -o a.dtb a.dts

Buildroot builds the tool due to BR2_PACKAGE_HOST_DTC=y.

On Ubuntu 18.04, the package is named:

sudo apt-get install device-tree-compiler

Device tree files are provided to the emulator just like the root filesystem and the Linux kernel image.

In real hardware, those components are also often provided separately. For example, on the Raspberry Pi 2, the SD card must contain two partitions:

  • the first contains all magic files, including the Linux kernel and the device tree

  • the second contains the root filesystem

Good format descriptions:

Minimal example

/dts-v1/;

/ {
    a;
};

Check correctness with:

dtc a.dts

Separate nodes are simply merged by node path, e.g.:

/dts-v1/;

/ {
    a;
};

/ {
    b;
};

then dtc a.dts gives:

/dts-v1/;

/ {
        a;
        b;
};

This is specially interesting because QEMU and gem5 are capable of generating DTBs that match the selected machine depending on dynamic command line parameters for some types of machines.

So observing the device tree from the guest allows to easily see what the emulator has generated.

Compile the dtc tool into the root filesystem:

./build-buildroot \
  --arch aarch64 \
  --config 'BR2_PACKAGE_DTC=y' \
  --config 'BR2_PACKAGE_DTC_PROGRAMS=y' \
;

-M virt for example, which we use by default for aarch64, boots just fine without the -dtb option:

./run --arch aarch64

Then, from inside the guest:

dtc -I fs -O dts /sys/firmware/devicetree/base

contains:

        cpus {
                #address-cells = <0x1>;
                #size-cells = <0x0>;

                cpu@0 {
                        compatible = "arm,cortex-a57";
                        device_type = "cpu";
                        reg = <0x0>;
                };
        };

Since emulators know everything about the hardware, they can automatically generate device trees for us, which is very convenient.

This is the case for both QEMU and gem5.

For example, if we increase the number of cores to 2:

./run --arch aarch64 --cpus 2

QEMU automatically adds a second CPU to the DTB!

                cpu@0 {
                cpu@1 {

The action seems to be happening at: hw/arm/virt.c.

You can dump the DTB QEMU generated with:

./run --arch aarch64 -- -machine dumpdtb=dtb.dtb

gem5 fs_bigLITTLE 2a9573f5942b5416fb0570cf5cb6cdecba733392 can also generate its own DTB.

gem5 can generate DTBs on ARM with --generate-dtb. The generated DTB is placed in the m5out directory named as system.dtb.

KVM is Linux kernel interface that greatly speeds up execution of virtual machines.

You can make QEMU or gem5 by passing enabling KVM with:

./run --kvm

KVM works by running userland instructions natively directly on the real hardware instead of running a software simulation of those instructions.

Therefore, KVM only works if you the host architecture is the same as the guest architecture. This means that this will likely only work for x86 guests since almost all development machines are x86 nowadays. Unless you are running an ARM desktop for some weird reason :-)

We don’t enable KVM by default because:

  • it limits visibility, since more things are running natively:

  • QEMU kernel boots are already fast enough for most purposes without it

One important use case for KVM is to fast forward gem5 execution, often to skip boot, take a gem5 checkpoint, and then move on to a more detailed and slow simulation

TODO: we haven’t gotten it to work yet, but it should be doable, and this is an outline of how to do it. Just don’t expect this to tested very often for now.

We can test KVM on arm by running this repository inside an Ubuntu arm QEMU VM.

This produces no speedup of course, since the VM is already slow since it cannot use KVM on the x86 host.

Then, from inside that image:

sudo apt-get install git
git clone https://github.com/************/linux-kernel-module-cheat
cd linux-kernel-module-cheat
./setup -y

and then proceed exactly as in Prebuilt setup.

We don’t want to build the full Buildroot image inside the VM as that would be way too slow, thus the recommendation for the prebuilt setup.

TODO: do the right thing and cross compile QEMU and gem5. gem5’s Python parts might be a pain. QEMU should be easy: https://stackoverflow.com/questions/26514252/cross-compile-qemu-for-arm

While gem5 does have KVM, as of 2019 its support has not been very good, because debugging it is harder and people haven’t focused intensively on it.

X86 was broken with pending patches: https://www.mail-archive.com/[email protected]/msg15046.html It failed immediately on:

panic: KVM: Failed to enter virtualized mode (hw reason: 0x80000021)

also mentioned at:

Bibliography:

Both QEMU and gem5 have an user mode simulation mode in addition to full system simulation that we consider elsewhere in this project.

In QEMU, it is called just "user mode", and in gem5 it is called syscall emulation mode.

In both, the basic idea is the same.

User mode simulation takes regular userland executables of any arch as input and executes them directly, without booting a kernel.

Instead of simulating the full system, it translates normal instructions like in full system mode, but magically forwards system calls to the host OS.

Advantages over full system simulation:

  • the simulation may run faster since you don’t have to simulate the Linux kernel and several device models

  • you don’t need to build your own kernel or root filesystem, which saves time. You still need a toolchain however, but the pre-packaged ones may work fine.

Disadvantages:

  • lower guest to host portability:

    • TODO confirm: host OS == guest OS?

    • TODO confirm: the host Linux kernel should be newer than the kernel the executable was built for.

      It may still work even if that is not the case, but could fail is a missing system call is reached.

      The target Linux kernel of the executable is a GCC toolchain build-time configuration.

    • emulator implementers have to keep up with libc changes, some of which break even a C hello world due setup code executed before main.

  • cannot be used to test the Linux kernel or any devices, and results are less representative of a real system since we are faking more

Let’s run userland/c/command_line_arguments.c built with the Buildroot toolchain on QEMU user mode:

./build user-mode-qemu
./run \
  --userland userland/c/command_line_arguments.c \
  --cli-args='asdf "qw er"' \
;

Output:

/path/to/linux-kernel-module-cheat/out/userland/default/x86_64/c/command_line_arguments.out
asdf
qw er

./run --userland path resolution is analogous to that of ./run --baremetal.

./build user-mode-qemu first builds Buildroot, and then runs ./build-userland, which is further documented at: Section 2.8, “Userland setup”. It also builds QEMU. If you ahve already done a QEMU Buildroot setup previously, this will be very fast.

If you modify the userland programs, rebuild simply with:

./build-userland

To rebuild just QEMU userland if you hack it, use:

./build-qemu --mode userland

The:

--mode userland

is needed because QEMU has two separate executables:

  • qemu-x86_64 for userland

  • qemu-system-x86_64 for full system

It’s nice when the obvious just works, right?

./run \
  --arch aarch64 \
  --gdb-wait \
  --userland userland/c/command_line_arguments.c \
  --cli-args 'asdf "qw er"' \
;

and on another shell:

./run-gdb \
  --arch aarch64 \
  --userland userland/c/command_line_arguments.c \
  main \
;

Or alternatively, if you are using tmux, do everything in one go with:

./run \
  --arch aarch64 \
  --gdb \
  --userland userland/c/command_line_arguments.c \
  --cli-args 'asdf "qw er"' \
;

To stop at the very first instruction of a freestanding program, just use --no-continue. A good example of this is shown at: [freestanding-programs].

Automatically run all userland tests that can be run in user mode simulation, and check that they exit with status 0:

./build --all-archs test-executables-userland
./test-executables --all-archs --all-emulators

Or just for QEMU:

./build --all-archs test-executables-userland-qemu
./test-executables --all-archs --emulator qemu

This script skips a manually configured list of tests, notably:

  • tests that depend on a full running kernel and cannot be run in user mode simulation, e.g. those that rely on kernel modules

  • tests that require user interaction

  • tests that take perceptible amounts of time

  • known bugs we didn’t have time to fix ;-)

Tests under userland/libs/ are only run if --package or --package-all are given as described at [userland-libs-directory].

The gem5 tests require building statically with build id static, see also: Section 11.7, “gem5 syscall emulation mode”. TODO automate this better.

See: [test-this-repo] for more useful testing tips.

If you followed QEMU Buildroot setup, you can now run the executables created by Buildroot directly as:

./run \
  --userland "$(./getvar buildroot_target_dir)/bin/echo" \
  --cli-args='asdf' \
;

To easily explore the userland executable environment interactively, you can do:

./run \
  --arch aarch64 \
  --userland "$(./getvar --arch aarch64 buildroot_target_dir)/bin/sh" \
  --terminal \
;

or:

./run \
  --arch aarch64 \
  --userland "$(./getvar --arch aarch64 buildroot_target_dir)/bin/sh" \
  --cli-args='-c "uname -a && pwd"' \
;

Here is an interesting examples of this: Section 17.19.1, “Linux Test Project”

At 125d14805f769104f93c510bedaa685a52ec025d we moved Buildroot from uClibc to glibc, and caused some user mode pain, which we document here.

glibc has a check for kernel version, likely obtained from the uname syscall, and if the kernel is not new enough, it quits.

Both gem5 and QEMU however allow setting the reported uname version from the command line, which we do to always match our toolchain.

QEMU by default copies the host uname value, but we always override it in our scripts.

Determining the right number to use for the kernel version is of course highly non-trivial and would require an extensive userland test suite, which most emulators don’t have.

./run --arch aarch64 --kernel-version 4.18 --userland userland/posix/uname.c

Bibliography:

The ID is just hardcoded on the source:

For some reason QEMU / glibc x86_64 picks up the host libc, which breaks things.

Other archs work as they different host libc is skipped. User mode static executables also work.

We have worked around this with with https://bugs.launchpad.net/qemu/+bug/1701798/comments/12 from the thread: https://bugs.launchpad.net/qemu/+bug/1701798 by creating the file: rootfs_overlay/etc/ld.so.cache which is a symlink to a file that cannot exist: /dev/null/nonexistent.

Reproduction:

rm -f "$(./getvar buildroot_target_dir)/etc/ld.so.cache"
./run --userland userland/c/hello.c
./run --userland userland/c/hello.c --qemu-which host

Outcome:

*** stack smashing detected ***: <unknown> terminated
qemu: uncaught target signal 6 (Aborted) - core dumped

To get things working again, restore ld.so.cache with:

./build-buildroot

I’ve also tested on an Ubuntu 16.04 guest and the failure is different one:

qemu: uncaught target signal 4 (Illegal instruction) - core dumped

A non-QEMU-specific example of stack smashing is shown at: https://stackoverflow.com/questions/1345670/stack-smashing-detected/51897264#51897264

Tested at: 2e32389ebf1bedd89c682aa7b8fe42c3c0cf96e5 + 1.

Example:

./build-userland \
  --arch aarch64 \
  --static \
;
./run \
  --arch aarch64 \
  --static \
  --userland userland/c/command_line_arguments.c \
  --cli-args 'asdf "qw er"' \
;

Running dynamically linked executables in QEMU requires pointing it to the root filesystem with the -L option so that it can find the dynamic linker and shared libraries, see also:

We pass -L by default, so everything just works.

However, in case something goes wrong, you can also try statically linked executables, since this mechanism tends to be a bit more stable, for example:

Running statically linked executables sometimes makes things break:

One limitation of static executables is that Buildroot mostly only builds dynamic versions of libraries (the libc is an exception).

So programs that rely on those libraries might not compile as GCC can’t find the .a version of the library.

For example, if we try to build [blas] statically:

./build-userland --package openblas --static -- userland/libs/openblas/hello.c

it fails with:

ld: cannot find -lopenblas

g++ and pthreads also causes issues:

As a consequence, the following just hangs as of LKMC ca0403849e03844a328029d70c08556155dc1cd0 + 1 the example userland/cpp/atomic/std_atomic.cpp:

./run --userland userland/cpp/atomic/std_atomic.cpp --static

And before that, it used to fail with other randomly different errors, e.g.:

qemu-x86_64: /path/to/linux-kernel-module-cheat/submodules/qemu/accel/tcg/cpu-exec.c:700: cpu_exec: Assertion `!have_mmap_lock()' failed.
qemu-x86_64: /path/to/linux-kernel-module-cheat/submodules/qemu/accel/tcg/cpu-exec.c:700: cpu_exec: Assertion `!have_mmap_lock()' failed.

And a native Ubuntu 18.04 AMD64 run with static compilation segfaults.

As of LKMC f5d4998ff51a548ed3f5153aacb0411d22022058 the aarch64 error:

./run --arch aarch64 --userland userland/cpp/atomic/fail.cpp --static

is:

terminate called after throwing an instance of 'std::system_error'
  what():  Unknown error 16781344
qemu: uncaught target signal 6 (Aborted) - core dumped

The workaround:

-pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive

fixes some of the problems, but not all TODO which were missing?, so we are just skipping those tests for now.

The following work on both QEMU and gem5 as of LKMC 99d6bc6bc19d4c7f62b172643be95d9c43c26145 + 1. Interactive input:

./run --userland userland/c/getchar.c

A line of type should show:

enter a character:

and after pressing say a and Enter, we get:

you entered: a

Note however that due to QEMU user mode does not show stdout immediately we don’t really see the initial enter a character line.

Non-interactive input from a file by forwarding emulators stdin implicitly through our Python scripts:

printf a > f.tmp
./run --userland userland/c/getchar.c < f.tmp

Input from a file by explicitly requesting our scripts to use it via the Python API:

printf a > f.tmp
./run --emulator gem5 --userland userland/c/getchar.c --stdin-file f.tmp

This is especially useful when running tests that require stdin input.

Less robust than QEMU’s, but still usable:

There are much more unimplemented syscalls in gem5 than in QEMU. Many of those are trivial to implement however.

So let’s just play with some static ones:

./build-userland --arch aarch64
./run \
  --arch aarch64 \
  --emulator gem5 \
  --userland userland/c/command_line_arguments.c \
  --cli-args 'asdf "qw er"' \
;

TODO: how to escape spaces on the command line arguments?

GDB step debug also works normally on gem5:

./run \
  --arch aarch64 \
  --emulator gem5 \
  --gdb-wait \
  --userland userland/c/command_line_arguments.c \
  --cli-args 'asdf "qw er"' \
;
./run-gdb \
  --arch aarch64 \
  --emulator gem5 \
  --userland userland/c/command_line_arguments.c \
  main \
;

As of gem5 7fa4c946386e7207ad5859e8ade0bbfc14000d91, the crappy se.py script does not forward the exit status of syscall emulation mode, you can test it with:

./run --dry-run --emulator gem5 --userland userland/c/false.c

Then manually run the generated gem5 CLI, and do:

echo $?

and the output is always 0.

Instead, it just outputs a message to stdout just like for m5 fail:

Simulated exit code not 0! Exit code is 1

which we parse in run and then exit with the correct result ourselves…​

Since gem5 has to implement syscalls itself in syscall emulation mode, it can of course clearly see which syscalls are being made, and we can log them for debug purposes with gem5 tracing, e.g.:

./run \
  --emulator gem5 \
  --userland userland/arch/x86_64/freestanding/linux/hello.S \
  --trace-stdout \
  --trace ExecAll,SyscallBase,SyscallVerbose \
;

the trace as of f2eeceb1cde13a5ff740727526bf916b356cee38 + 1 contains:

      0: system.cpu A0 T0 : @asm_main_after_prologue    : mov   rdi, 0x1
      0: system.cpu A0 T0 : @asm_main_after_prologue.0  :   MOV_R_I : limm   rax, 0x1 : IntAlu :  D=0x0000000000000001  flags=(IsInteger|IsMicroop|IsLastMicroop|IsFirstMicroop)
   1000: system.cpu A0 T0 : @asm_main_after_prologue+7    : mov rdi, 0x1
   1000: system.cpu A0 T0 : @asm_main_after_prologue+7.0  :   MOV_R_I : limm   rdi, 0x1 : IntAlu :  D=0x0000000000000001  flags=(IsInteger|IsMicroop|IsLastMicroop|IsFirstMicroop)
   2000: system.cpu A0 T0 : @asm_main_after_prologue+14    : lea        rsi, DS:[rip + 0x19]
   2000: system.cpu A0 T0 : @asm_main_after_prologue+14.0  :   LEA_R_P : rdip   t7, %ctrl153,  : IntAlu :  D=0x000000000040008d  flags=(IsInteger|IsMicroop|IsDelayedCommit|IsFirstMicroop)
   2500: system.cpu A0 T0 : @asm_main_after_prologue+14.1  :   LEA_R_P : lea   rsi, DS:[t7 + 0x19] : IntAlu :  D=0x00000000004000a6  flags=(IsInteger|IsMicroop|IsLastMicroop)
   3500: system.cpu A0 T0 : @asm_main_after_prologue+21    : mov        rdi, 0x6
   3500: system.cpu A0 T0 : @asm_main_after_prologue+21.0  :   MOV_R_I : limm   rdx, 0x6 : IntAlu :  D=0x0000000000000006  flags=(IsInteger|IsMicroop|IsLastMicroop|IsFirstMicroop)
   4000: system.cpu: T0 : syscall write called w/arguments 1, 4194470, 6, 0, 0, 0
hello
   4000: system.cpu: T0 : syscall write returns 6
   4000: system.cpu A0 T0 : @asm_main_after_prologue+28    :   syscall    eax           : IntAlu :   flags=(IsInteger|IsSerializeAfter|IsNonSpeculative|IsSyscall)
   5000: system.cpu A0 T0 : @asm_main_after_prologue+30    : mov        rdi, 0x3c
   5000: system.cpu A0 T0 : @asm_main_after_prologue+30.0  :   MOV_R_I : limm   rax, 0x3c : IntAlu :  D=0x000000000000003c  flags=(IsInteger|IsMicroop|IsLastMicroop|IsFirstMicroop)
   6000: system.cpu A0 T0 : @asm_main_after_prologue+37    : mov        rdi, 0
   6000: system.cpu A0 T0 : @asm_main_after_prologue+37.0  :   MOV_R_I : limm   rdi, 0  : IntAlu :  D=0x0000000000000000  flags=(IsInteger|IsMicroop|IsLastMicroop|IsFirstMicroop)
   6500: system.cpu: T0 : syscall exit called w/arguments 0, 4194470, 6, 0, 0, 0
   6500: system.cpu: T0 : syscall exit returns 0
   6500: system.cpu A0 T0 : @asm_main_after_prologue+44    :   syscall    eax           : IntAlu :   flags=(IsInteger|IsSerializeAfter|IsNonSpeculative|IsSyscall)

so we see that two syscall lines were added for each syscall, showing the syscall inputs and exit status, just like a mini strace!

gem5 user mode multithreading has been particularly flaky compared to QEMU’s, but work is being put into improving it.

In gem5 syscall simulation, the fork syscall checks if there is a free CPU, and if there is a free one, the new threads runs on that CPU.

Otherwise, the fork call, and therefore higher level interfaces to fork such as pthread_create also fail and return a failure return status in the guest.

For example, if we use just one CPU for userland/posix/pthread_self.c which spawns one thread besides main:

./run --cpus 1 --emulator gem5 --userland userland/posix/pthread_self.c --cli-args 1

fails with this error message coming from the guest stderr:

pthread_create: Resource temporarily unavailable

It works however if we add on extra CPU:

./run --cpus 2 --emulator gem5 --userland userland/posix/pthread_self.c --cli-args 1

Once threads exit, their CPU is freed and becomes available for new fork calls: For example, the following run spawns a thread, joins it, and then spawns again, and 2 CPUs are enough:

./run --cpus 2 --emulator gem5 --userland userland/posix/pthread_self.c --cli-args '1 2'

because at each point in time, only up to two threads are running.

gem5 syscall emulation does show the expected number of cores when queried, e.g.:

./run --cpus 1 --userland userland/cpp/thread_hardware_concurrency.cpp --emulator gem5
./run --cpus 2 --userland userland/cpp/thread_hardware_concurrency.cpp --emulator gem5

outputs 1 and 2 respectively.

This can also be clearly by running sched_getcpu:

./run \
  --arch aarch64 \
  --cli-args  4 \
  --cpus 8 \
  --emulator gem5 \
  --userland userland/linux/sched_getcpu.c \
;

which necessarily produces an output containing the CPU numbers from 1 to 4 and no higher:

1
3
4
2

TODO why does the 2 come at the end here? Would be good to do a detailed assembly run analysis.

gem5 syscall emulation has the nice feature of allowing you to run multiple executables "at once".

Each executable starts running on the next free core much as if it had been forked right at the start of simulation: gem5 syscall emulation multithreading.

This can be useful to quickly create deterministic multi-CPU workload.

se.py --cmd takes a semicolon separated list, so we could do which LKMC exposes this by taking --userland multiple times as in:

./run \
  --arch aarch64 \
  --cpus 2 \
  --emulator gem5 \
  --userland userland/posix/getpid.c \
  --userland userland/posix/getpid.c \
;

We need at least one CPU per executable, just like when forking new processes.

The outcome of this is that we see two different pid messages printed to stdout:

pid=101
pid=100

since from [gem5-process] we can see that se.py sets up one different PID per executable starting at 100:

    workloads = options.cmd.split(';')
    idx = 0
    for wrkld in workloads:
        process = Process(pid = 100 + idx)

We can also see that these processes are running concurrently with gem5 tracing by hacking:

  --debug-flags ExecAll \
  --debug-file cout \

which starts with:

      0: system.cpu1: A0 T0 : @__end__+274873647040    :   add   x0, sp, #0         : IntAlu :  D=0x0000007ffffefde0  flags=(IsInteger)
      0: system.cpu0: A0 T0 : @__end__+274873647040    :   add   x0, sp, #0         : IntAlu :  D=0x0000007ffffefde0  flags=(IsInteger)
    500: system.cpu0: A0 T0 : @__end__+274873647044    :   bl   <__end__+274873649648> : IntAlu :  D=0x0000004000001008  flags=(IsInteger|IsControl|IsDirectControl|IsUncondControl|IsCall)
    500: system.cpu1: A0 T0 : @__end__+274873647044    :   bl   <__end__+274873649648> : IntAlu :  D=0x0000004000001008  flags=(IsInteger|IsControl|IsDirectControl|IsUncondControl|IsCall)

and therefore shows one instruction running on each CPU for each process at the same time.

gem5 b1623cb2087873f64197e503ab8894b5e4d4c7b4 syscall emulation has an --smt option presumably for [hardware-threads] but it has been neglected forever it seems: ************#104

If we start from the manually hacked working command from gem5 syscall emulation multiple executables and try to add:

--cpu 1 --cpu-type Derivo3CPU --caches

We choose DerivO3CPU because of the se.py assert:

example/se.py:115:        assert(options.cpu_type == "DerivO3CPU")

But then that fails with:

gem5.opt: /path/to/linux-kernel-module-cheat/out/gem5/master3/build/ARM/cpu/o3/cpu.cc:205: FullO3CPU<Impl>::FullO3CPU(DerivO3CPUParams*) [with Impl = O3CPUImpl]: Assertion `params->numPhysVecPredRegs >= numThreads * TheISA::NumVecPredRegs' failed.
Program aborted at tick 0

At 8d8307ac0710164701f6e14c99a69ee172ccbb70 + 1, I noticed that if you run userland/posix/count.c:

./run --userland userland/posix/count_to.c --cli-args 3

it first waits for 3 seconds, then the program exits, and then it dumps all the stdout at once, instead of counting once every second as expected.

The same can be reproduced by copying the raw QEMU command and piping it through tee, so I don’t think it is a bug in our setup:

/path/to/linux-kernel-module-cheat/out/qemu/default/x86_64-linux-user/qemu-x86_64 \
  -L /path/to/linux-kernel-module-cheat/out/buildroot/build/default/x86_64/target \
  /path/to/linux-kernel-module-cheat/out/userland/default/x86_64/posix/count.out \
  3 \
| tee

TODO: investigate further and then possibly post on QEMU mailing list.

Similarly to QEMU user mode does not show stdout immediately, QEMU error messages do not show at all through pipes.

In particular, it does not say anything if you pass it a non-existing executable:

qemu-x86_64 asdf | cat

So we just check ourselves manually

./run --eval-after 'insmod hello.ko'

If you are feeling raw, you can insert and remove modules with our own minimal module inserter and remover!

# init_module
./linux/myinsmod.out hello.ko
# finit_module
./linux/myinsmod.out hello.ko "" 1
./linux/myrmmod.out hello

which teaches you how it is done from C code.

Source:

The Linux kernel offers two system calls for module insertion:

  • init_module

  • finit_module

and:

man init_module

documents that:

The finit_module() system call is like init_module(), but reads the module to be loaded from the file descriptor fd. It is useful when the authenticity of a kernel module can be determined from its location in the filesystem; in cases where that is possible, the overhead of using cryptographically signed modules to determine the authenticity of a module can be avoided. The param_values argument is as for init_module().

finit is newer and was added only in v3.8. More rationale: https://lwn.net/Articles/519010/

modprobe searches for modules installed under:

ls /lib/modules/<kernel_version>

and specified in the modules.order file.

This is the default install path for CONFIG_SOME_MOD=m modules built with make modules_install in the Linux kernel tree, with root path given by INSTALL_MOD_PATH, and therefore canonical in that sense.

Currently, there are only two kinds of kernel modules that you can try out with modprobe:

We are not installing out custom ./build-modules modules there, because:

The more "reference" kernel.org implementation of lsmod, insmod, rmmod, etc.: https://git.kernel.org/pub/scm/utils/kernel/kmod/kmod.git

Default implementation on desktop distros such as Ubuntu 16.04, where e.g.:

ls -l /bin/lsmod

gives:

lrwxrwxrwx 1 root root 4 Jul 25 15:35 /bin/lsmod -> kmod

and:

dpkg -l | grep -Ei

contains:

ii  kmod                                        22-1ubuntu5                                         amd64        tools for managing Linux kernel modules

BusyBox also implements its own version of those executables, see e.g. modprobe. Here we will only describe features that differ from kmod to the BusyBox implementation.

Name of a predecessor set of tools.

kmod’s modprobe can also load modules under different names to avoid conflicts, e.g.:

sudo modprobe vmhgfs -o vm_hgfs

OverlayFS is a filesystem merged in the Linux kernel in 3.18.

As the name suggests, OverlayFS allows you to merge multiple directories into one. The following minimal runnable examples should give you an intuition on how it works:

We are very interested in this filesystem because we are looking for a way to make host cross compiled executables appear on the guest root / without reboot.

This would have several advantages:

  • makes it faster to test modified guest programs

    • not rebooting is fundamental for gem5, where the reboot is very costly.

    • no need to regenerate the root filesystem at all and reboot

    • overcomes the check_bin_arch problem as shown at: [rpath]

  • we could keep the base root filesystem very small, which implies:

    • less host disk usage, no need to copy the entire ./getvar out_rootfs_overlay_dir to the image again

    • no need to worry about [br2-target-rootfs-ext2-size]

We can already make host files appear on the guest with 9P, but they appear on a subdirectory instead of the root.

If they would appear on the root instead, that would be even more awesome, because you would just use the exact same paths relative to the root transparently.

For example, we wouldn’t have to mess around with variables such as PATH and LD_LIBRARY_PATH.

The idea is to:

We already have a prototype of this running from fstab on guest at /mnt/overlay, but it has the following shortcomings:

  • changes to underlying filesystems are not visible on the overlay unless you remount with mount -r remount /mnt/overlay, as mentioned on the kernel docs:

    Changes to the underlying filesystems while part of a mounted overlay
    filesystem are not allowed.  If the underlying filesystem is changed,
    the behavior of the overlay is undefined, though it will not result in
    a crash or deadlock.

    This makes everything very inconvenient if you are inside chroot action. You would have to leave chroot, remount, then come back.

  • the overlay does not contain sub-filesystems, e.g. /proc. We would have to re-mount them. But should be doable with some automation.

Even more awesome than chroot would be to pivot_root, but I couldn’t get that working either:

A simpler and possibly less overhead alternative to 9P would be to generate a secondary disk image with the benchmark you want to rebuild.

Then you can umount and re-mount on guest without reboot.

To build the secondary disk image run build-disk2:

./build-disk2

This will put the entire [out-rootfs-overlay-dir] into a squashfs filesystem.

Then, if that filesystem is present, ./run will automatically pass it as the second disk on the command line.

For example, from inside QEMU, you can mount that disk with:

mkdir /mnt/vdb
mount /dev/vdb /mnt/vdb
/mnt/vdb/lkmc/c/hello.out

To update the secondary disk while a simulation is running to avoid rebooting, first unmount in the guest:

umount /mnt/vdb

and then on the host:

# Edit the file.
vim userland/c/hello.c
./build-userland
./build-disk2

and now you can re-run the updated version of the executable on the guest after remounting it.

Both QEMU and gem5 are capable of outputting graphics to the screen, and taking mouse and keyboard input.

Text mode is the default mode for QEMU.

The opposite of text mode is QEMU graphic mode

In text mode, we just show the serial console directly on the current terminal, without opening a QEMU GUI window.

You cannot see any graphics from text mode, but text operations in this mode, including:

making this a good default, unless you really need to use with graphics.

Text mode works by sending the terminal character by character to a serial device.

This is different from a display screen, where each character is a bunch of pixels, and it would be much harder to convert that into actual terminal text.

For more details, see:

Note that you can still see an image even in text mode with the VNC:

./run --vnc

and on another terminal:

./vnc

but there is not terminal on the VNC window, just the CONFIG_LOGO penguin.

However, our QEMU setup captures Ctrl + C and other common signals and sends them to the guest, which makes it hard to quit QEMU for the first time since there is no GUI either.

The simplest way to quit QEMU, is to do:

Ctrl-A X

Alternative methods include:

Enable graphic mode with:

./run --graphic

Outcome: you see a penguin due to CONFIG_LOGO.

For a more exciting GUI experience, see: Section 14.4, “X11 Buildroot”

Text mode is the default due to the following considerable advantages:

  • copy and paste commands and stdout output to / from host

  • get full panic traces when you start making the kernel crash :-) See also: https://unix.stackexchange.com/questions/208260/how-to-scroll-up-after-a-kernel-panic

  • have a large scroll buffer, and be able to search it, e.g. by using tmux on host

  • one less window floating around to think about in addition to your shell :-)

  • graphics mode has only been properly tested on x86_64.

Text mode has the following limitations over graphics mode:

  • you can’t see graphics such as those produced by X11 Buildroot

  • very early kernel messages such as early console in extract_kernel only show on the GUI, since at such early stages, not even the serial has been setup.

x86_64 has a VGA device enabled by default, as can be seen as:

./qemu-monitor info qtree

and the Linux kernel picks it up through the fbdev graphics system as can be seen from:

cat /dev/urandom > /dev/fb0

TODO: on arm, we see the penguin and some boot messages, but don’t get a shell at then end:

./run --arch aarch64 --graphic

I think it does not work because the graphic window is DRM only, i.e.:

cat /dev/urandom > /dev/fb0

fails with:

cat: write error: No space left on device

and has no effect, and the Linux kernel does not appear to have a built-in DRM console as it does for fbdev with fbcon.

There is however one out-of-tree implementation: kmscon.

arm and aarch64 rely on the QEMU CLI option:

-device virtio-gpu-pci

and the kernel config options:

CONFIG_DRM=y
CONFIG_DRM_VIRTIO_GPU=y

Unlike x86, arm and aarch64 don’t have a display device attached by default, thus the need for virtio-gpu-pci.

See also https://wiki.qemu.org/Documentation/Platforms/ARM (recently edited and corrected by yours truly…​ :-)).

-device VGA
# We use virtio-gpu because the legacy VGA framebuffer is
# very troublesome on aarch64, and virtio-gpu is the only
# video device that doesn't implement it.

so maybe it is not possible?

gem5 does not have a "text mode", since it cannot redirect the Linux terminal to same host terminal where the executable is running: you are always forced to connect to the terminal with gem-shell.

TODO could not get it working on x86_64, only ARM.

More concretely, first build the kernel with the gem5 arm Linux kernel patches, and then run:

./build-linux \
  --arch arm \
  --custom-config-file-gem5 \
  --linux-build-id gem5-v4.15 \
;
./run --arch arm --emulator gem5 --linux-build-id gem5-v4.15

and then on another shell:

vinagre localhost:5900

The CONFIG_LOGO penguin only appears after several seconds, together with kernel messages of type:

[    0.152755] [drm] found ARM HDLCD version r0p0
[    0.152790] hdlcd 2b000000.hdlcd: bound virt-encoder (ops 0x80935f94)
[    0.152795] [drm] Supports vblank timestamp caching Rev 2 (21.10.2013).
[    0.152799] [drm] No driver support for vblank timestamp query.
[    0.215179] Console: switching to colour frame buffer device 240x67
[    0.230389] hdlcd 2b000000.hdlcd: fb0:  frame buffer device
[    0.230509] [drm] Initialized hdlcd 1.0.0 20151021 for 2b000000.hdlcd on minor 0

The port 5900 is incremented by one if you already have something running on that port, gem5 stdout tells us the right port on stdout as:

system.vncserver: Listening for connections on port 5900

and when we connect it shows a message:

info: VNC client attached

Alternatively, you can also dump each new frame to an image file with --frame-capture:

./run \
  --arch arm \
  --emulator gem5 \
  --linux-build-id gem5-v4.15 \
  -- --frame-capture \
;

This creates on compressed PNG whenever the screen image changes inside the m5out directory with filename of type:

frames_system.vncserver/fb.<frame-index>.<timestamp>.png.gz

It is fun to see how we get one new frame whenever the white underscore cursor appears and reappears under the penguin!

The last frame is always available uncompressed at: system.framebuffer.png.

TODO kmscube failed on aarch64 with:

kmscube[706]: unhandled level 2 translation fault (11) at 0x00000000, esr 0x92000006, in libgbm.so.1.0.0[7fbf6a6000+e000]

For aarch64 we also need to configure the kernel with linux_config/display:

git -C "$(./getvar linux_source_dir)" fetch https://gem5.googlesource.com/arm/linux gem5/v4.15:gem5/v4.15
git -C "$(./getvar linux_source_dir)" checkout gem5/v4.15
./build-linux \
  --arch aarch64 \
  --config-fragment linux_config/display \
  --custom-config-file-gem5 \
  --linux-build-id gem5-v4.15 \
;
git -C "$(./getvar linux_source_dir)" checkout -
./run --arch aarch64 --emulator gem5 --linux-build-id gem5-v4.15

This is because the gem5 aarch64 defconfig does not enable HDLCD like the 32 bit one arm one for some reason.

TODO get working. There is an unmerged patchset at: https://gem5-review.googlesource.com/c/public/gem5/+/11036/1

The DP650 is a newer display hardware than HDLCD. TODO is its interface publicly documented anywhere? Since it has a gem5 model and in-tree Linux kernel support, that information cannot be secret?

The key option to enable support in Linux is DRM_MALI_DISPLAY=y which we enable at linux_config/display.

Build the kernel exactly as for Graphic mode gem5 aarch64 and then run with:

./run --arch aarch64 --dp650 --emulator gem5 --linux-build-id gem5-v4.15

We cannot use mainline Linux because the gem5 arm Linux kernel patches are required at least to provide the CONFIG_DRM_VIRT_ENCODER option.

gem5 emulates the HDLCD ARM Holdings hardware for arm and aarch64.

The kernel uses HDLCD to implement the DRM interface, the required kernel config options are present at: linux_config/display.

TODO: minimize out the --custom-config-file. If we just remove it on arm: it does not work with a failing dmesg:

[    0.066208] [drm] found ARM HDLCD version r0p0
[    0.066241] hdlcd 2b000000.hdlcd: bound virt-encoder (ops drm_vencoder_ops)
[    0.066247] [drm] Supports vblank timestamp caching Rev 2 (21.10.2013).
[    0.066252] [drm] No driver support for vblank timestamp query.
[    0.066276] hdlcd 2b000000.hdlcd: Cannot do DMA to address 0x0000000000000000
[    0.066281] swiotlb: coherent allocation failed for device 2b000000.hdlcd size=8294400
[    0.066288] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.15.0 #1
[    0.066293] Hardware name: V2P-AARCH64 (DT)
[    0.066296] Call trace:
[    0.066301]  dump_backtrace+0x0/0x1b0
[    0.066306]  show_stack+0x24/0x30
[    0.066311]  dump_stack+0xb8/0xf0
[    0.066316]  swiotlb_alloc_coherent+0x17c/0x190
[    0.066321]  __dma_alloc+0x68/0x160
[    0.066325]  drm_gem_cma_create+0x98/0x120
[    0.066330]  drm_fbdev_cma_create+0x74/0x2e0
[    0.066335]  __drm_fb_helper_initial_config_and_unlock+0x1d8/0x3a0
[    0.066341]  drm_fb_helper_initial_config+0x4c/0x58
[    0.066347]  drm_fbdev_cma_init_with_funcs+0x98/0x148
[    0.066352]  drm_fbdev_cma_init+0x40/0x50
[    0.066357]  hdlcd_drm_bind+0x220/0x428
[    0.066362]  try_to_bring_up_master+0x21c/0x2b8
[    0.066367]  component_master_add_with_match+0xa8/0xf0
[    0.066372]  hdlcd_probe+0x60/0x78
[    0.066377]  platform_drv_probe+0x60/0xc8
[    0.066382]  driver_probe_device+0x30c/0x478
[    0.066388]  __driver_attach+0x10c/0x128
[    0.066393]  bus_for_each_dev+0x70/0xb0
[    0.066398]  driver_attach+0x30/0x40
[    0.066402]  bus_add_driver+0x1d0/0x298
[    0.066408]  driver_register+0x68/0x100
[    0.066413]  __platform_driver_register+0x54/0x60
[    0.066418]  hdlcd_platform_driver_init+0x20/0x28
[    0.066424]  do_one_initcall+0x44/0x130
[    0.066428]  kernel_init_freeable+0x13c/0x1d8
[    0.066433]  kernel_init+0x18/0x108
[    0.066438]  ret_from_fork+0x10/0x1c
[    0.066444] hdlcd 2b000000.hdlcd: Failed to set initial hw configuration.
[    0.066470] hdlcd 2b000000.hdlcd: master bind failed: -12
[    0.066477] hdlcd: probe of 2b000000.hdlcd failed with error -12

So what other options are missing from gem5_defconfig? It would be cool to minimize it out to better understand the options.

Once you’ve seen the CONFIG_LOGO penguin as a sanity check, you can try to go for a cooler X11 Buildroot setup.

Build and run:

./build-buildroot --config-fragment buildroot_config/x11
./run --graphic

Inside QEMU:

startx

And then from the GUI you can start exciting graphical programs such as:

xcalc
xeyes
x11
Figure 1. X11 Buildroot graphical user interface screenshot

We don’t build X11 by default because it takes a considerable amount of time (about 20%), and is not expected to be used by most users: you need to pass the -x flag to enable it.

Not sure how well that graphics stack represents real systems, but if it does it would be a good way to understand how it works.

To x11 packages have an xserver prefix as in:

./build-buildroot --config-fragment buildroot_config/x11 -- xserver_xorg-server-reconfigure

the easiest way to find them out is to just list "$(./getvar buildroot_build_build_dir)/x*.

TODO as of: c2696c978d6ca88e8b8599c92b1beeda80eb62b2 I noticed that startx leads to a BUG_ON:

[    2.809104] WARNING: CPU: 0 PID: 51 at drivers/gpu/drm/ttm/ttm_bo_vm.c:304 ttm_bo_vm_open+0x37/0x40

TODO 9076c1d9bcc13b6efdb8ef502274f846d8d4e6a1 I’m 100% sure that it was working before, but I didn’t run it forever, and it stopped working at some point. Needs bisection, on whatever commit last touched x11 stuff.

-show-cursor did not help, I just get to see the host cursor, but the guest cursor still does not move.

Doing:

watch -n 1 grep i8042 /proc/interrupts

shows that interrupts do happen when mouse and keyboard presses are done, so I expect that it is some wrong either with:

  • QEMU. Same behaviour if I try the host’s QEMU 2.10.1 however.

  • X11 configuration. We do have BR2_PACKAGE_XDRIVER_XF86_INPUT_MOUSE=y.

/var/log/Xorg.0.log contains the following interesting lines:

[    27.549] (II) LoadModule: "mouse"
[    27.549] (II) Loading /usr/lib/xorg/modules/input/mouse_drv.so
[    27.590] (EE) <default pointer>: Cannot find which device to use.
[    27.590] (EE) <default pointer>: cannot open input device
[    27.590] (EE) PreInit returned 2 for "<default pointer>"
[    27.590] (II) UnloadModule: "mouse"

The file /dev/inputs/mice does not exist.

Note that our current link:kernel_confi_fragment sets:

# CONFIG_INPUT_MOUSE is not set
# CONFIG_INPUT_MOUSEDEV_PSAUX is not set

for gem5, so you might want to remove those lines to debug this.

On ARM, startx hangs at a message:

vgaarb: this pci device is not a vga device

and nothing shows on the screen, and:

grep EE /var/log/Xorg.0.log

says:

(EE) Failed to load module "modesetting" (module does not exist, 0)

A friend told me this but I haven’t tried it yet:

  • xf86-video-modesetting is likely the missing ingredient, but it does not seem possible to activate it from Buildroot currently without patching things.

  • xf86-video-fbdev should work as well, but we need to make sure fbdev is enabled, and maybe add some line to the Xorg.conf

We disable networking by default because it starts an userland process, and we want to keep the number of userland processes to a minimum to make the system more understandable as explained at: [resource-tradeoff-guidelines]

To enable networking on Buildroot, simply run:

ifup -a

That command goes over all (-a) the interfaces in /etc/network/interfaces and brings them up.

Then test it with:

wget google.com
cat index.html

Disable networking with:

ifdown -a

To enable networking by default after boot, use the methods documented at Run command at the end of BusyBox init.

ping does not work within QEMU by default, e.g.:

ping google.com

hangs after printing the header:

PING google.com (216.58.204.46): 56 data bytes

In this section we discuss how to interact between the guest and the host through networking.

First ensure that you can access the external network since that is easier to get working, see: Section 15, “Networking”.

With nc we can create the most minimal example possible as a sanity check.

On guest run:

nc -l -p 45455

Then on host run:

echo asdf | nc localhost 45455

asdf appears on the guest.

This uses:

  • BusyBox' nc utility, which is enabled with CONFIG_NC=y

  • nc from the netcat-openbsd package on an Ubuntu 18.04 host

Only this specific port works by default since we have forwarded it on the QEMU command line.

We us this exact procedure to connect to gdbserver.

Not enabled by default due to the build / runtime overhead. To enable, build with:

./build-buildroot --config 'BR2_PACKAGE_OPENSSH=y'

Then inside the guest turn on sshd:

./sshd.sh

And finally on host:

ssh root@localhost -p 45456

Could not do port forwarding from host to guest, and therefore could not use gdbserver: https://stackoverflow.com/questions/48941494/how-to-do-port-forwarding-from-guest-to-host-in-gem5

Then in the host, start a server:

python -m SimpleHTTPServer 8000

And then in the guest, find the IP we need to hit with:

ip rounte

which gives:

default via 10.0.2.2 dev eth0
10.0.2.0/24 dev eth0 scope link  src 10.0.2.15

so we use in the guest:

wget 10.0.2.2:8000

Bibliography:

The 9p protocol allows the guest to mount a host directory.

Both QEMU and gem5 9P support 9P.

All of 9P and NFS (and sshfs) allow sharing directories between guest and host.

Advantages of 9P

  • requires sudo on the host to mount

  • we could share a guest directory to the host, but this would require running a server on the guest, which adds simulation overhead

    Furthermore, this would be inconvenient, since what we usually want to do is to share host cross built files with the guest, and to do that we would have to copy the files over after the guest starts the server.

  • QEMU implements 9P natively, which makes it very stable and convenient, and must mean it is a simpler protocol than NFS as one would expect.

    This is not the case for gem5 7bfb7f3a43f382eb49853f47b140bfd6caad0fb8 unfortunately, which relies on the diod host daemon, although it is not unfeasible that future versions could implement it natively as well.

Advantages of NFS:

  • way more widely used and therefore stable and available, not to mention that it also works on real hardware.

  • the name does not start with a digit, which is an invalid identifier in all programming languages known to man. Who in their right mind would call a software project as such? It does not even match the natural order of Plan 9; Plan then 9: P9!

As usual, we have already set everything up for you. On host:

cd "$(./getvar p9_dir)"
uname -a > host

Guest:

cd /mnt/9p/data
cat host
uname -a > guest

Host:

cat guest

The main ingredients for this are:

Bibliography:

Is possible on aarch64 as shown at: https://gem5-review.googlesource.com/c/public/gem5/+/22831, and it is just a matter of exposing to X86 for those that want it.

Enable it by passing the --vio-9p option on the fs.py gem5 command line:

./run --arch aarch64 --emulator gem5 -- --vio-9p

Then on the guest:

mkdir -p /mnt/9p/gem5
mount -t 9p -o trans=virtio,version=9p2000.L,aname=/path/to/linux-kernel-module-cheat/out/run/gem5/aarch64/0/m5out/9p/share gem5 /mnt/9p/gem5
echo asdf > /mnt/9p/gem5/qwer

Yes, you have to pass the full path to the directory on the host. Yes, this is horrible.

The shared directory is:

out/run/gem5/aarch64/0/m5out/9p/share

so we can observe the file the guest wrote from the host with:

out/run/gem5/aarch64/0/m5out/9p/share/qwer

and vice versa:

echo zxvc > out/run/gem5/aarch64/0/m5out/9p/share/qwer

is now visible from the guest:

cat /mnt/9p/gem5/qwer

Checkpoint restore with an open mount will likely fail because gem5 uses an ugly external executable to implement diod. The protocol is not very complex, and QEMU implements it in-tree, which is what gem5 should do as well at some point.

Also checkpoint without --vio-9p and restore with --vio-9p did not work either, the mount fails.

However, this did work, on guest:

unmount /mnt/9p/gem5
m5 checkpoint

then restore with the detalied CPU of interest e.g.

./run --arch aarch64 --emulator gem5 -- --vio-9p --cpu-type DerivO3CPU --caches

Tested on gem5 b2847f43c91e27f43bd4ac08abd528efcf00f2fd, LKMC 52a5fdd7c1d6eadc5900fc76e128995d4849aada.

TODO: get working.

9P is better with emulation, but let’s just get this working for fun.

First make sure that this works: Section 15.3.2, “Guest to host networking”.

Then, build the kernel with NFS support:

./build-linux --config-fragment linux_config/nfs

Now on host:

sudo apt-get install nfs-kernel-server

Now edit /etc/exports to contain:

/tmp *(rw,sync,no_root_squash,no_subtree_check)

and restart the server:

sudo systemctl restart nfs-kernel-server

Now on guest:

mkdir /mnt/nfs
mount -t nfs 10.0.2.2:/tmp /mnt/nfs

TODO: failing with:

mount: mounting 10.0.2.2:/tmp on /mnt/nfs failed: No such device

And now the /tmp directory from host is not mounted on guest!

If you don’t want to start the NFS server after the next boot automatically so save resources, do:

systemctl disable nfs-kernel-server

To modify a single option on top of our default kernel configs, do:

./build-linux --config 'CONFIG_FORTIFY_SOURCE=y'

Kernel modules depend on certain kernel configs, and therefore in general you might have to clean and rebuild the kernel modules after changing the kernel config:

./build-modules --clean
./build-modules

and then proceed as in Your first kernel module hack.

You might often get way without rebuilding the kernel modules however.

To use an extra kernel config fragment file on top of our defaults, do:

printf '
CONFIG_IKCONFIG=y
CONFIG_IKCONFIG_PROC=y
' > data/myconfig
./build-linux --config-fragment 'data/myconfig'

To use just your own exact .config instead of our defaults ones, use:

./build-linux --custom-config-file data/myconfig

There is also a shortcut --custom-config-file-gem5 to use the gem5 arm Linux kernel patches.

The following options can all be used together, sorted by decreasing config setting power precedence:

  • --config

  • --config-fragment

  • --custom-config-file

To do a clean menu config yourself and use that for the build, do:

./build-linux --clean
./build-linux --custom-config-target menuconfig

But remember that every new build re-configures the kernel by default, so to keep your configs you will need to use on further builds:

./build-linux --no-configure

So what you likely want to do instead is to save that as a new defconfig and use it later as:

./build-linux --no-configure --no-modules-install savedefconfig
cp "$(./getvar linux_build_dir)/defconfig" data/myconfig
./build-linux --custom-config-file data/myconfig

You can also use other config generating targets such as defconfig with the same method as shown at: Section 17.1.3.1.1, “Linux kernel defconfig”.

Get the build config in guest:

zcat /proc/config.gz

or with our shortcut:

./conf.sh

or to conveniently grep for a specific option case insensitively:

./conf.sh ikconfig

This is enabled by:

CONFIG_IKCONFIG=y
CONFIG_IKCONFIG_PROC=y

From host:

cat "$(./getvar linux_config)"
./linux/scripts/extract-ikconfig "$(./getvar vmlinux)"

although this can be useful when someone gives you a random image.

By default, build-linux generates a .config that is a mixture of:

To find out which kernel configs are being used exactly, simply run:

./build-linux --dry-run

and look for the merge_config.sh call. This script from the Linux kernel tree, as the name suggests, merges multiple configuration files into one as explained at: https://unix.stackexchange.com/questions/224887/how-to-script-make-menuconfig-to-automate-linux-kernel-build-configuration/450407#450407

For each arch, the base of our configs are named as:

linux_config/buildroot-<arch>

These configs are extracted directly from a Buildroot build with update-buildroot-kernel-configs.

Note that Buildroot can sed override some of the configurations, e.g. it forces CONFIG_BLK_DEV_INITRD=y when BR2_TARGET_ROOTFS_CPIO is on. For this reason, those configs are not simply copy pasted from Buildroot files, but rather from a Buildroot kernel build, and then minimized with make savedefconfig: https://stackoverflow.com/questions/27899104/how-to-create-a-defconfig-file-from-a-config

On top of those, we add the following by default:

To see Buildroot’s base configs, start from buildroot/configs/qemu_x86_64_defconfig.

That file contains BR2_LINUX_KERNEL_CUSTOM_CONFIG_FILE="board/qemu/x86_64/linux-4.15.config", which points to the base config file used: board/qemu/x86_64/linux-4.15.config.

arm, on the other hand, uses buildroot/configs/qemu_arm_vexpress_defconfig, which contains BR2_LINUX_KERNEL_DEFCONFIG="vexpress", and therefore just does a make vexpress_defconfig, and gets its config from the Linux kernel tree itself.

To boot defconfig from disk on Linux and see a shell, all we need is these missing virtio options:

./build-linux \
  --linux-build-id defconfig \
  --custom-config-target defconfig \
  --config CONFIG_VIRTIO_PCI=y \
  --config CONFIG_VIRTIO_BLK=y \
;
./run --linux-build-id defconfig

Oh, and check this out:

du -h \
  "$(./getvar vmlinux)" \
  "$(./getvar --linux-build-id defconfig vmlinux)" \
;

Output:

360M    /path/to/linux-kernel-module-cheat/out/linux/default/x86_64/vmlinux
47M     /path/to/linux-kernel-module-cheat/out/linux/defconfig/x86_64/vmlinux

Brutal. Where did we go wrong?

The extra virtio options are not needed if we use initrd:

./build-linux \
  --linux-build-id defconfig \
  --custom-config-target defconfig \
;
./run --initrd --linux-build-id defconfig

On aarch64, we can boot from initrd with:

./build-linux \
  --arch aarch64 \
  --linux-build-id defconfig \
  --custom-config-target defconfig \
;
./run \
  --arch aarch64 \
  --initrd \
  --linux-build-id defconfig \
  --memory 2G \
;

We need the 2G of memory because the CPIO is 600MiB due to a humongous amount of loadable kernel modules!

In aarch64, the size situation is inverted from x86_64, and this can be seen on the vmlinux size as well:

118M    /path/to/linux-kernel-module-cheat/out/linux/default/aarch64/vmlinux
240M    /path/to/linux-kernel-module-cheat/out/linux/defconfig/aarch64/vmlinux

So it seems that the ARM devs decided rather than creating a minimal config that boots QEMU, to try and make a single config that boots every board in existence. Terrible!

Tested on 1e2b7f1e5e9e3073863dc17e25b2455c8ebdeadd + 1.

linux_config/min contains minimal tweaks required to boot gem5 or for using our slightly different QEMU command line options than Buildroot on all archs.

It is one of the default config fragments we use, as explained at: Section 17.1.3, “About our Linux kernel configs”>.

Having the same config working for both QEMU and gem5 (oh, the hours of bisection) means that you can deal with functional matters in QEMU, which runs much faster, and switch to gem5 only for performance issues.

We can build just with min on top of the base config with:

./build-linux \
  --arch aarch64 \
  --config-fragment linux_config/min \
  --custom-config-file linux_config/buildroot-aarch64 \
  --linux-build-id min \
;

vmlinux had a very similar size to the default. It seems that linux_config/buildroot-aarch64 contains or implies most linux_config/default options already? TODO: that seems odd, really?

Tested on 649d06d6758cefd080d04dc47fd6a5a26a620874 + 1.

Other configs which we had previously tested at 4e0d9af81fcce2ce4e777cb82a1990d7c2ca7c1e are:

We try to use the latest possible kernel major release version.

In QEMU:

cat /proc/version

or in the source:

cd "$(./getvar linux_source_dir)"
git log | grep -E '    Linux [0-9]+\.' | head

During update all you kernel modules may break since the kernel API is not stable.

They are usually trivial breaks of things moving around headers or to sub-structs.

The userland, however, should simply not break, as Linus enforces strict backwards compatibility of userland interfaces.

This backwards compatibility is just awesome, it makes getting and running the latest master painless.

This also makes this repo the perfect setup to develop the Linux kernel.

In case something breaks while updating the Linux kernel, you can try to bisect it to understand the root cause, see: [bisection].

First, use use the branching procedure described at: [update-a-forked-submodule]

Because the kernel is so central to this repository, almost all tests must be re-run, so basically just follow the full testing procedure described at: [test-this-repo]. The only tests that can be skipped are essentially the [baremetal] tests.

Before comitting, don’t forget to update:

  • the linux_kernel_version constant in common.py

  • the tagline of this repository on:

    • this README

    • the GitHub project description

The kernel is not forward compatible, however, so downgrading the Linux kernel requires downgrading the userland too to the latest Buildroot branch that supports it.

The default Linux kernel version is bumped in Buildroot with commit messages of type:

linux: bump default to version 4.9.6

So you can try:

git log --grep 'linux: bump default to version'

Those commits change BR2_LINUX_KERNEL_LATEST_VERSION in /linux/Config.in.

You should then look up if there is a branch that supports that kernel. Staying on branches is a good idea as they will get backports, in particular ones that fix the build as newer host versions come out.

Finally, after downgrading Buildroot, if something does not work, you might also have to make some changes to how this repo uses Buildroot, as the Buildroot configuration options might have changed.

We don’t expect those changes to be very difficult. A good way to approach the task is to:

  • do a dry run build to get the equivalent Bash commands used:

    ./build-buildroot --dry-run
  • build the Buildroot documentation for the version you are going to use, and check if all Buildroot build commands make sense there

Then, if you spot an option that is wrong, some grepping in this repo should quickly point you to the code you need to modify.

It also possible that you will need to apply some patches from newer Buildroot versions for it to build, due to incompatibilities with the host Ubuntu packages and that Buildroot version. Just read the error message, and try:

  • git log master — packages/<pkg>

  • Google the error message for mailing list hits

Successful port reports:

Bootloaders can pass a string as input to the Linux kernel when it is booting to control its behaviour, much like the execve system call does to userland processes.

This allows us to control the behaviour of the kernel without rebuilding anything.

With QEMU, QEMU itself acts as the bootloader, and provides the -append option and we expose it through ./run --kernel-cli, e.g.:

./run --kernel-cli 'foo bar'

Then inside the host, you can check which options were given with:

cat /proc/cmdline

They are also printed at the beginning of the boot message:

dmesg | grep "Command line"

See also:

The arguments are documented in the kernel documentation: https://www.kernel.org/doc/html/v4.14/admin-guide/kernel-parameters.html

When dealing with real boards, extra command line options are provided on some magic bootloader configuration file, e.g.:

Double quotes can be used to escape spaces as in opt="a b", but double quotes themselves cannot be escaped, e.g. opt"a\"b"

This even lead us to use base64 encoding with --eval!

There are two methods:

  • __setup as in:

    __setup("console=", console_setup);
  • core_param as in:

    core_param(panic, panic_timeout, int, 0644);

core_param suggests how they are different:

/**
 * core_param - define a historical core kernel parameter.

...

 * core_param is just like module_param(), but cannot be modular and
 * doesn't add a prefix (such as "printk.").  This is for compatibility
 * with __setup(), and it makes sense as truly core parameters aren't
 * tied to the particular file they're in.
 */

By default, the Linux kernel mounts the root filesystem as readonly. TODO rationale?

This cannot be observed in the default BusyBox init, because by default our rootfs_overlay/etc/inittab does:

/bin/mount -o remount,rw /

Analogously, Ubuntu 18.04 does in its fstab something like:

UUID=/dev/sda1 / ext4 errors=remount-ro 0 1

which uses default mount rw flags.

We have however removed those setups init setups to keep things more minimal, and replaced them with the rw kernel boot parameter makes the root mounted as writable.

To observe the default readonly behaviour, hack the run script to remove replace init, and then run on a raw shell:

./run --kernel-cli 'init=/bin/sh'

Now try to do:

touch a

which fails with:

touch: a: Read-only file system

We can also observe the read-onlyness with:

mount -t proc /proc
mount

which contains:

/dev/root on / type ext2 (ro,relatime,block_validity,barrier,user_xattr)

and so it is Read Only as shown by ro.

Disable userland address space randomization. Test it out by running [rand-check-out] twice:

./run --eval-after './linux/rand_check.out;./linux/poweroff.out'
./run --eval-after './linux/rand_check.out;./linux/poweroff.out'

If we remove it from our run script by hacking it up, the addresses shown by linux/rand_check.out vary across boots.

Equivalent to:

echo 0 > /proc/sys/kernel/randomize_va_space

printk is the most simple and widely used way of getting information from the kernel, so you should familiarize yourself with its basic configuration.

We use printk a lot in our kernel modules, and it shows on the terminal by default, along with stdout and what you type.

Hide all printk messages:

dmesg -n 1

or equivalently:

echo 1 > /proc/sys/kernel/printk

Do it with a Kernel command line parameters to affect the boot itself:

./run --kernel-cli 'loglevel=5'

and now only boot warning messages or worse show, which is useful to identify problems.

Our default printk format is:

<LEVEL>[TIMESTAMP] MESSAGE

e.g.:

<6>[    2.979121] Freeing unused kernel memory: 2024K

where:

  • LEVEL: higher means less serious

  • TIMESTAMP: seconds since boot

This format is selected by the following boot options:

  • console_msg_format=syslog: add the <LEVEL> part. Added in v4.16.

  • printk.time=y: add the [TIMESTAMP] part

The debug highest level is a bit more magic, see: Section 17.4.3, “pr_debug” for more info.

The current printk level can be obtained with:

cat /proc/sys/kernel/printk

As of 87e846fc1f9c57840e143513ebd69c638bd37aa8 this prints:

7       4       1       7

which contains:

  • 7: current log level, modifiable by previously mentioned methods

  • 4: documented as: "printk’s without a loglevel use this": TODO what does that mean, how to call printk without a log level?

  • 1: minimum log level that still prints something (0 prints nothing)

  • 7: default log level

We start at the boot time default after boot by default, as can be seen from:

insmod myprintk.ko

which outputs something like:

<1>[   12.494429] pr_alert
<2>[   12.494666] pr_crit
<3>[   12.494823] pr_err
<4>[   12.494911] pr_warning
<5>[   12.495170] pr_notice
<6>[   12.495327] pr_info
#if defined CONFIG_PRINTK
	{
		.procname	= "printk",
		.data		= &console_loglevel,
		.maxlen		= 4*sizeof(int),
		.mode		= 0644,
		.proc_handler	= proc_dointvec,
	},

which teaches us that printk can be completely disabled at compile time:

config PRINTK
	default y
	bool "Enable support for printk" if EXPERT
	select IRQ_WORK
	help
	  This option enables normal printk support. Removing it
	  eliminates most of the message strings from the kernel image
	  and makes the kernel more or less silent. As this makes it
	  very difficult to diagnose system problems, saying N here is
	  strongly discouraged.

console_loglevel is defined at:

#define console_loglevel (console_printk[0])

and console_printk is an array with 4 ints:

int console_printk[4] = {
	CONSOLE_LOGLEVEL_DEFAULT,	/* console_loglevel */
	MESSAGE_LOGLEVEL_DEFAULT,	/* default_message_loglevel */
	CONSOLE_LOGLEVEL_MIN,		/* minimum_console_loglevel */
	CONSOLE_LOGLEVEL_DEFAULT,	/* default_console_loglevel */
};

and then we see that the default is configurable with CONFIG_CONSOLE_LOGLEVEL_DEFAULT:

/*
 * Default used to be hard-coded at 7, quiet used to be hardcoded at 4,
 * we're now allowing both to be set from kernel config.
 */
#define CONSOLE_LOGLEVEL_DEFAULT CONFIG_CONSOLE_LOGLEVEL_DEFAULT
#define CONSOLE_LOGLEVEL_QUIET	 CONFIG_CONSOLE_LOGLEVEL_QUIET

The message loglevel default is explained at:

/* printk's without a loglevel use this.. */
#define MESSAGE_LOGLEVEL_DEFAULT CONFIG_MESSAGE_LOGLEVEL_DEFAULT

The min is just hardcoded to one as you would expect, with some amazing kernel comedy around it:

/* We show everything that is MORE important than this.. */
#define CONSOLE_LOGLEVEL_SILENT  0 /* Mum's the word */
#define CONSOLE_LOGLEVEL_MIN	 1 /* Minimum loglevel we let people use */
#define CONSOLE_LOGLEVEL_DEBUG	10 /* issue debug messages */
#define CONSOLE_LOGLEVEL_MOTORMOUTH 15	/* You can't shut this one up */

We then also learn about the useless quiet and debug kernel parameters at:

config CONSOLE_LOGLEVEL_QUIET
	int "quiet console loglevel (1-15)"
	range 1 15
	default "4"
	help
	  loglevel to use when "quiet" is passed on the kernel commandline.

	  When "quiet" is passed on the kernel commandline this loglevel
	  will be used as the loglevel. IOW passing "quiet" will be the
	  equivalent of passing "loglevel=<CONSOLE_LOGLEVEL_QUIET>"

which explains the useless reason why that number is special. This is implemented at:

static int __init debug_kernel(char *str)
{
	console_loglevel = CONSOLE_LOGLEVEL_DEBUG;
	return 0;
}

static int __init quiet_kernel(char *str)
{
	console_loglevel = CONSOLE_LOGLEVEL_QUIET;
	return 0;
}

early_param("debug", debug_kernel);
early_param("quiet", quiet_kernel);
./run --kernel-cli 'ignore_loglevel'

enables all log levels, and is basically the same as:

./run --kernel-cli 'loglevel=8'

except that you don’t need to know what is the maximum level.

Debug messages are not printable by default without recompiling.

But the awesome CONFIG_DYNAMIC_DEBUG=y option which we enable by default allows us to do:

echo 8 > /proc/sys/kernel/printk
echo 'file kernel/module.c +p' > /sys/kernel/debug/dynamic_debug/control
./linux/myinsmod.out hello.ko

and we have a shortcut at:

./pr_debug.sh

Wildcards are also accepted, e.g. enable all messages from all files:

echo 'file * +p' > /sys/kernel/debug/dynamic_debug/control

TODO: why is this not working:

echo 'func sys_init_module +p' > /sys/kernel/debug/dynamic_debug/control

Enable messages in specific modules:

echo 8 > /proc/sys/kernel/printk
echo 'module myprintk +p' > /sys/kernel/debug/dynamic_debug/control
insmod myprintk.ko

This outputs the pr_debug message:

printk debug

but TODO: it also shows debug messages even without enabling them explicitly:

echo 8 > /proc/sys/kernel/printk
insmod myprintk.ko

and it shows as enabled:

# grep myprintk /sys/kernel/debug/dynamic_debug/control
/root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules/panic.c:12 [myprintk]myinit =p "pr_debug\012"

Enable pr_debug for boot messages as well, before we can reach userland and write to /proc:

./run --kernel-cli 'dyndbg="file * +p" loglevel=8'

Get ready for the noisiest boot ever, I think it overflows the printk buffer and funny things happen.

When CONFIG_DYNAMIC_DEBUG is set, printk(KERN_DEBUG is not the exact same as pr_debug( since printk(KERN_DEBUG messages are visible with:

./run --kernel-cli 'initcall_debug logleve=8'

which outputs lines of type:

<7>[    1.756680] calling  clk_disable_unused+0x0/0x130 @ 1
<7>[    1.757003] initcall clk_disable_unused+0x0/0x130 returned 0 after 111 usecs

which are printk(KERN_DEBUG inside init/main.c in v4.16.

This likely comes from the ifdef split at init/main.c:

/* If you are writing a driver, please use dev_dbg instead */
#if defined(CONFIG_DYNAMIC_DEBUG)
#include <linux/dynamic_debug.h>

/* dynamic_pr_debug() uses pr_fmt() internally so we don't need it here */
#define pr_debug(fmt, ...) \
    dynamic_pr_debug(fmt, ##__VA_ARGS__)
#elif defined(DEBUG)
#define pr_debug(fmt, ...) \
    printk(KERN_DEBUG pr_fmt(fmt), ##__VA_ARGS__)
#else
#define pr_debug(fmt, ...) \
    no_printk(KERN_DEBUG pr_fmt(fmt), ##__VA_ARGS__)
#endif

The Linux kernel allows passing module parameters at insertion time through the init_module and finit_module system calls.

The insmod tool exposes that as:

insmod params.ko i=3 j=4

Parameters are declared in the module as:

static u32 i = 0;
module_param(i, int, S_IRUSR | S_IWUSR);
MODULE_PARM_DESC(i, "my favorite int");

Automated test:

./params.sh
echo $?

Outcome: the test passes:

0

Sources:

As shown in the example, module parameters can also be read and modified at runtime from sysfs.

We can obtain the help text of the parameters with:

modinfo params.ko

The output contains:

parm:           j:my second favorite int
parm:           i:my favorite int

modprobe insertion can also set default parameters via the /etc/modprobe.conf file:

modprobe params
cat /sys/kernel/debug/lkmc_params

Output:

12 34

This is specially important when loading modules with Kernel module dependencies or else we would have no opportunity of passing those.

One module can depend on symbols of another module that are exported with EXPORT_SYMBOL:

./dep.sh
echo $?

Outcome: the test passes:

0

Sources:

The kernel deduces dependencies based on the EXPORT_SYMBOL that each module uses.

Symbols exported by EXPORT_SYMBOL can be seen with:

insmod dep.ko
grep lkmc_dep /proc/kallsyms

sample output:

ffffffffc0001030 r __ksymtab_lkmc_dep   [dep]
ffffffffc000104d r __kstrtab_lkmc_dep   [dep]
ffffffffc0002300 B lkmc_dep     [dep]

This requires CONFIG_KALLSYMS_ALL=y.

Dependency information is stored by the kernel module build system in the .ko files' MODULE_INFO, e.g.:

modinfo dep2.ko

contains:

depends:        dep

We can double check with:

strings 3 dep2.ko | grep -E 'depends'

The output contains:

depends=dep

Module dependencies are also stored at:

cd /lib/module/*
grep dep modules.dep

Output:

extra/dep2.ko: extra/dep.ko
extra/dep.ko:

TODO: what for, and at which point point does Buildroot / BusyBox generate that file?

Unlike insmod, modprobe deals with kernel module dependencies for us.

Then, for example:

modprobe buildroot_dep2

outputs to dmesg:

42

and then:

lsmod

outputs:

Module                  Size  Used by    Tainted: G
buildroot_dep2         16384  0
buildroot_dep          16384  1 buildroot_dep2

Sources:

Removal also removes required modules that have zero usage count:

modprobe -r buildroot_dep2

modprobe uses information from the modules.dep file to decide the required dependencies. That file contains:

extra/buildroot_dep2.ko: extra/buildroot_dep.ko

Bibliography:

Module metadata is stored on module files at compile time. Some of the fields can be retrieved through the THIS_MODULE struct module:

insmod module_info.ko

Dmesg output:

name = module_info
version = 1.0

Some of those are also present on sysfs:

cat /sys/module/module_info/version

Output:

1.0

And we can also observe them with the modinfo command line utility:

modinfo module_info.ko

sample output:

filename:       module_info.ko
license:        GPL
version:        1.0
srcversion:     AF3DE8A8CFCDEB6B00E35B6
depends:
vermagic:       4.17.0 SMP mod_unload modversions

Module information is stored in a special .modinfo section of the ELF file:

./run-toolchain readelf -- -SW "$(./getvar kernel_modules_build_subdir)/module_info.ko"

contains:

  [ 5] .modinfo          PROGBITS        0000000000000000 0000d8 000096 00   A  0   0  8

and:

./run-toolchain readelf -- -x .modinfo "$(./getvar kernel_modules_build_subdir)/module_info.ko"

gives:

  0x00000000 6c696365 6e73653d 47504c00 76657273 license=GPL.vers
  0x00000010 696f6e3d 312e3000 61736466 3d717765 ion=1.0.asdf=qwe
  0x00000020 72000000 00000000 73726376 65727369 r.......srcversi
  0x00000030 6f6e3d41 46334445 38413843 46434445 on=AF3DE8A8CFCDE
  0x00000040 42364230 30453335 42360000 00000000 B6B00E35B6......
  0x00000050 64657065 6e64733d 006e616d 653d6d6f depends=.name=mo
  0x00000060 64756c65 5f696e66 6f007665 726d6167 dule_info.vermag
  0x00000070 69633d34 2e31372e 3020534d 50206d6f ic=4.17.0 SMP mo
  0x00000080 645f756e 6c6f6164 206d6f64 76657273 d_unload modvers
  0x00000090 696f6e73 2000                       ions .

I think a dedicated section is used to allow the Linux kernel and command line tools to easily parse that information from the ELF file as we’ve done with readelf.

Bibliography:

As of kernel v5.8, you can’t use VERMAGIC_STRING string from modules anymore as per: https://github.com/************/linux/commit/51161bfc66a68d21f13d15a689b3ea7980457790. So instead we just showcase init_utsname.

Sample insmod output as of LKMC fa8c2ee521ea83a74a2300e7a3be9f9ab86e2cb6 + 1 aarch64:

<6>[   25.180697] sysname    = Linux
<6>[   25.180697] nodename   = buildroot
<6>[   25.180697] release    = 5.9.2
<6>[   25.180697] version    = #1 SMP Thu Jan 1 00:00:00 UTC 1970
<6>[   25.180697] machine    = aarch64
<6>[   25.180697] domainname = (none)

Vermagic is a magic string present in the kernel and previously visible in MODULE_INFO on kernel modules. It is used to verify that the kernel module was compiled against a compatible kernel version and relevant configuration:

insmod vermagic.ko

Possible dmesg output:

VERMAGIC_STRING = 4.17.0 SMP mod_unload modversions

If we artificially create a mismatch with MODULE_INFO(vermagic, the insmod fails with:

insmod: can't insert 'vermagic_fail.ko': invalid module format

and dmesg says the expected and found vermagic found:

vermagic_fail: version magic 'asdfqwer' should be '4.17.0 SMP mod_unload modversions '

The kernel’s vermagic is defined based on compile time configurations at include/linux/vermagic.h:

#define VERMAGIC_STRING                                                 \
        UTS_RELEASE " "                                                 \
        MODULE_VERMAGIC_SMP MODULE_VERMAGIC_PREEMPT                     \
        MODULE_VERMAGIC_MODULE_UNLOAD MODULE_VERMAGIC_MODVERSIONS       \
        MODULE_ARCH_VERMAGIC                                            \
        MODULE_RANDSTRUCT_PLUGIN

The SMP part of the string for example is defined on the same file based on the value of CONFIG_SMP:

#ifdef CONFIG_SMP
#define MODULE_VERMAGIC_SMP "SMP "
#else
#define MODULE_VERMAGIC_SMP ""

TODO how to get the vermagic from running kernel from userland? https://lists.kernelnewbies.org/pipermail/kernelnewbies/2012-October/006306.html

kmod modprobe has a flag to skip the vermagic check:

--force-modversion

This option just strips modversion information from the module before loading, so it is not a kernel feature.

init_module and cleanup_module are an older alternative to the module_init and module_exit macros:

insmod init_module.ko
rmmod init_module

Dmesg output:

init_module
cleanup_module

It is generally hard / impossible to use floating point operations in the kernel. TODO understand details.

A quick (x86-only for now because lazy) example is shown at: kernel_modules/float.c

Usage:

insmod float.ko myfloat=1 enable_fpu=1

We have to call: kernel_fpu_begin() before starting FPU operations, and kernel_fpu_end() when we are done. This particular example however did not blow up without it at lkmc 7f917af66b17373505f6c21d75af9331d624b3a9 + 1:

insmod float.ko myfloat=1 enable_fpu=0

The v5.1 documentation under arch/x86/include/asm/fpu/api.h reads:

 * Use kernel_fpu_begin/end() if you intend to use FPU in kernel context. It
 * disables preemption so be careful if you intend to use it for long periods
 * of time.

The example sets in the kernel_modules/Makefile:

CFLAGS_REMOVE_float.o += -mno-sse -mno-sse2

to avoid:

error: SSE register return with SSE disabled

We found those flags with ./build-modules --verbose.

Bibliography:

To test out kernel panics and oops in controlled circumstances, try out the modules:

insmod panic.ko
insmod oops.ko

Source:

A panic can also be generated with:

echo c > /proc/sysrq-trigger

How to generate them:

When a panic happens, Shift-PgUp does not work as it normally does, and it is hard to get the logs if on are on QEMU graphic mode:

On panic, the kernel dies, and so does our terminal.

The panic trace looks like:

panic: loading out-of-tree module taints kernel.
panic myinit
Kernel panic - not syncing: hello panic
CPU: 0 PID: 53 Comm: insmod Tainted: G           O     4.16.0 #6
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.11.0-0-g63451fca13-prebuilt.qemu-project.org 04/01/2014
Call Trace:
 dump_stack+0x7d/0xba
 ? 0xffffffffc0000000
 panic+0xda/0x213
 ? printk+0x43/0x4b
 ? 0xffffffffc0000000
 myinit+0x1d/0x20 [panic]
 do_one_initcall+0x3e/0x170
 do_init_module+0x5b/0x210
 load_module+0x2035/0x29d0
 ? kernel_read_file+0x7d/0x140
 ? SyS_finit_module+0xa8/0xb0
 SyS_finit_module+0xa8/0xb0
 do_syscall_64+0x6f/0x310
 ? trace_hardirqs_off_thunk+0x1a/0x32
 entry_SYSCALL_64_after_hwframe+0x42/0xb7
RIP: 0033:0x7ffff7b36206
RSP: 002b:00007fffffffeb78 EFLAGS: 00000206 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000000005c RCX: 00007ffff7b36206
RDX: 0000000000000000 RSI: 000000000069e010 RDI: 0000000000000003
RBP: 000000000069e010 R08: 00007ffff7ddd320 R09: 0000000000000000
R10: 00007ffff7ddd320 R11: 0000000000000206 R12: 0000000000000003
R13: 00007fffffffef4a R14: 0000000000000000 R15: 0000000000000000
Kernel Offset: disabled
---[ end Kernel panic - not syncing: hello panic

Notice how our panic message hello panic is visible at:

Kernel panic - not syncing: hello panic

The log shows which module each symbol belongs to if any, e.g.:

myinit+0x1d/0x20 [panic]

says that the function myinit is in the module panic.

To find the line that panicked, do:

./run-gdb

and then:

info line *(myinit+0x1d)

which gives us the correct line:

Line 7 of "/root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules/panic.c" starts at address 0xbf00001c <myinit+28> and ends at 0xbf00002c <myexit>.

The exact same thing can be done post mortem with:

./run-toolchain gdb -- \
  -batch \
  -ex 'info line *(myinit+0x1d)' \
  "$(./getvar kernel_modules_build_subdir)/panic.ko" \
;

Related:

Basically just calls panic("BUG!") for most archs.

For testing purposes, it is very useful to quit the emulator automatically with exit status non zero in case of kernel panic, instead of just hanging forever.

Enabled by default with:

Also asked at https://unix.stackexchange.com/questions/443017/can-i-make-qemu-exit-with-failure-on-kernel-panic which also mentions the x86_64 -device pvpanic, but I don’t see much advantage to it.

TODO neither method exits with exit status different from 0, so for now we are just grepping the logs for panic messages, which sucks.

One possibility that gets close would be to use GDB step debug to break at the panic function, and then send a QEMU monitor from GDB quit command if that happens, but I don’t see a way to exit with non-zero status to indicate error.

gem5 9048ef0ffbf21bedb803b785fb68f83e95c04db8 (January 2019) can detect panics automatically if the option system.panic_on_panic is on.

It parses kernel symbols and detecting when the PC reaches the address of the panic function. gem5 then prints to stdout:

Kernel panic in simulated kernel

and exits with status -6.

At gem5 ff52563a214c71fcd1e21e9f00ad839612032e3b (July 2018) behaviour was different, and just exited 0: https://www.mail-archive.com/[email protected]/msg15870.html TODO find fixing commit.

We enable the system.panic_on_panic option by default on arm and aarch64, which makes gem5 exit immediately in case of panic, which is awesome!

If we don’t set system.panic_on_panic, then gem5 just hangs on an infinite guest loop.

TODO: why doesn’t gem5 x86 ff52563a214c71fcd1e21e9f00ad839612032e3b support system.panic_on_panic as well? Trying to set system.panic_on_panic there fails with:

tried to set or access non-existentobject parameter: panic_on_panic

However, at that commit panic on x86 makes gem5 crash with:

panic: i8042 "System reset" command not implemented.

which is a good side effect of an unimplemented hardware feature, since the simulation actually stops.

        kernelPanicEvent = addKernelFuncEventOrPanic<Linux::KernelPanicEvent>(
            "panic", "Kernel panic in simulated kernel", dmesg_output);

Here we see that the symbol "panic" for the panic() function is the one being tracked.

Make the kernel reboot after n seconds after panic:

echo 1 > /proc/sys/kernel/panic

Can also be controlled with the panic= kernel boot parameter.

0 to disable, -1 to reboot immediately.

Bibliography:

If CONFIG_KALLSYMS=n, then addresses are shown on traces instead of symbol plus offset.

In v4.16 it does not seem possible to configure that at runtime. GDB step debugging with:

./run --eval-after 'insmod dump_stack.ko' --gdb-wait --tmux-args dump_stack

shows that traces are printed at arch/x86/kernel/dumpstack.c:

static void printk_stack_address(unsigned long address, int reliable,
                 char *log_lvl)
{
    touch_nmi_watchdog();
    printk("%s %s%pB\n", log_lvl, reliable ? "" : "? ", (void *)address);
}

and %pB is documented at Documentation/core-api/printk-formats.rst:

If KALLSYMS are disabled then the symbol address is printed instead.

I wasn’t able do disable CONFIG_KALLSYMS to test this this out however, it is being selected by some other option? But I then used make menuconfig to see which options select it, and they were all off…​

On oops, the shell still lives after.

However we:

  • leave the normal control flow, and oops after never gets printed: an interrupt is serviced

  • cannot rmmod oops afterwards

It is possible to make oops lead to panics always with:

echo 1 > /proc/sys/kernel/panic_on_oops
insmod oops.ko

An oops stack trace looks like:

BUG: unable to handle kernel NULL pointer dereference at 0000000000000000
IP: myinit+0x18/0x30 [oops]
PGD dccf067 P4D dccf067 PUD dcc1067 PMD 0
Oops: 0002 [#1] SMP NOPTI
Modules linked in: oops(O+)
CPU: 0 PID: 53 Comm: insmod Tainted: G           O     4.16.0 #6
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.11.0-0-g63451fca13-prebuilt.qemu-project.org 04/01/2014
RIP: 0010:myinit+0x18/0x30 [oops]
RSP: 0018:ffffc900000d3cb0 EFLAGS: 00000282
RAX: 000000000000000b RBX: ffffffffc0000000 RCX: ffffffff81e3e3a8
RDX: 0000000000000001 RSI: 0000000000000086 RDI: ffffffffc0001033
RBP: ffffc900000d3e30 R08: 69796d2073706f6f R09: 000000000000013b
R10: ffffea0000373280 R11: ffffffff822d8b2d R12: 0000000000000000
R13: ffffffffc0002050 R14: ffffffffc0002000 R15: ffff88000dc934c8
FS:  00007ffff7ff66a0(0000) GS:ffff88000fc00000(0000) knlGS:0000000000000000
CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 0000000000000000 CR3: 000000000dcd2000 CR4: 00000000000006f0
Call Trace:
 do_one_initcall+0x3e/0x170
 do_init_module+0x5b/0x210
 load_module+0x2035/0x29d0
 ? SyS_finit_module+0xa8/0xb0
 SyS_finit_module+0xa8/0xb0
 do_syscall_64+0x6f/0x310
 ? trace_hardirqs_off_thunk+0x1a/0x32
 entry_SYSCALL_64_after_hwframe+0x42/0xb7
RIP: 0033:0x7ffff7b36206
RSP: 002b:00007fffffffeb78 EFLAGS: 00000206 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000000005c RCX: 00007ffff7b36206
RDX: 0000000000000000 RSI: 000000000069e010 RDI: 0000000000000003
RBP: 000000000069e010 R08: 00007ffff7ddd320 R09: 0000000000000000
R10: 00007ffff7ddd320 R11: 0000000000000206 R12: 0000000000000003
R13: 00007fffffffef4b R14: 0000000000000000 R15: 0000000000000000
Code: <c7> 04 25 00 00 00 00 00 00 00 00 e8 b2 33 09 c1 31 c0 c3 0f 1f 44
RIP: myinit+0x18/0x30 [oops] RSP: ffffc900000d3cb0
CR2: 0000000000000000
---[ end trace 3cdb4e9d9842b503 ]---

To find the line that oopsed, look at the RIP register:

RIP: 0010:myinit+0x18/0x30 [oops]

and then on GDB:

./run-gdb

run

info line *(myinit+0x18)

which gives us the correct line:

Line 7 of "/root/linux-kernel-module-cheat/out/kernel_modules/x86_64/kernel_modules/panic.c" starts at address 0xbf00001c <myinit+28> and ends at 0xbf00002c <myexit>.

This-did not work on arm due to GDB step debug kernel module insmodded by init on ARM so we need to either:

The dump_stack function produces a stack trace much like panic and oops, but causes no problems and we return to the normal control flow, and can cleanly remove the module afterwards:

insmod dump_stack.ko

The WARN_ON macro basically just calls dump_stack.

One extra side effect is that we can make it also panic with:

echo 1 > /proc/sys/kernel/panic_on_warn
insmod warn_on.ko

Can also be activated with the panic_on_warn boot parameter.

Let’s learn how to diagnose problems with the root filesystem not being found. TODO add a sample panic error message for each error type:

This is the diagnosis procedure.

First, if we remove the following options from the our kernel build:

CONFIG_VIRTIO_BLK=y
CONFIG_VIRTIO_PCI=y

we get a message like this:

<4>[    0.541708] VFS: Cannot open root device "vda" or unknown-block(0,0): error -6
<4>[    0.542035] Please append a correct "root=" boot option; here are the available partitions:
<0>[    0.542562] Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0)

From the message, we notice that the kernel sees a disk of some sort (vda means a virtio disk), but it could not open it.

This means that the kernel cannot properly read any bytes from the disk.

And afterwards, it has an useless message here are the available partitions:, but of course we have no available partitions, the list is empty, because the kernel cannot even read bytes from the disk, so it definitely cannot understand its filesystems.

This can indicate basically two things:

  • on real hardware, it could mean that the hardware is broken. Kind of hard on emulators ;-)

  • you didn’t configure the kernel with the option that enables it to read from that kind of disk.

    In our case, disks are virtio devices that QEMU exposes to the guest kernel. This is why removing the options:

    CONFIG_VIRTIO_BLK=y
    CONFIG_VIRTIO_PCI=y

    led to this error.

Now, let’s restore the previously removed virtio options, and instead remove:

CONFIG_EXT4_FS=y

This time, the kernel will be able to read bytes from the device. But it won’t be able to read files from the filesystem, because our filesystem is in ext4 format.

Therefore, this time the error message looks like this:

<4>[    0.585296] List of all partitions:
<4>[    0.585913] fe00          524288 vda
<4>[    0.586123]  driver: virtio_blk
<4>[    0.586471] No filesystem could mount root, tried:
<4>[    0.586497]  squashfs
<4>[    0.586724]
<0>[    0.587360] Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(254,0)

In this case, we see that the kernel did manage to read from the vda disk! It even told us how: by using the driver: virtio_blk.

However, it then went through the list of all filesystem types it knows how to read files from, in our case just squashf, and none of those worked, because our partition is an ext4 partition.

Finally, the last possible error is that we simply passed the wrong root= kernel CLI option. For example, if we hack our command to pass:

root=/dev/vda2

which does not even exist since /dev/vda is a raw non-partitioned ext4 image, then boot fails with a message:

<4>[    0.608475] Please append a correct "root=" boot option; here are the available partitions:
<4>[    0.609563] fe00          524288 vda
<4>[    0.609723]  driver: virtio_blk
<0>[    0.610433] Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(254,2)

This one is easy, because the kernel tells us clearly which partitions it would have been able to understand. In our case /dev/vda.

Once all those problems are solved, in the working setup, we finally see something like:

<6>[    0.636129] EXT4-fs (vda): mounted filesystem with ordered data mode. Opts: (null)
<6>[    0.636700] VFS: Mounted root (ext4 filesystem) on device 254:0.

Tested on LKMC 863a373a30cd3c7982e3e453c4153f85133b17a9, Linux kernel 5.4.3.

Bibliography:

Pseudo filesystems are filesystems that don’t represent actual files in a hard disk, but rather allow us to do special operations on filesystem-related system calls.

What each pseudo-file does for each related system call does is defined by its File operations.

Bibliography:

Debugfs is the simplest pseudo filesystem to play around with:

./debugfs.sh
echo $?

Outcome: the test passes:

0

Sources:

Debugfs is made specifically to help test kernel stuff. Just mount, set File operations, and we are done.

For this reason, it is the filesystem that we use whenever possible in our tests.

debugfs.sh explicitly mounts a debugfs at a custom location, but the most common mount point is /sys/kernel/debug.

This mount not done automatically by the kernel however: we, like most distros, do it from userland with our fstab.

Debugfs support requires the kernel to be compiled with CONFIG_DEBUG_FS=y.

Only the more basic file operations can be implemented in debugfs, e.g. mmap never gets called:

Procfs is just another fops entry point:

./procfs.sh
echo $?

Outcome: the test passes:

0

Procfs is a little less convenient than debugfs, but is more used in serious applications.

Procfs can run all system calls, including ones that debugfs can’t, e.g. mmap.

Sources:

Bibliography:

Its data is shared with uname(), which is a POSIX C function and has a Linux syscall to back it up.

Where the data comes from and how to modify it:

In this repo, leaking host information, and to make builds more reproducible, we are setting:

  • user and date to dummy values with KBUILD_BUILD_USER and KBUILD_BUILD_TIMESTAMP

  • hostname to the kernel git commit with KBUILD_BUILD_HOST and KBUILD_BUILD_VERSION

A sample result is:

Linux version 4.19.0-dirty (lkmc@84df9525b0c27f3ebc2ebb1864fa62a97fdedb7d) (gcc version 6.4.0 (Buildroot 2018.05-00002-gbc60382b8f)) #1 SMP Thu Jan 1 00:00:00 UTC 1970

Sysfs is more restricted than procfs, as it does not take an arbitrary file_operations:

./sysfs.sh
echo $?

Outcome: the test passes:

0

Sources:

Vs procfs:

You basically can only do open, close, read, write, and lseek on sysfs files.

It is similar to a seq_file file operation, except that write is also implemented.

TODO: what are those kobject structs? Make a more complex example that shows what they can do.

Bibliography:

Character devices can have arbitrary File operations associated to them:

./character_device.sh
echo $?

Outcome: the test passes:

0

Sources:

Unlike procfs entires, character device files are created with userland mknod or mknodat syscalls:

mknod </dev/path_to_dev> c <major> <minor>

Intuitively, for physical devices like keyboards, the major number maps to which driver, and the minor number maps to which device it is.

A single driver can drive multiple compatible devices.

The major and minor numbers can be observed with:

ls -l /dev/urandom

Output:

crw-rw-rw-    1 root     root        1,   9 Jun 29 05:45 /dev/urandom

which means:

  • c (first letter): this is a character device. Would be b for a block device.

  • 1, 9: the major number is 1, and the minor 9

To avoid device number conflicts when registering the driver we:

  • ask the kernel to allocate a free major number for us with: register_chrdev(0

  • find ouf which number was assigned by grepping /proc/devices for the kernel module name

File operations are the main method of userland driver communication.

struct file_operations determines what the kernel will do on filesystem system calls of Pseudo filesystems.

This example illustrates the most basic system calls: open, read, write, close and lseek:

./fops.sh
echo $?

Outcome: the test passes:

0

Sources:

Then give this a try:

sh -x ./fops.sh

We have put printks on each fop, so this allows you to see which system calls are being made for each command.

Writing trivial read File operations is repetitive and error prone. The seq_file API makes the process much easier for those trivial cases:

./seq_file.sh
echo $?

Outcome: the test passes:

0

Sources:

In this example we create a debugfs file that behaves just like a file that contains:

0
1
2

However, we only store a single integer in memory and calculate the file on the fly in an iterator fashion.

Bibliography:

If you have the entire read output upfront, single_open is an even more convenient version of seq_file:

./seq_file.sh
echo $?

Outcome: the test passes:

0

Sources:

This example produces a debugfs file that behaves like a file that contains:

ab
cd

The poll system call allows an user process to do a non-busy wait on a kernel event.

Sources:

Example:

./poll.sh

Outcome: jiffies gets printed to stdout every second from userland, e.g.:

poll
<6>[    4.275305] poll
<6>[    4.275580] return POLLIN
revents = 1
POLLIN n=10 buf=4294893337
poll
<6>[    4.276627] poll
<6>[    4.276911] return 0
<6>[    5.271193] wake_up
<6>[    5.272326] poll
<6>[    5.273207] return POLLIN
revents = 1
POLLIN n=10 buf=4294893588
poll
<6>[    5.276367] poll
<6>[    5.276618] return 0
<6>[    6.275178] wake_up
<6>[    6.276370] poll
<6>[    6.277269] return POLLIN
revents = 1
POLLIN n=10 buf=4294893839

Force the poll file_operation to return 0 to see what happens more clearly:

./poll.sh pol0=1

Sample output:

poll
<6>[   85.674801] poll
<6>[   85.675788] return 0
<6>[   86.675182] wake_up
<6>[   86.676431] poll
<6>[   86.677373] return 0
<6>[   87.679198] wake_up
<6>[   87.680515] poll
<6>[   87.681564] return 0
<6>[   88.683198] wake_up

From this we see that control is not returned to userland: the kernel just keeps calling the poll file_operation again and again.

Typically, we are waiting for some hardware to make some piece of data available available to the kernel.

The hardware notifies the kernel that the data is ready with an interrupt.

To simplify this example, we just fake the hardware interrupts with a kthread that sleeps for a second in an infinite loop.

Bibliography:

The ioctl system call is the best way to pass an arbitrary number of parameters to the kernel in a single go:

./ioctl.sh
echo $?

Outcome: the test passes:

0

Sources:

ioctl is one of the most important methods of communication with real device drivers, which often take several fields as input.

ioctl takes as input:

  • an integer request : it usually identifies what type of operation we want to do on this call

  • an untyped pointer to memory: can be anything, but is typically a pointer to a struct

    The type of the struct often depends on the request input

    This struct is defined on a uapi-style C header that is used both to compile the kernel module and the userland executable.

    The fields of this struct can be thought of as arbitrary input parameters.

And the output is:

  • an integer return value. man ioctl documents:

    Usually, on success zero is returned. A few ioctl() requests use the return value as an output parameter and return a nonnegative value on success. On error, -1 is returned, and errno is set appropriately.

  • the input pointer data may be overwritten to contain arbitrary output

Bibliography:

The mmap system call allows us to share memory between user and kernel space without copying:

./mmap.sh
echo $?

Outcome: the test passes:

0

Sources:

In this example, we make a tiny 4 byte kernel buffer available to user-space, and we then modify it on userspace, and check that the kernel can see the modification.

mmap, like most more complex File operations, does not work with debugfs as of 4.9, so we use a procfs file for it.

Bibliography:

Anonymous inodes allow getting multiple file descriptors from a single filesystem entry, which reduces namespace pollution compared to creating multiple device files:

./anonymous_inode.sh
echo $?

Outcome: the test passes:

0

Sources:

This example gets an anonymous inode via ioctl from a debugfs entry by using anon_inode_getfd.

Reads to that inode return the sequence: 1, 10, 100, …​ 10000000, 1, 100, …​

Netlink sockets offer a socket API for kernel / userland communication:

./netlink.sh
echo $?

Outcome: the test passes:

0

Sources:

Launch multiple user requests in parallel to stress our socket:

insmod netlink.ko sleep=1
for i in `seq 16`; do ./netlink.out & done

Bibliography:

Kernel threads are managed exactly like userland threads; they also have a backing task_struct, and are scheduled with the same mechanism:

insmod kthread.ko

Outcome: dmesg counts from 0 to 9 once every second infinitely many times:

0
1
2
...
8
9
0
1
2
...

The count stops when we rmmod:

rmmod kthread

The sleep is done with usleep_range, see: Section 17.9.2, “sleep”.

Bibliography:

Let’s launch two threads and see if they actually run in parallel:

insmod kthreads.ko

Outcome: two threads count to dmesg from 0 to 9 in parallel.

Each line has output of form:

<thread_id> <count>

Possible very likely outcome:

1 0
2 0
1 1
2 1
1 2
2 2
1 3
2 3

The threads almost always interleaved nicely, thus confirming that they are actually running in parallel.

Count to dmesg every one second from 0 up to n - 1:

insmod sleep.ko n=5

The sleep is done with a call to usleep_range directly inside module_init for simplicity.

Bibliography:

A more convenient front-end for kthread:

insmod workqueue_cheat.ko

Outcome: count from 0 to 9 infinitely many times

Stop counting:

rmmod workqueue_cheat

The workqueue thread is killed after the worker function returns.

We can’t call the module just workqueue.c because there is already a built-in with that name: https://unix.stackexchange.com/questions/364956/how-can-insmod-fail-with-kernel-module-is-already-loaded-even-is-lsmod-does-not

Count from 0 to 9 every second infinitely many times by scheduling a new work item from a work item:

insmod work_from_work.ko

Stop:

rmmod work_from_work

The sleep is done indirectly through: queue_delayed_work, which waits the specified time before scheduling the work.

Let’s block the entire kernel! Yay:

./run --eval-after 'dmesg -n 1;insmod schedule.ko schedule=0'

Outcome: the system hangs, the only way out is to kill the VM.

kthreads only allow interrupting if you call schedule(), and the schedule=0 kernel module parameter turns it off.

Sleep functions like usleep_range also end up calling schedule.

If we allow schedule() to be called, then the system becomes responsive:

./run --eval-after 'dmesg -n 1;insmod schedule.ko schedule=1'

and we can observe the counting with:

dmesg -w

The system also responds if we add another core:

./run --cpus 2 --eval-after 'dmesg -n 1;insmod schedule.ko schedule=0'

Wait queues are a way to make a thread sleep until an event happens on the queue:

insmod wait_queue.c

Dmesg output:

0 0
1 0
2 0
# Wait one second.
0 1
1 1
2 1
# Wait one second.
0 2
1 2
2 2
...

Stop the count:

rmmod wait_queue

This example launches three threads:

  • one thread generates events every with wake_up

  • the other two threads wait for that with wait_event, and print a dmesg when it happens.

    The wait_event macro works a bit like:

    while (!cond)
        sleep_until_event

Count from 0 to 9 infinitely many times in 1 second intervals using timers:

insmod timer.ko

Stop counting:

rmmod timer

Timers are callbacks that run when an interrupt happens, from the interrupt context itself.

Therefore they produce more accurate timing than thread scheduling, which is more complex, but you can’t do too much work inside of them.

Bibliography:

Brute force monitor every shared interrupt that will accept us:

./run --eval-after 'insmod irq.ko' --graphic

Now try the following:

  • press a keyboard key and then release it after a few seconds

  • press a mouse key, and release it after a few seconds

  • move the mouse around

Outcome: dmesg shows which IRQ was fired for each action through messages of type:

handler irq = 1 dev = 250

dev is the character device for the module and never changes, as can be confirmed by:

grep lkmc_irq /proc/devices

The IRQs that we observe are:

  • 1 for keyboard press and release.

    If you hold the key down for a while, it starts firing at a constant rate. So this happens at the hardware level!

  • 12 mouse actions

This only works if for IRQs for which the other handlers are registered as IRQF_SHARED.

We can see which ones are those, either via dmesg messages of type:

genirq: Flags mismatch irq 0. 00000080 (myirqhandler0) vs. 00015a00 (timer)
request_irq irq = 0 ret = -16
request_irq irq = 1 ret = 0

which indicate that 0 is not, but 1 is, or with:

cat /proc/interrupts

which shows:

  0:         31   IO-APIC   2-edge      timer
  1:          9   IO-APIC   1-edge      i8042, myirqhandler0

so only 1 has myirqhandler0 attached but not 0.

The QEMU monitor also has some interrupt statistics for x86_64:

./qemu-monitor info irq

TODO: properly understand how each IRQ maps to what number.

The Linux kernel v4.16 mainline also has a dummy-irq module at drivers/misc/dummy-irq.c for monitoring a single IRQ.

We build it by default with:

CONFIG_DUMMY_IRQ=m

And then you can do

./run --graphic

and in guest:

modprobe dummy-irq irq=1

Outcome: when you click a key on the keyboard, dmesg shows:

dummy-irq: interrupt occurred on IRQ 1

However, this module is intended to fire only once as can be seen from its source:

    static int count = 0;

    if (count == 0) {
        printk(KERN_INFO "dummy-irq: interrupt occurred on IRQ %d\n",
            irq);
        count++;
    }

and furthermore interrupt 1 and 12 happen immediately TODO why, were they somehow pending?

In the guest with QEMU graphic mode:

watch -n 1 cat /proc/interrupts

Then see how clicking the mouse and keyboard affect the interrupt counts.

This confirms that:

  • 1: keyboard

  • 12: mouse click and drags

The module also shows which handlers are registered for each IRQ, as we have observed at irq.ko

When in text mode, we can also observe interrupt line 4 with handler ttyS0 increase continuously as IO goes through the UART.

Convert a virtual address to physical:

insmod virt_to_phys.ko
cat /sys/kernel/debug/lkmc_virt_to_phys

Sample output:

*kmalloc_ptr = 0x12345678
kmalloc_ptr = ffff88000e169ae8
virt_to_phys(kmalloc_ptr) = 0xe169ae8
static_var = 0x12345678
&static_var = ffffffffc0002308
virt_to_phys(&static_var) = 0x40002308

We can confirm that the kmalloc_ptr translation worked with:

./qemu-monitor 'xp 0xe169ae8'

which reads four bytes from a given physical address, and gives the expected:

000000000e169ae8: 0x12345678

TODO it only works for kmalloc however, for the static variable:

./qemu-monitor 'xp 0x40002308'

it gave a wrong value of 00000000.

Bibliography:

Only tested in x86_64.

The Linux kernel exposes physical addresses to userland through:

  • /proc/<pid>/maps

  • /proc/<pid>/pagemap

  • /dev/mem

In this section we will play with them.

The following files contain examples to access that data and test it out:

First get a virtual address to play with:

./posix/virt_to_phys_test.out &

Sample output:

vaddr 0x600800
pid 110

The program:

  • allocates a volatile variable and sets is value to 0x12345678

  • prints the virtual address of the variable, and the program PID

  • runs a while loop until until the value of the variable gets mysteriously changed somehow, e.g. by nasty tinkerers like us

Then, translate the virtual address to physical using /proc/<pid>/maps and /proc/<pid>/pagemap:

./linux/virt_to_phys_user.out 110 0x600800

Sample output physical address:

0x7c7b800

Now we can verify that linux/virt_to_phys_user.out gave the correct physical address in the following ways:

Bibliography:

The xp QEMU monitor command reads memory at a given physical address.

First launch linux/virt_to_phys_user.out as described at Userland physical address experiments.

On a second terminal, use QEMU to read the physical address:

./qemu-monitor 'xp 0x7c7b800'

Output:

0000000007c7b800: 0x12345678

Yes!!! We read the correct value from the physical address.

We could not find however to write to memory from the QEMU monitor, boring.

/dev/mem exposes access to physical addresses, and we use it through the convenient devmem BusyBox utility.

First launch linux/virt_to_phys_user.out as described at Userland physical address experiments.

Next, read from the physical address:

devmem 0x7c7b800

Possible output:

Memory mapped at address 0x7ff7dbe01000.
Value at address 0X7C7B800 (0x7ff7dbe01800): 0x12345678

which shows that the physical memory contains the expected value 0x12345678.

0x7ff7dbe01000 is a new virtual address that devmem maps to the physical address to be able to read from it.

Modify the physical memory:

devmem 0x7c7b800 w 0x9abcdef0

After one second, we see on the screen:

i 9abcdef0
[1]+  Done                       ./posix/virt_to_phys_test.out

so the value changed, and the while loop exited!

This example requires:

  • CONFIG_STRICT_DEVMEM=n, otherwise devmem fails with:

    devmem: mmap: Operation not permitted
  • nopat kernel parameter

which we set by default.

Dump the physical address of all pages mapped to a given process using /proc/<pid>/maps and /proc/<pid>/pagemap.

First launch linux/virt_to_phys_user.out as described at Userland physical address experiments. Suppose that the output was:

# ./posix/virt_to_phys_test.out &
vaddr 0x601048
pid 63
# ./linux/virt_to_phys_user.out 63 0x601048
0x1a61048

Now obtain the page map for the process:

./linux/pagemap_dump.out 63

Sample output excerpt:

vaddr pfn soft-dirty file/shared swapped present library
400000 1ede 0 1 0 1 ./posix/virt_to_phys_test.out
600000 1a6f 0 0 0 1 ./posix/virt_to_phys_test.out
601000 1a61 0 0 0 1 ./posix/virt_to_phys_test.out
602000 2208 0 0 0 1 [heap]
603000 220b 0 0 0 1 [heap]
7ffff78ec000 1fd4 0 1 0 1 /lib/libuClibc-1.0.30.so

Source:

Meaning of the flags:

  • vaddr: first virtual address of a page the belongs to the process. Notably:

    ./run-toolchain readelf -- -l "$(./getvar userland_build_dir)/posix/virt_to_phys_test.out"

    contains:

      Type           Offset             VirtAddr           PhysAddr
                     FileSiz            MemSiz              Flags  Align
    ...
      LOAD           0x0000000000000000 0x0000000000400000 0x0000000000400000
                     0x000000000000075c 0x000000000000075c  R E    0x200000
      LOAD           0x0000000000000e98 0x0000000000600e98 0x0000000000600e98
                     0x00000000000001b4 0x0000000000000218  RW     0x200000
    
     Section to Segment mapping:
      Segment Sections...
    ...
       02     .interp .hash .dynsym .dynstr .rela.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame
       03     .ctors .dtors .jcr .dynamic .got.plt .data .bss

    from which we deduce that:

    • 400000 is the text segment

    • 600000 is the data segment

  • pfn: add three zeroes to it, and you have the physical address.

    Three zeroes is 12 bits which is 4kB, which is the size of a page.

    For example, the virtual address 0x601000 has pfn of 0x1a61, which means that its physical address is 0x1a61000

    This is consistent with what linux/virt_to_phys_user.out told us: the virtual address 0x601048 has physical address 0x1a61048.

    048 corresponds to the three last zeroes, and is the offset within the page.

    Also, this value falls inside 0x601000, which as previously analyzed is the data section, which is the normal location for global variables such as ours.

  • soft-dirty: TODO

  • file/shared: TODO. 1 seems to indicate that the page can be shared across processes, possibly for read-only pages? E.g. the text segment has 1, but the data has 0.

  • swapped: TODO swapped to disk?

  • present: TODO vs swapped?

  • library: which executable owns that page

This program works in two steps:

  • parse the human readable lines lines from /proc/<pid>/maps. This files contains lines of form:

    7ffff7b6d000-7ffff7bdd000 r-xp 00000000 fe:00 658                        /lib/libuClibc-1.0.22.so

    which tells us that:

    • 7f8af99f8000-7f8af99ff000 is a virtual address range that belong to the process, possibly containing multiple pages.

    • /lib/libuClibc-1.0.22.so is the name of the library that owns that memory

  • loop over each page of each address range, and ask /proc/<pid>/pagemap for more information about that page, including the physical address

Good overviews:

I hope to have examples of all methods some day, since I’m obsessed with visibility.

Logs proc events such as process creation to a netlink socket.

We then have a userland program that listens to the events and prints them out:

# ./linux/proc_events.out &
# set mcast listen ok
# sleep 2 & sleep 1
fork: parent tid=48 pid=48 -> child tid=79 pid=79
fork: parent tid=48 pid=48 -> child tid=80 pid=80
exec: tid=80 pid=80
exec: tid=79 pid=79
# exit: tid=80 pid=80 exit_code=0
exit: tid=79 pid=79 exit_code=0
echo a
a
#

TODO: why exit: tid=79 shows after exit: tid=80?

Note how echo a is a Bash built-in, and therefore does not spawn a new process.

TODO: why does this produce no output?

./linux/proc_events.out >f &

TODO can you get process data such as UID and process arguments? It seems not since exec_proc_event contains so little data: https://github.com/torvalds/linux/blob/v4.16/include/uapi/linux/cn_proc.h#L80 We could try to immediately read it from /proc, but there is a risk that the process finished and another one took its PID, so it wouldn’t be reliable.

0111ca406bdfa6fd65a2605d353583b4c4051781 was failing with:

>>> kernel_modules 1.0 Building
/usr/bin/make -j8 -C '/linux-kernel-module-cheat//out/aarch64/buildroot/build/kernel_modules-1.0/user' BR2_PACKAGE_OPENBLAS="" CC="/linux-kernel-module-cheat//out/aarch64/buildroot/host/bin/aarch64-buildroot-linux-uclibc-gcc" LD="/linux-kernel-module-cheat//out/aarch64/buildroot/host/bin/aarch64-buildroot-linux-uclibc-ld"
/linux-kernel-module-cheat//out/aarch64/buildroot/host/bin/aarch64-buildroot-linux-uclibc-gcc  -ggdb3 -fopenmp -O0 -std=c99 -Wall -Werror -Wextra -o 'proc_events.out' 'proc_events.c'
In file included from /linux-kernel-module-cheat//out/aarch64/buildroot/host/aarch64-buildroot-linux-uclibc/sysroot/usr/include/signal.h:329:0,
                 from proc_events.c:12:
/linux-kernel-module-cheat//out/aarch64/buildroot/host/aarch64-buildroot-linux-uclibc/sysroot/usr/include/sys/ucontext.h:50:16: error: field ‘uc_mcontext’ has incomplete type
     mcontext_t uc_mcontext;
                ^~~~~~~~~~~

so we commented it out.

Related threads:

If we try to naively update uclibc to 1.0.29 with buildroot_override, which contains the above mentioned patch, clean aarch64 test build fails with:

../utils/ldd.c: In function 'elf_find_dynamic':
../utils/ldd.c:238:12: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
     return (void *)byteswap_to_host(dynp->d_un.d_val);
            ^
/tmp/user/20321/cciGScKB.o: In function `process_line_callback':
msgmerge.c:(.text+0x22): undefined reference to `escape'
/tmp/user/20321/cciGScKB.o: In function `process':
msgmerge.c:(.text+0xf6): undefined reference to `poparser_init'
msgmerge.c:(.text+0x11e): undefined reference to `poparser_feed_line'
msgmerge.c:(.text+0x128): undefined reference to `poparser_finish'
collect2: error: ld returned 1 exit status
Makefile.in:120: recipe for target '../utils/msgmerge.host' failed
make[2]: *** [../utils/msgmerge.host] Error 1
make[2]: *** Waiting for unfinished jobs....
/tmp/user/20321/ccF8V8jF.o: In function `process':
msgfmt.c:(.text+0xbf3): undefined reference to `poparser_init'
msgfmt.c:(.text+0xc1f): undefined reference to `poparser_feed_line'
msgfmt.c:(.text+0xc2b): undefined reference to `poparser_finish'
collect2: error: ld returned 1 exit status
Makefile.in:120: recipe for target '../utils/msgfmt.host' failed
make[2]: *** [../utils/msgfmt.host] Error 1
package/pkg-generic.mk:227: recipe for target '/data/git/linux-kernel-module-cheat/out/aarch64/buildroot/build/uclibc-custom/.stamp_built' failed
make[1]: *** [/data/git/linux-kernel-module-cheat/out/aarch64/buildroot/build/uclibc-custom/.stamp_built] Error 2
Makefile:79: recipe for target '_all' failed
make: *** [_all] Error 2

Buildroot master has already moved to uclibc 1.0.29 at f8546e836784c17aa26970f6345db9d515411700, but it is not yet in any tag…​ so I’m not tempted to update it yet just for this.

Trace a single function:

cd /sys/kernel/debug/tracing/

# Stop tracing.
echo 0 > tracing_on

# Clear previous trace.
echo > trace

# List the available tracers, and pick one.
cat available_tracers
echo function > current_tracer

# List all functions that can be traced
# cat available_filter_functions
# Choose one.
echo __kmalloc > set_ftrace_filter
# Confirm that only __kmalloc is enabled.
cat enabled_functions

echo 1 > tracing_on

# Latest events.
head trace

# Observe trace continuously, and drain seen events out.
cat trace_pipe &

Sample output:

# tracer: function
#
# entries-in-buffer/entries-written: 97/97   #P:1
#
#                              _-----=> irqs-off
#                             / _----=> need-resched
#                            | / _---=> hardirq/softirq
#                            || / _--=> preempt-depth
#                            ||| /     delay
#           TASK-PID   CPU#  ||||    TIMESTAMP  FUNCTION
#              | |       |   ||||       |         |
            head-228   [000] ....   825.534637: __kmalloc <-load_elf_phdrs
            head-228   [000] ....   825.534692: __kmalloc <-load_elf_binary
            head-228   [000] ....   825.534815: __kmalloc <-load_elf_phdrs
            head-228   [000] ....   825.550917: __kmalloc <-__seq_open_private
            head-228   [000] ....   825.550953: __kmalloc <-tracing_open
            head-229   [000] ....   826.756585: __kmalloc <-load_elf_phdrs
            head-229   [000] ....   826.756627: __kmalloc <-load_elf_binary
            head-229   [000] ....   826.756719: __kmalloc <-load_elf_phdrs
            head-229   [000] ....   826.773796: __kmalloc <-__seq_open_private
            head-229   [000] ....   826.773835: __kmalloc <-tracing_open
            head-230   [000] ....   827.174988: __kmalloc <-load_elf_phdrs
            head-230   [000] ....   827.175046: __kmalloc <-load_elf_binary
            head-230   [000] ....   827.175171: __kmalloc <-load_elf_phdrs

Trace all possible functions, and draw a call graph:

echo 1 > max_graph_depth
echo 1 > events/enable
echo function_graph > current_tracer

Sample output:

# CPU  DURATION                  FUNCTION CALLS
# |     |   |                     |   |   |   |
 0)   2.173 us    |                  } /* ntp_tick_length */
 0)               |                  timekeeping_update() {
 0)   4.176 us    |                    ntp_get_next_leap();
 0)   5.016 us    |                    update_vsyscall();
 0)               |                    raw_notifier_call_chain() {
 0)   2.241 us    |                      notifier_call_chain();
 0) + 19.879 us   |                    }
 0)   3.144 us    |                    update_fast_timekeeper();
 0)   2.738 us    |                    update_fast_timekeeper();
 0) ! 117.147 us  |                  }
 0)               |                  _raw_spin_unlock_irqrestore() {
 0)   4.045 us    |                    _raw_write_unlock_irqrestore();
 0) + 22.066 us   |                  }
 0) ! 265.278 us  |                } /* update_wall_time */

TODO: what do + and ! mean?

Each enable under the events/ tree enables a certain set of functions, the higher the enable more functions are enabled.

TODO example:

./build-buildroot --config 'BR2_PACKAGE_TRACE_CMD=y'

kprobes is an instrumentation mechanism that injects arbitrary code at a given address in a trap instruction, much like GDB. Oh, the good old kernel. :-)

./build-linux --config 'CONFIG_KPROBES=y'

Then on guest:

insmod kprobe_example.ko
sleep 4 & sleep 4 &'

Outcome: dmesg outputs on every fork:

<_do_fork> pre_handler: p->addr = 0x00000000e1360063, ip = ffffffff810531d1, flags = 0x246
<_do_fork> post_handler: p->addr = 0x00000000e1360063, flags = 0x246
<_do_fork> pre_handler: p->addr = 0x00000000e1360063, ip = ffffffff810531d1, flags = 0x246
<_do_fork> post_handler: p->addr = 0x00000000e1360063, flags = 0x246

TODO: it does not work if I try to immediately launch sleep, why?

insmod kprobe_example.ko
sleep 4 & sleep 4 &

I don’t think your code can refer to the surrounding kernel code however: the only visible thing is the value of the registers.

You can then hack it up to read the stack and read argument values, but do you really want to?

There is also a kprobes + ftrace based mechanism with CONFIG_KPROBE_EVENTS=y which does read the memory for us based on format strings that indicate type…​ https://github.com/torvalds/linux/blob/v4.16/Documentation/trace/kprobetrace.txt Horrendous. Used by: https://github.com/brendangregg/perf-tools/blob/98d42a2a1493d2d1c651a5c396e015d4f082eb20/execsnoop

Bibliography:

TODO: didn’t port during refactor after 3b0a343647bed577586989fb702b760bd280844a. Reimplementing should not be hard.

Results (boot not excluded) are shown at: Table 1, “Boot instruction counts for various setups”

Table 1. Boot instruction counts for various setups
Commit Arch Simulator Instruction count

7228f75ac74c896417fb8c5ba3d375a14ed4d36b

arm

QEMU

680k

7228f75ac74c896417fb8c5ba3d375a14ed4d36b

arm

gem5 AtomicSimpleCPU

160M

7228f75ac74c896417fb8c5ba3d375a14ed4d36b

arm

gem5 HPI

155M

7228f75ac74c896417fb8c5ba3d375a14ed4d36b

x86_64

QEMU

3M

7228f75ac74c896417fb8c5ba3d375a14ed4d36b

x86_64

gem5 AtomicSimpleCPU

528M

QEMU:

./trace-boot --arch x86_64

sample output:

instructions 1833863
entry_address 0x1000000
instructions_firmware 20708

gem5:

./run --arch aarch64 --emulator gem5 --eval 'm5 exit'
# Or:
# ./run --arch aarch64 --emulator gem5 --eval 'm5 exit' -- --cpu-type=HPI --caches
./gem5-stat --arch aarch64 sim_insts

Notes:

  • 0x1000000 is the address where QEMU puts the Linux kernel at with -kernel in x86.

    It can be found from:

    ./run-toolchain readelf -- -e "$(./getvar vmlinux)" | grep Entry

    TODO confirm further. If I try to break there with:

    ./run-gdb *0x1000000

    but I have no corresponding source line. Also note that this line is not actually the first line, since the kernel messages such as early console in extract_kernel have already shown on screen at that point. This does not break at all:

    ./run-gdb extract_kernel

    It only appears once on every log I’ve seen so far, checked with grep 0x1000000 trace.txt

    Then when we count the instructions that run before the kernel entry point, there is only about 100k instructions, which is insignificant compared to the kernel boot itself.

    TODO --arch arm and --arch aarch64 does not count firmware instructions properly because the entry point address of the ELF file (ffffff8008080000 for aarch64) does not show up on the trace at all. Tested on f8c0502bb2680f2dbe7c1f3d7958f60265347005.

  • We can also discount the instructions after init runs by using readelf to get the initial address of init. One easy way to do that now is to just run:

    ./run-gdb --userland "$(./getvar userland_build_dir)/linux/poweroff.out" main

    And get that from the traces, e.g. if the address is 4003a0, then we search:

    grep -n 4003a0 trace.txt

    I have observed a single match for that instruction, so it must be the init, and there were only 20k instructions after it, so the impact is negligible.

  • to disable networking. Is replacing init enough?

    CONFIG_NET=n did not significantly reduce instruction counts, so maybe replacing init is enough.

  • gem5 simulates memory latencies. So I think that the CPU loops idle while waiting for memory, and counts will be higher.

Make it harder to get hacked and easier to notice that you were, at the cost of some (small?) runtime overhead.

Detects buffer overflows for us:

./build-linux --config 'CONFIG_FORTIFY_SOURCE=y' --linux-build-id fortify
./build-modules --clean
./build-modules
./build-buildroot
./run --eval-after 'insmod strlen_overflow.ko' --linux-build-id fortify

Possible dmesg output:

strlen_overflow: loading out-of-tree module taints kernel.
detected buffer overflow in strlen
------------[ cut here ]------------

followed by a trace.

You may not get this error because this depends on strlen overflowing at least until the next page: if a random \0 appears soon enough, it won’t blow up as desired.

TODO not always reproducible. Find a more reproducible failure. I could not observe it on:

insmod memcpy_overflow.ko

TODO get a hello world permission control working:

./build-linux \
  --config-fragment linux_config/selinux \
  --linux-build-id selinux \
;
./build-buildroot --config 'BR2_PACKAGE_REFPOLICY=y'
./run --enable-kvm --linux-build-id selinux

This builds:

After boot finishes, we see:

Starting auditd: mkdir: invalid option -- 'Z'

which comes from /etc/init.d/S01auditd, because BusyBox' mkdir does not have the crazy -Z option like Ubuntu. That’s amazing!

The kernel logs contain:

SELinux:  Initializing.

Inside the guest we now have:

getenforce

which initially says:

Disabled

TODO: if we try to enforce:

setenforce 1

it does not work and outputs:

setenforce: SELinux is disabled

SELinux requires glibc as mentioned at: [libc-choice].

But in part because it is dying, I didn’t spend much effort to integrate it into this repo, although it would be a good fit in principle, since it is essentially a virtualization method.

Maybe some brave soul will send a pull request one day.

UIO is a kernel subsystem that allows to do certain types of driver operations from userland.

This would be awesome to improve debuggability and safety of kernel modules.

VFIO looks like a newer and better UIO replacement, but there do not exist any examples of how to use it: https://stackoverflow.com/questions/49309162/interfacing-with-qemu-edu-device-via-userspace-i-o-uio-linux-driver

TODO get something interesting working. I currently don’t understand the behaviour very well.

TODO how to ACK interrupts? How to ensure that every interrupt gets handled separately?

TODO how to write to registers. Currently using /dev/mem and lspci.

This example should handle interrupts from userland and print a message to stdout:

./uio_read.sh

TODO: what is the expected behaviour? I should have documented this when I wrote this stuff, and I’m that lazy right now that I’m in the middle of a refactor :-)

UIO interface in a nutshell:

  • blocking read / poll: waits until interrupts

  • write: call irqcontrol callback. Default: 0 or 1 to enable / disable interrupts.

  • mmap: access device memory

Sources:

Bibliography:

Requires Graphics.

You can also try those on the Ctrl-Alt-F3 of your Ubuntu host, but it is much more fun inside a VM!

Stop the cursor from blinking:

echo 0 > /sys/class/graphics/fbcon/cursor_blink
echo 1 > /sys/class/graphics/fbcon/rotate

Relies on: CONFIG_FRAMEBUFFER_CONSOLE_ROTATION=y.

Documented under: Documentation/fb/.

TODO: font and keymap. Mentioned at: https://cmcenroe.me/2017/05/05/linux-console.html and I think can be done with BusyBox loadkmap and loadfont, we just have to understand their formats, related:

Requires Graphics.

Let’s have some fun.

I think most are implemented under:

drivers/tty

TODO find all.

Scroll up / down the terminal:

Shift-PgDown
Shift-PgUp

Or inside ./qemu-monitor:

sendkey shift-pgup
sendkey shift-pgdown

If you run in QEMU graphic mode:

./run --graphic

and then from the graphic window you enter the keys:

Ctrl-Alt-Del

then this runs the following command on the guest:

/sbin/reboot

This is enabled from our rootfs_overlay/etc/inittab:

::ctrlaltdel:/sbin/reboot

This leads Linux to try to reboot, and QEMU shutdowns due to the -no-reboot option which we set by default for, see: Section 17.6.1.3, “Exit emulator on panic”.

Here is a minimal example of Ctrl Alt Del:

./run --kernel-cli 'init=/lkmc/linux/ctrl_alt_del.out' --graphic

When you hit Ctrl-Alt-Del in the guest, our tiny init handles a SIGINT sent by the kernel and outputs to stdout:

cad

To map between man 2 reboot and the uClibc RB_* magic constants see:

less "$(./getvar buildroot_build_build_dir)"/uclibc-*/include/sys/reboot.h"

The procfs mechanism is documented at:

less linux/Documentation/sysctl/kernel.txt

which says:

When the value in this file is 0, ctrl-alt-del is trapped and
sent to the init(1) program to handle a graceful restart.
When, however, the value is > 0, Linux's reaction to a Vulcan
Nerve Pinch (tm) will be an immediate reboot, without even
syncing its dirty buffers.

Note: when a program (like dosemu) has the keyboard in 'raw'
mode, the ctrl-alt-del is intercepted by the program before it
ever reaches the kernel tty layer, and it's up to the program
to decide what to do with it.

Under the hood, behaviour is controlled by the reboot syscall:

man 2 reboot

reboot system calls can set either of the these behaviours for Ctrl-Alt-Del:

  • do a hard shutdown syscall. Set in uClibc C code with:

    reboot(RB_ENABLE_CAD)

    or from procfs with:

    echo 1 > /proc/sys/kernel/ctrl-alt-del

    Done by BusyBox' reboot -f.

  • send a SIGINT to the init process. This is what BusyBox' init does, and it then execs the string set in inittab.

    Set in uclibc C code with:

    reboot(RB_DISABLE_CAD)

    or from procfs with:

    echo 0 > /proc/sys/kernel/ctrl-alt-del

    Done by BusyBox' reboot.

When a BusyBox init is with the signal, it prints the following lines:

The system is going down NOW!
Sent SIGTERM to all processes
Sent SIGKILL to all processes
Requesting system reboot

On busybox-1.29.2’s init at init/init.c we see how the kill signals are sent:

static void run_shutdown_and_kill_processes(void)
{
	/* Run everything to be run at "shutdown".  This is done _prior_
	 * to killing everything, in case people wish to use scripts to
	 * shut things down gracefully... */
	run_actions(SHUTDOWN);

	message(L_CONSOLE | L_LOG, "The system is going down NOW!");

	/* Send signals to every process _except_ pid 1 */
	kill(-1, SIGTERM);
	message(L_CONSOLE, "Sent SIG%s to all processes", "TERM");
	sync();
	sleep(1);

	kill(-1, SIGKILL);
	message(L_CONSOLE, "Sent SIG%s to all processes", "KILL");
	sync();
	/*sleep(1); - callers take care about making a pause */
}

and run_shutdown_and_kill_processes is called from:

/* The SIGPWR/SIGUSR[12]/SIGTERM handler */
static void halt_reboot_pwoff(int sig) NORETURN;
static void halt_reboot_pwoff(int sig)

which also prints the final line:

	message(L_CONSOLE, "Requesting system %s", m);

which is set as the signal handler via TODO.

Bibliography:

We cannot test these actual shortcuts on QEMU since the host captures them at a lower level, but from:

./qemu-monitor

we can for example crash the system with:

sendkey alt-sysrq-c

Same but boring because no magic key:

echo c > /proc/sysrq-trigger

Implemented in:

drivers/tty/sysrq.c

On your host, on modern systems that don’t have the SysRq key you can do:

Alt-PrtSc-space

which prints a message to dmesg of type:

sysrq: SysRq : HELP : loglevel(0-9) reboot(b) crash(c) terminate-all-tasks(e) memory-full-oom-kill(f) kill-all-tasks(i) thaw-filesystems(j) sak(k) show-backtrace-all-active-cpus(l) show-memory-usage(m) nice-all-RT-tasks(n) poweroff(o) show-registers(p) show-all-timers(q) unraw(r) sync(s) show-task-states(t) unmount(u) show-blocked-tasks(w) dump-ftrace-buffer(z)

Individual SysRq can be enabled or disabled with the bitmask:

/proc/sys/kernel/sysrq

The bitmask is documented at:

less linux/Documentation/admin-guide/sysrq.rst

In order to play with TTYs, do this:

printf '
tty2::respawn:/sbin/getty -n -L -l /lkmc/loginroot.sh tty2 0 vt100
tty3::respawn:-/bin/sh
tty4::respawn:/sbin/getty 0 tty4
tty63::respawn:-/bin/sh
::respawn:/sbin/getty -L ttyS0 0 vt100
::respawn:/sbin/getty -L ttyS1 0 vt100
::respawn:/sbin/getty -L ttyS2 0 vt100
# Leave one serial empty.
#::respawn:/sbin/getty -L ttyS3 0 vt100
' >> rootfs_overlay/etc/inittab
./build-buildroot
./run --graphic -- \
  -serial telnet::1235,server,nowait \
  -serial vc:800x600 \
  -serial telnet::1236,server,nowait \
;

and on a second shell:

telnet localhost 1235

We don’t add more TTYs by default because it would spawn more processes, even if we use askfirst instead of respawn.

On the GUI, switch TTYs with:

You can also test this on most hosts such as Ubuntu 18.04, except that when in the GUI, you must use Ctrl-Alt-Fx to switch to another terminal.

Next, we also have the following shells running on the serial ports, hit enter to activate them:

although we cannot change between terminals from there.

Each populated TTY contains a "shell":

Identify the current TTY with the command:

tty

Bibliography:

This outputs:

Get the TTY in bulk for all processes:

./psa.sh

The TTY appears under the TT section, which is enabled by -o tty. This shows the TTY device number, e.g.:

4,1

and we can then confirm it with:

ls -l /dev/tty1

Next try:

insmod kthread.ko

and switch between virtual terminals, to understand that the dmesg goes to whatever current virtual terminal you are on, but not the others, and not to the serial terminals.

Bibliography:

TODO: how to place an sh directly on a TTY as well without getty?

If I try the exact same command that the inittab is doing from a regular shell after boot:

/sbin/getty 0 tty1

it fails with:

getty: setsid: Operation not permitted

The following however works:

./run --eval 'getty 0 tty1 & getty 0 tty2 & getty 0 tty3 & sleep 99999999' --graphic

presumably because it is being called from init directly?

Outcome: Alt-Right cycles between three TTYs, tty1 being the default one that appears under the boot messages.

man 2 setsid says that there is only one failure possibility:

EPERM The process group ID of any process equals the PID of the calling process. Thus, in particular, setsid() fails if the calling process is already a process group leader.

We can get some visibility into it to try and solve the problem with:

./psa.sh

Take the command described at TTY and try adding the following:

  • -e 'console=tty7': boot messages still show on /dev/tty1 (TODO how to change that?), but we don’t get a shell at the end of boot there.

    Instead, the shell appears on /dev/tty7.

  • -e 'console=tty2' like /dev/tty7, but /dev/tty2 is broken, because we have two shells there:

    • one due to the ::respawn:-/bin/sh entry which uses whatever console points to

    • another one due to the tty2::respawn:/sbin/getty entry we added

  • -e 'console=ttyS0' much like tty2, but messages show only on serial, and the terminal is broken due to having multiple shells on it

  • -e 'console=tty1 console=ttyS0': boot messages show on both tty1 and ttyS0, but only S0 gets a shell because it came last

This is due to the CONFIG_LOGO=y option which we enable by default.

reset on the terminal then kills the poor penguins.

When CONFIG_LOGO=y is set, the logo can be disabled at boot with:

./run --kernel-cli 'logo.nologo'

Looks like a recompile is needed to modify the image…​

DRM / DRI is the new interface that supersedes fbdev:

./build-buildroot --config 'BR2_PACKAGE_LIBDRM=y'
./build-userland --package libdrm -- userland/libs/libdrm/modeset.c
./run --eval-after './libs/libdrm/modeset.out' --graphic

Outcome: for a few seconds, the screen that contains the terminal gets taken over by changing colors of the rainbow.

TODO not working for aarch64, it takes over the screen for a few seconds and the kernel messages disappear, but the screen stays black all the time.

./build-buildroot --config 'BR2_PACKAGE_LIBDRM=y'
./build-userland --package libdrm
./build-buildroot
./run --eval-after './libs/libdrm/modeset.out' --graphic

kmscube however worked, which means that it must be a bug with this demo?

We set CONFIG_DRM=y on our default kernel configuration, and it creates one device file for each display:

# ls -l /dev/dri
total 0
crw-------    1 root     root      226,   0 May 28 09:41 card0
# grep 226 /proc/devices
226 drm
# ls /sys/module/drm /sys/module/drm_kms_helper/

Try creating new displays:

./run --arch aarch64 --graphic -- -device virtio-gpu-pci

to see multiple /dev/dri/cardN, and then use a different display with:

./run --eval-after './libs/libdrm/modeset.out' --graphic

Bibliography:

./build-buildroot --config-fragment buildroot_config/kmscube

Outcome: a colored spinning cube coded in OpenGL + EGL takes over your display and spins forever: https://www.youtube.com/watch?v=CqgJMgfxjsk

It is a bit amusing to see OpenGL running outside of a window manager window like that: https://stackoverflow.com/questions/3804065/using-opengl-without-a-window-manager-in-linux/50669152#50669152

TODO: it is very slow, about 1FPS. I tried Buildroot master ad684c20d146b220dd04a85dbf2533c69ec8ee52 with:

make qemu_x86_64_defconfig
printf "
BR2_CCACHE=y
BR2_PACKAGE_HOST_QEMU=y
BR2_PACKAGE_HOST_QEMU_LINUX_USER_MODE=n
BR2_PACKAGE_HOST_QEMU_SYSTEM_MODE=y
BR2_PACKAGE_HOST_QEMU_VDE2=y
BR2_PACKAGE_KMSCUBE=y
BR2_PACKAGE_MESA3D=y
BR2_PACKAGE_MESA3D_DRI_DRIVER_SWRAST=y
BR2_PACKAGE_MESA3D_OPENGL_EGL=y
BR2_PACKAGE_MESA3D_OPENGL_ES=y
BR2_TOOLCHAIN_BUILDROOT_CXX=y
" >> .config

and the FPS was much better, I estimate something like 15FPS.

On Ubuntu 18.04 with NVIDIA proprietary drivers:

sudo apt-get instll kmscube
kmscube

fails with:

drmModeGetResources failed: Invalid argument
failed to initialize legacy DRM

See also:

TODO get working.

Implements a console for DRM.

The Linux kernel has a built-in fbdev console called Linux kernel console fun but not for DRM it seems.

The upstream project seems dead with last commit in 2014: https://www.freedesktop.org/wiki/Software/kmscon/

Build failed in Ubuntu 18.04 with: dvdhrm/kmscon#131 but this fork compiled but didn’t run on host: Aetf/kmscon#2 (comment)

Haven’t tested the fork on QEMU too much insanity.

TODO get working.

Looks like a more raw alternative to libdrm:

./build-buildroot --config 'BR2_PACKABE_LIBDRI2=y'
wget \
  -O "$(./getvar userland_source_dir)/dri2test.c" \
  https://raw.githubusercontent.com/robclark/libdri2/master/test/dri2test.c \
;
./build-userland

but then I noticed that that example requires multiple files, and I don’t feel like integrating it into our build.

When I build it on Ubuntu 18.04 host, it does not generate any executable, so I’m confused.

Tests a lot of Linux and POSIX userland visible interfaces.

Buildroot already has a package, so it is trivial to build it:

./build-buildroot --config 'BR2_PACKAGE_LTP_TESTSUITE=y'

So now let’s try and see if the exit system call is working:

/usr/lib/ltp-testsuite/testcases/bin/exit01

which gives successful output:

exit01      1  TPASS  :  exit() test PASSED

Besides testing any kernel modifications you make, LTP can also be used to the system call implementation of User mode simulation as shown at User mode Buildroot executables:

./run --userland "$(./getvar buildroot_target_dir)/usr/lib/ltp-testsuite/testcases/bin/exit01"

Tested at: 287c83f3f99db8c1ff9bbc85a79576da6a78e986 + 1.

[posix] userland stress. Two versions:

./build-buildroot \
  --config 'BR2_PACKAGE_STRESS=y' \
  --config 'BR2_PACKAGE_STRESS_NG=y' \
;

STRESS_NG is likely the best, but it requires glibc, see: [libc-choice].

Websites:

stress usage:

stress --help
stress -c 16 &
ps

and notice how 16 threads were created in addition to a parent worker thread.

It just runs forever, so kill it when you get tired:

kill %1

stress -c 1 -t 1 makes gem5 irresponsive for a very long time.

Between all archs on QEMU and gem5 we touch all of those kernel built output files.

Converting arch/* images to vmlinux is possible in theory x86 with extract-vmlinux but we didn’t get any gem5 boots working from images generated like that for some reason, see: ************#79

Virtio is an interface that guest machines can use to efficiently use resources from host machines.

The types of resources it supports are for disks and networking hardware.

This interface is not like the real interface used by the host to read from real disks and network devices.

Rather, it is a simplified interface, that makes those operations simpler and faster since guest and host work together knowing that this is an emulation use case.

The following kernel modules and [baremetal] executables dump and disassemble various registers which cannot be observed from userland (usually "system registers", "control registers"):

Some of those programs are using:

Alternatively, you can also get their value from inside GDB step debug with:

info registers all

or the short version:

i r a

or to get just specific registers, e.g. just ARMv8’s SCTLR:

i r SCTLR

but it is sometimes just more convenient to run an executable to get the registers at the point of interest.

See also:

Zephyr is an RTOS that has [posix] support. I think it works much like our Baremetal setup which uses Newlib and generates individual ELF files that contain both our C program’s code, and the Zephyr libraries.

TODO get a hello world working, and then consider further integration in this repo, e.g. being able to run all C userland content on it.

TODO: Cortex-A CPUs are not currently supported, there are some qemu_cortex_m0 boards, but can’t find a QEMU Cortex-A. There is an x86_64 qemu board, but we don’t currently have an x86 baremetal toolchain. For this reason, we won’t touch this further for now.

However, unlike Newlib, Zephyr must be setting up a simple pre-main runtime to be able to handle threads.

Failed attempt:

# https://askubuntu.com/questions/952429/is-there-a-good-ppa-for-cmake-backports
wget -O - https://apt.kitware.com/keys/kitware-archive-latest.asc 2>/dev/null | sudo apt-key add -
sudo apt-add-repository 'deb https://apt.kitware.com/ubuntu/ bionic-rc main'
sudo apt-get update
sudo apt-get install cmake
git clone https://github.com/zephyrproject-rtos/zephyr
pip3 install --user -U west packaging
cd zephyr
git checkout v1.14.1
west init zephyrproject
west update
export ZEPHYR_TOOLCHAIN_VARIANT=xtools
export XTOOLS_TOOLCHAIN_PATH="$(pwd)/out/crosstool-ng/build/default/install/aarch64/bin/"
source zephyr-env.sh
west build -b qemu_aarch64 samples/hello_world

The build system of that project is a bit excessive / wonky. You need an edge CMake not present in Ubuntu 18.04, which I don’t want to install right now, and it uses the weird custom west build tool frontend.

TODO minimal setup to run it on QEMU? Possible?

TODO: get prototype working and then properly integrate:

./build-xen

Source: build-xen

This script attempts to build Xen for aarch64 and feed it into QEMU through submodules/boot-wrapper-aarch64

TODO: other archs not yet attempted.

The current bad behaviour is that it prints just:

Boot-wrapper v0.2

and nothing else.

We will also need CONFIG_XEN=y on the Linux kernel, but first Xen should print some Xen messages before the kernel is ever reached.

If we pass to QEMU the xen image directly instead of the boot wrapper one:

-kernel ../xen/xen/xen

then Xen messages do show up! So it seems that the configuration failure lies in the boot wrapper itself rather than Xen.

Maybe it is also possible to run Xen directly like this: QEMU can already load multiple images at different memory locations with the generic loader: https://github.com/qemu/qemu/blob/master/docs/generic-loader.txt which looks something along:

-kernel file1.elf -device loader,file=file2.elf

so as long as we craft the correct DTB and feed it into Xen so that it can see the kernel, it should work. TODO does QEMU support patching the auto-generated DTB with pre-generated options? In the worst case we can just dump it hand hack it up though with -machine dumpdtb, see: Section 9.4, “Device tree emulator generation”.

Bibliography:

U-Boot is a popular bootloader.

It can read disk filesystems, and Buildroot supports it, so we could in theory put it into memory, and let it find a kernel image from the root filesystem and boot that, but I didn’t manage to get it working yet: https://stackoverflow.com/questions/58028789/how-to-boot-linux-aarch64-with-u-boot-with-buildroot-on-qemu

QEMU is a system simulator: it simulates a CPU and devices such as interrupt handlers, timers, UART, screen, keyboard, etc.

If you are familiar with VirtualBox, then QEMU then basically does the same thing: it opens a "window" inside your desktop that can run an operating system inside your operating system.

Also both can use very similar techniques: either Binary translation or KVM. VirtualBox' binary translator is / was based on QEMU’s it seems: https://en.wikipedia.org/wiki/VirtualBox#Software-based_virtualization

The huge advantage of QEMU over VirtualBox is that is supports cross arch simulation, e.g. simulate an ARM guest on an x86 host.

QEMU is likely the leading cross arch system simulator as of 2018. It is even the default [android] simulator that developers get with Android Studio 3 to develop apps without real hardware.

Another advantage of QEMU over virtual box is that it doesn’t have Oracle' hands all all over it, more like RedHat + ARM.

Another advantage of QEMU is that is has no nice configuration GUI. Because who needs GUIs when you have 50 million semi-documented CLI options? Android Studio adds a custom GUI configuration tool on top of it.

QEMU is also supported by Buildroot in-tree, see e.g.: https://github.com/buildroot/buildroot/blob/2018.05/configs/qemu_aarch64_virt_defconfig We however just build our own manually with build-qemu, as it gives more flexibility, and building QEMU is very easy!

All of this makes QEMU the natural choice of reference system simulator for this repo.

We disable disk persistency for both QEMU and gem5 by default, to prevent the emulator from putting the image in an unknown state.

For QEMU, this is done by passing the snapshot option to -drive, and for gem5 it is the default behaviour.

If you hack up our run script to remove that option, then:

./run --eval-after 'date >f;poweroff'

followed by:

./run --eval-after 'cat f'

gives the date, because poweroff without -n syncs before shutdown.

The sync command also saves the disk:

sync

When you do:

./build-buildroot

the disk image gets overwritten by a fresh filesystem and you lose all changes.

Remember that if you forcibly turn QEMU off without sync or poweroff from inside the VM, e.g. by closing the QEMU window, disk changes may not be saved.

Persistency is also turned off when booting from initrd with a CPIO instead of with a disk.

Disk persistency is useful to re-run shell commands from the history of a previous session with Ctrl-R, but we felt that the loss of determinism was not worth it.

TODO how to make gem5 disk writes persistent?

As of cadb92f2df916dbb47f428fd1ec4932a2e1f0f48 there are some read_only entries in the gem5 config.ini under cow sections, but hacking them to true did not work:

diff --git a/configs/common/FSConfig.py b/configs/common/FSConfig.py
index 17498c42b..76b8b351d 100644
--- a/configs/common/FSConfig.py
+++ b/configs/common/FSConfig.py
@@ -60,7 +60,7 @@ os_types = { 'alpha' : [ 'linux' ],
            }

 class CowIdeDisk(IdeDisk):
-    image = CowDiskImage(child=RawDiskImage(read_only=True),
+    image = CowDiskImage(child=RawDiskImage(read_only=False),
                          read_only=False)

     def childImage(self, ci):

The directory of interest is src/dev/storage.

qcow2 does not appear supported, there are not hits in the source tree, and there is a mention on Nate’s 2009 wishlist: http://gem5.org/Nate%27s_Wish_List

This would be good to allow storing smaller sparse ext2 images locally on disk.

QEMU allows us to take snapshots at any time through the monitor.

You can then restore CPU, memory and disk state back at any time.

qcow2 filesystems must be used for that to work.

To test it out, login into the VM with and run:

./run --eval-after 'umount /mnt/9p/*;./count.sh'

On another shell, take a snapshot:

./qemu-monitor savevm my_snap_id

The counting continues.

Restore the snapshot:

./qemu-monitor loadvm my_snap_id

and the counting goes back to where we saved. This shows that CPU and memory states were reverted.

The umount is needed because snapshotting conflicts with 9P, which we felt is a more valuable default. If you forget to unmount, the following error appears on the QEMU monitor:

Migration is disabled when VirtFS export path '/linux-kernel-module-cheat/out/x86_64/buildroot/build' is mounted in the guest using mount_tag 'host_out'

We can also verify that the disk state is also reversed. Guest:

echo 0 >f

Monitor:

./qemu-monitor savevm my_snap_id

Guest:

echo 1 >f

Monitor:

./qemu-monitor loadvm my_snap_id

Guest:

cat f

And the output is 0.

Our setup does not allow for snapshotting while using initrd.

Snapshots are stored inside the .qcow2 images themselves.

They can be observed with:

"$(./getvar buildroot_host_dir)/bin/qemu-img" info "$(./getvar qcow2_file)"

which after savevm my_snap_id and savevm asdf contains an output of type:

image: out/x86_64/buildroot/images/rootfs.ext2.qcow2
file format: qcow2
virtual size: 512M (536870912 bytes)
disk size: 180M
cluster_size: 65536
Snapshot list:
ID        TAG                 VM SIZE                DATE       VM CLOCK
1         my_snap_id              47M 2018-04-27 21:17:50   00:00:15.251
2         asdf                    47M 2018-04-27 21:20:39   00:00:18.583
Format specific information:
    compat: 1.1
    lazy refcounts: false
    refcount bits: 16
    corrupt: false

As a consequence:

  • it is possible to restore snapshots across boots, since they stay on the same image the entire time

  • it is not possible to use snapshots with initrd in our setup, since we don’t pass -drive at all when initrd is enabled

This section documents:

For the more complex interfaces, we focus on simplified educational devices, either:

Only tested in x86.

Small upstream educational PCI device:

./qemu_edu.sh

This tests a lot of features of the edu device, to understand the results, compare the inputs with the documentation of the hardware: https://github.com/qemu/qemu/blob/v2.12.0/docs/specs/edu.txt

Sources:

Works because we add to our default QEMU CLI:

-device edu

This example uses:

  • the QEMU edu educational device, which is a minimal educational in-tree PCI example

  • the pci.ko kernel module, which exercises the edu hardware.

    I’ve contacted the awesome original author author of edu Jiri Slaby, and he told there is no official kernel module example because this was created for a kernel module university course that he gives, and he didn’t want to give away answers. I don’t agree with that philosophy, so students, cheat away with this repo and go make startups instead.

TODO exercise DMA on the kernel module. The edu hardware model has that feature:

In this section we will try to interact with PCI devices directly from userland without kernel modules.

First identify the PCI device with:

lspci

In our case for example, we see:

00:06.0 Unclassified device [00ff]: Device 1234:11e8 (rev 10)
00:07.0 Unclassified device [00ff]: Device 1234:11e9

which we identify as being QEMU edu PCI device by the magic number: 1234:11e8.

Alternatively, we can also do use the QEMU monitor:

./qemu-monitor info qtree

which gives:

      dev: edu, id ""
        addr = 06.0
        romfile = ""
        rombar = 1 (0x1)
        multifunction = false
        command_serr_enable = true
        x-pcie-lnksta-dllla = true
        x-pcie-extcap-init = true
        class Class 00ff, addr 00:06.0, pci id 1234:11e8 (sub 1af4:1100)
        bar 0: mem at 0xfea00000 [0xfeafffff]

Read the configuration registers as binary:

hexdump /sys/bus/pci/devices/0000:00:06.0/config

Get nice human readable names and offsets of the registers and some enums:

setpci --dumpregs

Get the values of a given config register from its human readable name, either with either bus or device id:

setpci -s 0000:00:06.0 BASE_ADDRESS_0
setpci -d 1234:11e8 BASE_ADDRESS_0

Note however that BASE_ADDRESS_0 also appears when you do:

lspci -v

as:

Memory at feb54000

Then you can try messing with that address with /dev/mem:

devmem 0xfeb54000 w 0x12345678

which writes to the first register of the edu device.

The device then fires an interrupt at irq 11, which is unhandled, which leads the kernel to say you are a bad person:

<3>[ 1065.567742] irq 11: nobody cared (try booting with the "irqpoll" option)

followed by a trace.

Next, also try using our irq.ko IRQ monitoring module before triggering the interrupt:

insmod irq.ko
devmem 0xfeb54000 w 0x12345678

Our kernel module handles the interrupt, but does not acknowledge it like our proper edu kernel module, and so it keeps firing, which leads to infinitely many messages being printed:

handler irq = 11 dev = 251

There are two versions of setpci and lspci:

  • a simple one from BusyBox

  • a more complete one from pciutils which Buildroot has a package for, and is the default on Ubuntu 18.04 host. This is the one we enable by default.

The PCI standard is non-free, obviously like everything in low level: https://pcisig.com/specifications but Google gives several illegal PDF hits :-)

And of course, the best documentation available is: http://wiki.osdev.org/PCI

Like every other hardware, we could interact with PCI on x86 using only IO instructions and memory operations.

But PCI is a complex communication protocol that the Linux kernel implements beautifully for us, so let’s use the kernel API.

Bibliography:

lspci -k shows something like:

00:04.0 Class 00ff: 1234:11e8 lkmc_pci

Meaning of the first numbers:

<8:bus>:<5:device>.<3:function>

Often abbreviated to BDF.

Sometimes a fourth number is also added, e.g.:

0000:00:04.0

TODO is that the domain?

Class: pure magic: https://www-s.acm.illinois.edu/sigops/2007/roll_your_own/7.c.1.html TODO: does it have any side effects? Set in the edu device at:

k->class_id = PCI_CLASS_OTHERS

Each PCI device has 6 BAR IOs (base address register) as per the PCI spec.

Each BAR corresponds to an address range that can be used to communicate with the PCI.

Each BAR is of one of the two types:

  • IORESOURCE_IO: must be accessed with inX and outX

  • IORESOURCE_MEM: must be accessed with ioreadX and iowriteX. This is the saner method apparently, and what the edu device uses.

The length of each region is defined by the hardware, and communicated to software via the configuration registers.

The Linux kernel automatically parses the 64 bytes of standardized configuration registers for us.

QEMU devices register those regions with:

memory_region_init_io(&edu->mmio, OBJECT(edu), &edu_mmio_ops, edu,
                "edu-mmio", 1 << 20);
pci_register_bar(pdev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY, &edu->mmio);

TODO: broken. Was working before we moved arm from -M versatilepb to -M virt around af210a76711b7fa4554dcc2abd0ddacfc810dfd4. Either make it work on -M virt if that is possible, or document precisely how to make it work with versatilepb, or hopefully vexpress which is newer.

The best you can do is to hack our build script to add:

HOST_QEMU_OPTS='--extra-cflags=-DDEBUG_PL061=1'

where PL061 is the dominating ARM Holdings hardware that handles GPIO.

Then compile with:

./build-buildroot --arch arm --config-fragment buildroot_config/gpio
./build-linux --config-fragment linux_config/gpio

then test it out with:

./gpio.sh

Buildroot’s Linux tools package provides some GPIO CLI tools: lsgpio, gpio-event-mon, gpio-hammer, TODO document them here.

TODO: broken when arm moved to -M virt, same as GPIO.

Hack QEMU’s hw/misc/arm_sysctl.c with a printf:

static void arm_sysctl_write(void *opaque, hwaddr offset,
                            uint64_t val, unsigned size)
{
    arm_sysctl_state *s = (arm_sysctl_state *)opaque;

    switch (offset) {
    case 0x08: /* LED */
        printf("LED val = %llx\n", (unsigned long long)val);

and then rebuild with:

./build-qemu --arch arm
./build-linux --arch arm --config-fragment linux_config/leds

But beware that one of the LEDs has a heartbeat trigger by default (specified on dts), so it will produce a lot of output.

And then activate it with:

cd /sys/class/leds/versatile:0
cat max_brightness
echo 255 >brightness

Relevant QEMU files:

  • hw/arm/versatilepb.c

  • hw/misc/arm_sysctl.c

Relevant kernel files:

  • arch/arm/boot/dts/versatile-pb.dts

  • drivers/leds/led-class.c

  • drivers/leds/leds-sysctl.c

The QEMU monitor is a magic terminal that allows you to send text commands to the QEMU VM itself: https://en.wikibooks.org/wiki/QEMU/Monitor

While QEMU is running, on another terminal, run:

./qemu-monitor

or send one command such as info qtree and quit the monitor:

./qemu-monitor info qtree

or equivalently:

echo 'info qtree' | ./qemu-monitor

Source: qemu-monitor

qemu-monitor uses the -monitor QEMU command line option, which makes the monitor listen from a socket.

Alternatively, we can also enter the QEMU monitor from inside -nographics QEMU text mode with:

Ctrl-A C

and go back to the terminal with:

Ctrl-A C

When in graphic mode, we can do it from the GUI:

Ctrl-Alt ?

where ? is a digit 1, or 2, or, 3, etc. depending on what else is available on the GUI: serial, parallel and frame buffer.

Finally, we can also access QEMU monitor commands directly from GDB step debug with the monitor command:

./run-gdb

then inside that shell:

monitor info qtree

This way you can use both QEMU monitor and GDB commands to inspect the guest from inside a single shell! Pretty awesome.

In general, ./qemu-monitor is the best option, as it:

  • works on both modes

  • allows to use the host Bash history to re-run one off commands

  • allows you to search the output of commands on your host shell even when in graphic mode

Getting everything to work required careful choice of QEMU command line options:

It is also worth looking into the QEMU Guest Agent tool qemu-gq that can be enabled with:

./build-buildroot --config 'BR2_PACKAGE_QEMU=y'

When doing GDB step debug it is possible to send QEMU monitor commands through the GDB monitor command, which saves you the trouble of opening yet another shell.

Try for example:

monitor help
monitor info qtree

When you start hacking QEMU or gem5, it is useful to see what is going on inside the emulator themselves.

This is of course trivial since they are just regular userland programs on the host, but we make it a bit easier with:

./run --debug-vm

Or for a faster development loop you can pass -ex command as a semicolon separated list:

./run --debug-vm-ex 'break qemu_add_opts;run'

which is equivalent to the more verbose:

./run --debug-vm-args '-ex "break qemu_add_opts" -ex "run"'

if you ever want need anything besides -ex.

Or if things get really involved and you want a debug script:

printf 'break qemu_add_opts
run
' > data/vm.gdb
./run --debug-vm-file data/vm.gdb

Our default emulator builds are optimized with gcc -O2 -g. To use -O0 instead, build and run with:

./build-qemu --qemu-build-type debug --verbose
./run --debug-vm
./build-gem5 --gem5-build-type debug --verbose
./run --debug-vm --emulator-gem5

The --verbose is optional, but shows clearly each GCC build command so that you can confirm what --*-build-type is doing.

The build outputs are automatically stored in a different directories for optimized and debug builds, which prevents debug files from overwriting opt ones. Therefore, --gem5-build-id is not required.

The price to pay for debuggability is high however: a Linux kernel boot was about 3x slower in QEMU and 14 times slower in gem5 debug compared to opt, see benchmarks at: [benchmark-linux-kernel-boot].

Similar slowdowns can be observed at: [benchmark-emulators-on-userland-executables].

When in QEMU text mode, using --debug-vm makes Ctrl-C not get passed to the QEMU guest anymore: it is instead captured by GDB itself, so allow breaking. So e.g. you won’t be able to easily quit from a guest program like:

sleep 10

In graphic mode, make sure that you never click inside the QEMU graphic while debugging, otherwise you mouse gets captured forever, and the only solution I can find is to go to a TTY with Ctrl-Alt-F1 and kill QEMU.

You can still send key presses to QEMU however even without the mouse capture, just either click on the title bar, or alt tab to give it focus.

While step debugging any complex program, you always end up feeling the need to step in reverse to reach the last call to some function that was called before the failure point, in order to trace back the problem to the actual bug source.

While GDB "has" this feature, it is just too broken to be usable, and so we expose the amazing Mozilla RR tool conveniently in this repo: https://stackoverflow.com/questions/1470434/how-does-reverse-debugging-work/53063242#53063242

Before the first usage setup rr with:

echo 'kernel.perf_event_paranoid=1' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

Then use it with your content of interest, for example:

./run --debug-vm-rr --userland userland/c/hello.c

This will:

  • first run the program once until completion or crash

  • then restart the program at the very first instruction at _start and leave you in a GDB shell

From there, run the program until your point of interest, e.g.:

break qemu_add_opts
continue

and you can now reliably use reverse debugging commands such as reverse-continue, reverse-finish and reverse-next!

To restart debugging again after quitting rr, simply run on your host terminal:

rr replay

The use case of rr is often to go to the final crash and then walk back from there, so you often want to automate running until the end after record with --debug-vm-args as in:

./run --debug-vm-args='-ex continue' --debug-vm-rr --userland userland/c/hello.c

Programs often tend to blow up in very low frames that use values passed in from higher frames. In those cases, remember that just like with forward debugging, you can’t just go:

up
up
up
reverse-next

but rather, you must:

reverse-finish
reverse-finish
reverse-finish
reverse-next

Start pdb at the first instruction:

./run --emulator gem5 --gem5-exe-args='--pdb' --terminal

Requires --terminal as we must be on foreground.

Alternatively, you can add to the point of the code where you want to break the usual:

import ipdb; ipdb.set_trace()

and then run with:

./run --emulator gem5 --terminal

QEMU can log several different events.

The most interesting are events which show instructions that QEMU ran, for which we have a helper:

./trace-boot --arch x86_64

Under the hood, this uses QEMU’s -trace option.

You can then inspect the address of each instruction run:

less "$(./getvar --arch x86_64 run_dir)/trace.txt"

Sample output excerpt:

exec_tb 0.000 pid=10692 tb=0x7fb4f8000040 pc=0xfffffff0
exec_tb 35.391 pid=10692 tb=0x7fb4f8000180 pc=0xfe05b
exec_tb 21.047 pid=10692 tb=0x7fb4f8000340 pc=0xfe066
exec_tb 12.197 pid=10692 tb=0x7fb4f8000480 pc=0xfe06a

Get the list of available trace events:

./run --trace help

TODO: any way to show the actualy disassembled instruction executed directly from there? Possible with QEMU -d tracing.

Enable other specific trace events:

./run --trace trace1,trace2
./qemu-trace2txt -a "$arch"
less "$(./getvar -a "$arch" run_dir)/trace.txt"

This functionality relies on the following setup:

  • ./configure --enable-trace-backends=simple. This logs in a binary format to the trace file.

    It makes 3x execution faster than the default trace backend which logs human readable data to stdout.

    Logging with the default backend log greatly slows down the CPU, and in particular leads to this boot message:

    All QSes seen, last rcu_sched kthread activity 5252 (4294901421-4294896169), jiffies_till_next_fqs=1, root ->qsmask 0x0
    swapper/0       R  running task        0     1      0 0x00000008
     ffff880007c03ef8 ffffffff8107aa5d ffff880007c16b40 ffffffff81a3b100
     ffff880007c03f60 ffffffff810a41d1 0000000000000000 0000000007c03f20
     fffffffffffffedc 0000000000000004 fffffffffffffedc ffffffff00000000
    Call Trace:
     <IRQ>  [<ffffffff8107aa5d>] sched_show_task+0xcd/0x130
     [<ffffffff810a41d1>] rcu_check_callbacks+0x871/0x880
     [<ffffffff810a799f>] update_process_times+0x2f/0x60

    in which the boot appears to hang for a considerable time.

  • patch QEMU source to remove the disable from exec_tb in the trace-events file. See also: https://rwmj.wordpress.com/2016/03/17/tracing-qemu-guest-execution/

QEMU also has a second trace mechanism in addition to -trace, find out the events with:

./run -- -d help

Let’s pick the one that dumps executed instructions, in_asm:

./run --eval './linux/poweroff.out' -- -D out/trace.txt -d in_asm
less out/trace.txt

Sample output excerpt:

----------------
IN:
0xfffffff0:  ea 5b e0 00 f0           ljmpw    $0xf000:$0xe05b

----------------
IN:
0x000fe05b:  2e 66 83 3e 88 61 00     cmpl     $0, %cs:0x6188
0x000fe062:  0f 85 7b f0              jne      0xd0e1

TODO: after IN:, symbol names are meant to show, which is awesome, but I don’t get any. I do see them however when running a bare metal example from: https://github.com/************/newlib-examples/tree/900a9725947b1f375323c7da54f69e8049158881

TODO: what is the point of having two mechanisms, -trace and -d? -d tracing is cool because it does not require a messy recompile, and it can also show symbols.

TODO: is it possible to show the register values for each instruction?

This would include the memory values read into the registers.

Seems impossible due to optimizations that QEMU does:

PANDA can list memory addresses, so I bet it can also decode the instructions: https://github.com/panda-re/panda/blob/883c85fa35f35e84a323ed3d464ff40030f06bd6/panda/docs/LINE_Censorship.md I wonder why they don’t just upstream those things to QEMU’s tracing: panda-re/panda#290

gem5 can do it as shown at: Section 23.9.8, “gem5 tracing”.

Not possible apparently, not even with the memory_region_ops_read and memory_region_ops_write trace events, Peter comments https://lists.gnu.org/archive/html/qemu-devel/2015-06/msg07482.html

No. You will miss all the fast-path memory accesses, which are done with custom generated assembly in the TCG backend. In general QEMU is not designed to support this kind of monitoring of guest operations.

We can further use Binutils' addr2line to get the line that corresponds to each address:

./trace-boot --arch x86_64
./trace2line --arch x86_64
less "$(./getvar --arch x86_64 run_dir)/trace-lines.txt"

The last commands takes several seconds.

The format is as follows:

39368 _static_cpu_has arch/x86/include/asm/cpufeature.h:148

Where:

  • 39368: number of consecutive times that a line ran. Makes the output much shorter and more meaningful

  • _static_cpu_has: name of the function that contains the line

  • arch/x86/include/asm/cpufeature.h:148: file and line

This could of course all be done with GDB, but it would likely be too slow to be practical.

TODO do even more awesome offline post-mortem analysis things, such as:

  • detect if we are in userspace or kernelspace. Should be a simple matter of reading the

  • read kernel data structures, and determine the current thread. Maybe we can reuse / extend the kernel’s GDB Python scripts??

QEMU runs, unlike gem5, are not deterministic by default, however it does support a record and replay mechanism that allows you to replay a previous run deterministically.

This awesome feature allows you to examine a single run as many times as you would like until you understand everything:

# Record a run.
./run --eval-after './linux/rand_check.out;./linux/poweroff.out;' --record
# Replay the run.
./run --eval-after './linux/rand_check.out;./linux/poweroff.out;' --replay

A convenient shortcut to do both at once to test the feature is:

./qemu-rr --eval-after './linux/rand_check.out;./linux/poweroff.out;'

By comparing the terminal output of both runs, we can see that they are the exact same, including things which normally differ across runs:

The record and replay feature was revived around QEMU v3.0.0. In v5.2.0 it is quite usable, almost all peripherals and vCPUs are supported.

replay may be used with with network:

./qemu-rr --eval-after 'ifup -a;wget -S google.com;./linux/poweroff.out;'

arm and aarch64 targets can also be used with rr:

./qemu-rr --arch aarch64 --eval-after './linux/rand_check.out;./linux/poweroff.out;'
./qemu-rr --arch aarch64 --eval-after 'ifup -a;wget -S google.com;./linux/poweroff.out;'

Replay also supports initrd and no disk:

./build-buildroot --arch aarch64 --initrd
./qemu-rr --arch aarch64 --eval-after './linux/rand_check.out;./linux/poweroff.out;' --initrd

QEMU replays support checkpointing, and this allows for a simplistic "reverse debugging" implementation since v5.2.0:

./run --eval-after './linux/rand_check.out;./linux/poweroff.out;' --record
./run --eval-after './linux/rand_check.out;./linux/poweroff.out;' --replay --gdb-wait

On another shell:

./run-gdb start_kernel

In GDB:

n
n
n
n
reverse-continue

and we are back at start_kernel

reverse-continue proceeds to the latest of the earlier breakpoints or to the very beginning if there were no breakpoints before.

TODO: is there any way to distinguish which instruction runs on each core? Doing:

./run --arch x86_64 --cpus 2 --eval './linux/poweroff.out' --trace exec_tb
./qemu-trace2txt

just appears to output both cores intertwined without any clear differentiation.

gem5 provides also provides a tracing mechanism documented at: http://www.gem5.org/Trace_Based_Debugging:

./run --arch aarch64 --eval 'm5 exit' --emulator gem5 --trace ExecAll
less "$(./getvar --arch aarch64 run_dir)/trace.txt"

Our wrapper just forwards the options to the --debug-flags gem5 option.

Keep in mind however that the disassembly is very broken in several places as of 2019q2, so you can’t always trust it.

Output the trace to stdout instead of a file:

./run \
  --arch aarch64 \
  --emulator gem5 \
  --eval 'm5 exit' \
  --trace ExecAll \
  --trace-stdout \
;

We also have a shortcut for --trace ExecAll -trace-stdout with --trace-insts-stdout

./run \
  --arch aarch64 \
  --emulator gem5 \
  --eval 'm5 exit' \
  --trace-insts-stdout \
;

Be warned, the trace is humongous, at 16Gb.

This would produce a lot of output however, so you will likely not want that when tracing a Linux kernel boot instructions. But it can be very convenient for smaller traces such as [baremetal].

List all available debug flags:

./run --arch aarch64 --gem5-exe-args='--debug-help' --emulator gem5

but to understand most of them you have to look at the source code:

less "$(./getvar gem5_source_dir)/src/cpu/SConscript"
less "$(./getvar gem5_source_dir)/src/cpu/exetrace.cc"

The most important trace flags to know about are:

Trace internals are discussed at: gem5 trace internals.

As can be seen on the Sconstruct, Exec is just an alias that enables a set of flags.

We can make the trace smaller by naming the trace file as trace.txt.gz, which enables GZIP compression, but that is not currently exposed on our scripts, since you usually just need something human readable to work on.

Enabling tracing made the runtime about 4x slower on the [p51], with or without .gz compression.

Trace the source lines just like for QEMU with:

./trace-boot --arch aarch64 --emulator gem5
./trace2line --arch aarch64 --emulator gem5
less "$(./getvar --arch aarch64 run_dir)/trace-lines.txt"

TODO: 7452d399290c9c1fc6366cdad129ef442f323564 ./trace2line this is too slow and takes hours. QEMU’s processing of 170k events takes 7 seconds. gem5’s processing is analogous, but there are 140M events, so it should take 7000 seconds ~ 2 hours which seems consistent with what I observe, so maybe there is no way to speed this up…​ The workaround is to just use gem5’s ExecSymbol to get function granularity, and then GDB individually if line detail is needed?

gem5 traces are generated from DPRINTF(<trace-id> calls scattered throughout the code, except for ExecAll instruction traces, which uses Debug::ExecEnable directly..

The trace IDs are themselves encoded in SConscript files, e.g.:

DebugFlag('Event'

in src/cpu/SConscript.

The build system then automatically adds the options to the --debug-flags.

For this entry, the build system then generates a file build/ARM/debug/ExecEnable.hh, which contains:

namespace Debug {
class SimpleFlag;
extern SimpleFlag ExecEnable;
}

and must be included in from callers of DPRINTF( as <debug/ExecEnable.hh>.

Tested in b4879ae5b0b6644e6836b0881e4da05c64a6550d.

This debug flag traces all instructions.

The output format is of type:

25007000: system.cpu T0 : @start_kernel    : stp
25007000: system.cpu T0 : @start_kernel.0  :   addxi_uop   ureg0, sp, #-112 : IntAlu :  D=0xffffff8008913f90
25007500: system.cpu T0 : @start_kernel.1  :   strxi_uop   x29, [ureg0] : MemWrite :  D=0x0000000000000000 A=0xffffff8008913f90
25008000: system.cpu T0 : @start_kernel.2  :   strxi_uop   x30, [ureg0, #8] : MemWrite :  D=0x0000000000000000 A=0xffffff8008913f98
25008500: system.cpu T0 : @start_kernel.3  :   addxi_uop   sp, ureg0, #0 : IntAlu :  D=0xffffff8008913f90

There are two types of lines:

Breakdown:

  • 25007500: time count in some unit. Note how the microops execute at further timestamps.

  • system.cpu: distinguishes between CPUs when there are more than one. For example, running [arm-baremetal-multicore] with two cores produces system.cpu0 and system.cpu1

  • T0: thread number. TODO: hyperthread? How to play with it?

    config.ini has --param 'system.multi_thread = True' --param 'system.cpu[0].numThreads = 2', but in [arm-baremetal-multicore] the first one alone does not produce T1, and with the second one simulation blows up with:

    fatal: fatal condition interrupts.size() != numThreads occurred: CPU system.cpu has 1 interrupt controllers, but is expecting one per thread (2)
  • @start_kernel: we are in the start_kernel function. Awesome feature! Implemented with libelf https://sourceforge.net/projects/elftoolchain/ copy pasted in-tree ext/libelf. To get raw addresses, remove the ExecSymbol, which is enabled by Exec. This can be done with Exec,-ExecSymbol.

  • .1 as in @start_kernel.1: index of the [gem5-microops]

  • stp: instruction disassembly. Note however that the disassembly of many instructions are very broken as of 2019q2, and you can’t just trust them blindly.

  • strxi_uop x29, [ureg0]: microop disassembly.

  • MemWrite : D=0x0000000000000000 A=0xffffff8008913f90: a memory write microop:

    • D stands for data, and represents the value that was written to memory or to a register

    • A stands for address, and represents the address to which the value was written. It only shows when data is being written to memory, but not to registers.

The best way to verify all of this is to write some baremetal code

This flag shows a more detailed register usage than gem5 ExecAll trace format.

For example, if we run in LKMC 0323e81bff1d55b978a4b36b9701570b59b981eb:

./run --arch aarch64 --baremetal userland/arch/aarch64/add.S --emulator gem5 --trace ExecAll,Registers --trace-stdout

then the stdout contains:

  31000: system.cpu A0 T0 : @main_after_prologue    :   movz   x0, #1, #0        : IntAlu :  D=0x0000000000000001  flags=(IsInteger)
  31500: system.cpu.[tid:0]: Setting int reg 34 (34) to 0.
  31500: system.cpu.[tid:0]: Reading int reg 0 (0) as 0x1.
  31500: system.cpu.[tid:0]: Setting int reg 1 (1) to 0x3.
  31500: system.cpu A0 T0 : @main_after_prologue+4    :   add   x1, x0, #2         : IntAlu :  D=0x0000000000000003  flags=(IsInteger)
  32000: system.cpu.[tid:0]: Setting int reg 34 (34) to 0.
  32000: system.cpu.[tid:0]: Reading int reg 1 (1) as 0x3.
  32000: system.cpu.[tid:0]: Reading int reg 31 (34) as 0.
  32000: system.cpu.[tid:0]: Setting int reg 0 (0) to 0x3.

which corresponds to the two following instructions:

mov x0, 1
add x1, x0, 2

TODO that format is either buggy or is very difficult to understand:

  • what is 34? Presumably some flags register?

  • what do the numbers in parenthesis mean at 31 (34)? Presumably some flags register?

  • why is the first instruction setting reg 1 and the second one reg 0, given that the first sets x0 and the second x1?

As of gem5 16eeee5356585441a49d05c78abc328ef09f7ace the default tracer is ExeTracer. It is set at:

src/cpu/BaseCPU.py:63:default_tracer = ExeTracer()

which then gets used at:

class BaseCPU(ClockedObject):
    [...]
    tracer = Param.InstTracer(default_tracer, "Instruction tracer")

All tracers derive from the common InstTracer base class:

git grep ': InstTracer'

gives:

src/arch/arm/tracers/tarmac_parser.hh:218:    TarmacParser(const Params *p) : InstTracer(p), startPc(p->start_pc),
src/arch/arm/tracers/tarmac_tracer.cc:57:  : InstTracer(p),
src/cpu/exetrace.hh:67:    ExeTracer(const Params *params) : InstTracer(params)
src/cpu/inst_pb_trace.cc:72:    : InstTracer(p), buf(nullptr), bufSize(0), curMsg(nullptr)
src/cpu/inteltrace.hh:63:    IntelTrace(const IntelTraceParams *p) : InstTracer(p)

As mentioned at gem5 TARMAC traces, there appears to be no way to select those currently without hacking the config scripts.

TARMAC is described at: gem5 TARMAC traces.

TODO: are IntelTrace and TarmacParser useful for anything or just relics?

Then there is also the NativeTrace class:

src/cpu/nativetrace.hh:68:class NativeTrace : public ExeTracer

which gets implemented in a few different ISAs, but not all:

src/arch/arm/nativetrace.hh:40:class ArmNativeTrace : public NativeTrace
src/arch/sparc/nativetrace.hh:41:class SparcNativeTrace : public NativeTrace
src/arch/x86/nativetrace.hh:41:class X86NativeTrace : public NativeTrace

TODO: I can’t find any usages of those classes from in-tree configs.

Sometimes in Ubuntu 14.04, after the QEMU SDL GUI starts, it does not get updated after keyboard strokes, and there are artifacts like disappearing text.

We have not managed to track this problem down yet, but the following workaround always works:

Ctrl-Shift-U
Ctrl-C
root

This started happening when we switched to building QEMU through Buildroot, and has not been observed on later Ubuntu.

Using text mode is another workaround if you don’t need GUI features.

gem5 has a bunch of crappiness, mostly described at: gem5 vs QEMU, but it does deserve some credit on the following points:

  • insanely configurable system topology from Python without recompiling, made possible in part due to a well defined memory packet structure that allows adding caches and buses transparently

  • each micro architectural model (gem5 CPU types) works with all ISAs

  • advantages of gem5:

  • disadvantages of gem5:

    • slower than QEMU, see: [benchmark-linux-kernel-boot]

      This implies that the user base is much smaller, since no Android devs.

      Instead, we have only chip makers, who keep everything that really works closed, and researchers, who can’t version track or document code properly >:-) And this implies that:

      • the documentation is more scarce

      • it takes longer to support new hardware features

      Well, not that AOSP is that much better anyway.

    • not sure: gem5 has BSD license while QEMU has GPL

      This suits chip makers that want to distribute forks with secret IP to their customers.

      On the other hand, the chip makers tend to upstream less, and the project becomes more crappy in average :-)

    • gem5 is way more complex and harder to modify and maintain

      The only hairy thing in QEMU is the binary code generation.

      gem5 however has tended towards horrendous intensive code generation in order to support all its different hardware types

      gem5 also has a complex Python interface which is also largely auto-generated, which greatly increases the maintenance complexity of the project: [embedding-python-in-another-application].

      This is done so that reconfiguring platforms can be done quickly without recompiling, and it is amazing when it works, but the maintenance costs are also very high. For example, [pybind11] of several trivial param_ files accounted for 50% of the build time at one point: [pybind11-accounts-for-50-of-gem5-build-time].

      All of this also makes it hard to setup an IDE for developing gem5: gem5 Eclipse configuration

      The feelings of helplessness this brings are well summarized by the following CSDN article https://blog.csdn.net/maokelong95/article/details/85333905:

      Found DPRINTF based debugging unable to meet your needs?

      Found GDB based debugging unfriendly to human beings?

      Want to debug gem5 source with the help of modern IDEs like Eclipse?

      Failed in getting help from GEM5 community?

      Come on, dude! Here is the up-to-date tutorial for you!

      Just be ready for THE ENDLESS NIGHTMARE gem5 will bring!

OK, this is why we used gem5 in the first place, performance measurements!

Let’s see how many cycles dhrystone, which Buildroot provides, takes for a few different input parameters.

We will do that for various input parameters on full system by taking a checkpoint after the boot finishes a fast atomic CPU boot, and then we will restore in a more detailed mode and run the benchmark:

./build-buildroot --config 'BR2_PACKAGE_DHRYSTONE=y'
# Boot fast, take checkpoint, and exit.
./run --arch aarch64 --emulator gem5 --eval-after './gem5.sh'

# Restore the checkpoint after boot, and benchmark with input 1000.
./run \
  --arch aarch64 \
  --emulator gem5 \
  --eval-after './gem5.sh' \
  --gem5-readfile 'm5 resetstats;dhrystone 1000;m5 dumpstats' \
  --gem5-restore 1 \
  -- \
  --cpu-type=HPI \
  --restore-with-cpu=HPI \
  --caches \
  --l2cache \
  --l1d_size=64kB \
  --l1i_size=64kB \
  --l2_size=256kB \
;
# Get the value for number of cycles.
# head because there are two lines: our dumpstats and the
# automatic dumpstats at the end which we don't care about.
./gem5-stat --arch aarch64 | head -n 1

# Now for input 10000.
./run \
  --arch aarch64 \
  --emulator gem5 \
  --eval-after './gem5.sh' \
  --gem5-readfile 'm5 resetstats;dhrystone 10000;m5 dumpstats' \
  --gem5-restore 1 \
  -- \
  --cpu-type=HPI \
  --restore-with-cpu=HPI \
  --caches \
  --l2cache \
  --l1d_size=64kB \
  --l1i_size=64kB \
  --l2_size=256kB \
;
./gem5-stat --arch aarch64 | head -n 1

If you ever need a shell to quickly inspect the system state after boot, you can just use:

./run \
  --arch aarch64 \
  --emulator gem5 \
  --eval-after './gem5.sh' \
  --gem5-readfile 'sh' \
  --gem5-restore 1 \

This procedure is further automated and DRYed up at:

./gem5-bench-dhrystone
cat out/gem5-bench-dhrystone.txt

Output at 2438410c25e200d9766c8c65773ee7469b599e4a + 1:

n cycles
1000 13665219
10000 20559002
100000 85977065

so as expected, the Dhrystone run with a larger input parameter 100000 took more cycles than the ones with smaller input parameters.

The gem5-stats commands output the approximate number of CPU cycles it took Dhrystone to run.

A more naive and simpler to understand approach would be a direct:

./run --arch aarch64 --emulator gem5 --eval 'm5 checkpoint;m5 resetstats;dhrystone 10000;m5 exit'

but the problem is that this method does not allow to easily run a different script without running the boot again. The ./gem5.sh script works around that by using m5 readfile as explained further at: Section 24.6.3, “gem5 checkpoint restore and run a different script”.

Now you can play a fun little game with your friends:

  • pick a computational problem

  • make a program that solves the computation problem, and outputs output to stdout

  • write the code that runs the correct computation in the smallest number of cycles possible

Interesting algorithms and benchmarks for this game are being collected at:

To find out why your program is slow, a good first step is to have a look at the gem5 m5out/stats.txt file.

A few imperfections of our benchmarking method are:

  • when we do m5 resetstats and m5 exit, there is some time passed before the exec system call returns and the actual benchmark starts and ends

  • the benchmark outputs to stdout, which means so extra cycles in addition to the actual computation. But TODO: how to get the output to check that it is correct without such IO cycles?

Solutions to these problems include:

  • modify benchmark code with instrumentation directly, see m5ops instructions for an example.

  • monitor known addresses TODO possible? Create an example.

Those problems should be insignificant if the benchmark runs for long enough however.

Besides optimizing a program for a given CPU setup, chip developers can also do the inverse, and optimize the chip for a given benchmark!

The rabbit hole is likely deep, but let’s scratch a bit of the surface.

./run --arch arm --cpus 2 --emulator gem5

Can be checked with /proc/cpuinfo or getconf in Ubuntu 18.04:

cat /proc/cpuinfo
getconf _NPROCESSORS_CONF

Or from User mode simulation, we can use either of:

User mode simulation QEMU v4.0.0 always shows the number of cores of the host, presumably because the thread switching uses host threads directly which would make that harder to implement.

It does not seem possible to make the guest see a different number of cores than what the host has. Full system does have the -smp options, which controls this.

E.g., all of of the following output the same as nproc on the host:

nproc
./run --cpus 1 --userland userland/cpp/thread_hardware_concurrency.cpp
./run --cpus 2 --userland userland/cpp/thread_hardware_concurrency.cpp

This random page suggests that QEMU splits one host thread thread per guest thread, and thus presumably delegates context switching to the host kernel: https://qemu.weilnetz.de/w64/2012/2012-12-04/qemu-tech.html#User-emulation-specific-details

We can confirm that with:

./run --userland userland/posix/pthread_count.c --cli-args 4
ps Haux | grep qemu | wc

At 369a47fc6e5c2f4a7f911c1c058b6088f8824463 + 1 QEMU appears to spawn 3 host threads plus one for every new guest thread created. Remember that userland/posix/pthread_count.c spawns N + 1 total threads if you count the main thread.

With GICv3, tested at LKMC 224fae82e1a79d9551b941b19196c7e337663f22 gem5 3ca404da175a66e0b958165ad75eb5f54cb5e772 on vanilla kernel:

./run \
  --arch aarch64 \
  --emulator gem5 \
  --cpus 16 \
  -- \
  --machine-type VExpress_GEM5_V2 \
;

boots to a shell and nproc shows 16.

For the GICv2 extension method, build the kernel with the gem5 arm Linux kernel patches, and then run:

./run \
  --arch aarch64 \
  --linux-build-id gem5-v4.15 \
  --emulator gem5 \
  --cpus 16 \
  -- \
  --param 'system.realview.gic.gem5_extensions = True' \
;

Tested in LKMC 788087c6f409b84adf3cff7ac050fa37df6d4c46. It fails after boot with FATAL: kernel too old as mentioned at: gem5 arm Linux kernel patches but everything seems to work on the gem5 side of things.

A quick ./run --emulator gem5 -- -h leads us to the options:

--caches
--l1d_size=1024
--l1i_size=1024
--l2cache
--l2_size=1024
--l3_size=1024

But keep in mind that it only affects benchmark performance of the most detailed CPU types as shown at: Table 2, “gem5 cache support in function of CPU type”.

Table 2. gem5 cache support in function of CPU type
arch CPU type caches used

X86

AtomicSimpleCPU

no

X86

DerivO3CPU

?*

ARM

AtomicSimpleCPU

no

ARM

HPI

yes

*: couldn’t test because of:

Cache sizes can in theory be checked with the methods described at: https://superuser.com/questions/55776/finding-l2-cache-size-in-linux:

lscpu
cat /sys/devices/system/cpu/cpu0/cache/index2/size

and on Ubuntu 20.04 host but not Buildroot 1.31.1:

getconf -a | grep CACHE

and we also have an easy to use userland executable using [sysconf] at userland/linux/sysconf.c:

./run --emulator gem5 --userland userland/linux/sysconf.c

but for some reason the Linux kernel is not seeing the cache sizes:

Behaviour breakdown:

  • arm QEMU and gem5 (both AtomicSimpleCPU or HPI), x86 gem5: /sys files don’t exist, and getconf and lscpu value empty

  • x86 QEMU: /sys files exist, but getconf and lscpu values still empty

Or for a quick and dirty performance measurement approach instead:

./gem5-bench-cache -- --arch aarch64
cat "$(./getvar --arch aarch64 run_dir)/bench-cache.txt"

which gives:

cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 1000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024   --l1i_size=1024   --l2_size=1024   --l3_size=1024   --cpu-type=HPI --restore-with-cpu=HPI
time 23.82
exit_status 0
cycles 93284622
instructions 4393457

cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 1000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024kB --l1i_size=1024kB --l2_size=1024kB --l3_size=1024kB --cpu-type=HPI --restore-with-cpu=HPI
time 14.91
exit_status 0
cycles 10128985
instructions 4211458

cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 10000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024   --l1i_size=1024   --l2_size=1024   --l3_size=1024   --cpu-type=HPI --restore-with-cpu=HPI
time 51.87
exit_status 0
cycles 188803630
instructions 12401336

cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 10000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024kB --l1i_size=1024kB --l2_size=1024kB --l3_size=1024kB --cpu-type=HPI --restore-with-cpu=HPI
time 35.35
exit_status 0
cycles 20715757
instructions 12192527

cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 100000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024   --l1i_size=1024   --l2_size=1024   --l3_size=1024   --cpu-type=HPI --restore-with-cpu=HPI
time 339.07
exit_status 0
cycles 1176559936
instructions 94222791

cmd ./run --emulator gem5 --arch aarch64 --gem5-readfile "dhrystone 100000" --gem5-restore 1 -- --caches --l2cache --l1d_size=1024kB --l1i_size=1024kB --l2_size=1024kB --l3_size=1024kB --cpu-type=HPI --restore-with-cpu=HPI
time 240.37
exit_status 0
cycles 125666679
instructions 91738770

We make the following conclusions:

  • the number of instructions almost does not change: the CPU is waiting for memory all the extra time. TODO: why does it change at all?

  • the wall clock execution time is not directionally proportional to the number of cycles: here we had a 10x cycle increase, but only 2x time increase. This suggests that the simulation of cycles in which the CPU is waiting for memory to come back is faster.

Some info at: [timingsimplecpu-analysis-1] but highly TODO :-)

TODO These look promising:

--list-mem-types
--mem-type=MEM_TYPE
--mem-channels=MEM_CHANNELS
--mem-ranks=MEM_RANKS
--mem-size=MEM_SIZE

TODO: now to verify this with the Linux kernel? Besides raw performance benchmarks.

Now for a raw simplistic benchmark on TimingSimpleCPU without caches via [c-busy-loop]:

./run --arch aarch64 --cli-args 1000000 --emulator gem5 --userland userland/gcc/busy_loop.c -- --cpu-type TimingSimpleCPU

LKMC eb22fd3b6e7fff7e9ef946a88b208debf5b419d5 gem5 872cb227fdc0b4d60acc7840889d567a6936b6e1 outputs:

Exiting @ tick 897173931000 because exiting with last active thread context

and now because:

  • we have no caches, each instruction is fetched from memory

  • each loop contains 11 instructions as shown at [c-busy-loop]

  • and supposing that the loop dominated executable pre/post main, which we know is true since as shown in [benchmark-emulators-on-userland-executables] an empty dynamically linked C program only as about 100k instructions, while our loop runs 1000000 * 11 = 12M.

we should have about 1000000 * 11 / 897173931000 ps ~ 12260722 ~ 12MB/s of random accesses. The default memory type used is DDR3_1600_8x8 as per:

common/Options.py:101:    parser.add_option("--mem-type", type="choice", default="DDR3_1600_8x8

and according to https://en.wikipedia.org/wiki/DDR3_SDRAM that reaches 6400 MB/s so we are only off by a factor of 50x :-) TODO. Maybe if the minimum transaction if 64 bytes, we would be on point.

Another example we could use later on is userland/gcc/busy_loop.c, but then that mixes icache and dcache accesses, so the analysis is a bit more complex:

./run --arch aarch64 --cli-args 0x1000000 --emulator gem5 --userland userland/gcc/busy_loop.c -- --cpu-type TimingSimpleCPU

Can be set across emulators with:

./run --memory 512M

We can verify this on the guest directly from the kernel with:

cat /proc/meminfo

as of LKMC 1e969e832f66cb5a72d12d57c53fb09e9721d589 this output contains:

MemTotal:         498472 kB

which we expand with:

printf '0x%X\n' $((498472 * 1024))

to:

0x1E6CA000

TODO: why is this value a bit smaller than 512M?

free also gives the same result:

free -b

contains:

             total       used       free     shared    buffers     cached
Mem:     510435328   20385792  490049536          0     503808    2760704
-/+ buffers/cache:   17121280  493314048
Swap:            0          0          0

which we expand with:

printf '0x%X\n' 510435328$((498472 * 1024)

man free from Ubuntu’s procps 3.3.15 tells us that free obtains this information from /proc/meminfo as well.

From C, we can get this information with sysconf(_SC_PHYS_PAGES) or get_phys_pages():

./linux/total_memory.out

Output:

sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE) = 0x1E6CA000
sysconf(_SC_AVPHYS_PAGES) * sysconf(_SC_PAGESIZE) = 0x1D178000
get_phys_pages() * sysconf(_SC_PAGESIZE) = 0x1E6CA000
get_avphys_pages() * sysconf(_SC_PAGESIZE) = 0x1D178000

This can be explored pretty well from gem5 config.ini.

se.py just has a single DDR3_1600_8x8 DRAM with size given as Memory size and physical address starting at 0.

fs.py also has that DDR3_1600_8x8 DRAM, but can have more memory types. Notably, aarch64 has as shown on RealView.py VExpress_GEM5_Base:

0x00000000-0x03ffffff: (  0     -  64 MiB) Boot memory (CS0)
0x04000000-0x07ffffff: ( 64 MiB - 128 MiB) Reserved
0x08000000-0x0bffffff: (128 MiB - 192 MiB) NOR FLASH0 (CS0 alias)
0x0c000000-0x0fffffff: (192 MiB - 256 MiB) NOR FLASH1 (Off-chip, CS4)
0x80000000-XxXXXXXXXX: (  2 GiB -        ) DRAM

We place the entry point of our baremetal executables right at the start of DRAM with our [baremetal-linker-script].

This can be seen indirectly with:

./getvar --arch aarch64 --emulator gem5 entry_address

which gives 0x80000000 in decimal, or more directly with some some gem5 tracing:

./run \
  --arch aarch64 \
  --baremetal baremetal/arch/aarch64/no_bootloader/exit.S \
  --emulator gem5 \
  --trace ExecAll,-ExecSymbol \
  --trace-stdout \
;

and we see that the first instruction runs at 0x80000000:

      0: system.cpu: A0 T0 : 0x80000000

TODO: what are the boot memory and NOR FLASH used for?

TODO These look promising:

--ethernet-linkspeed
--ethernet-linkdelay

As of gem5 872cb227fdc0b4d60acc7840889d567a6936b6e1 defaults to 2GHz for fs.py:

    parser.add_option("--cpu-clock", action="store", type="string",
                      default='2GHz',
                      help="Clock for blocks running at CPU speed")

We can check that very easily by looking at the timestamps of a Exec trace of an gem5 AtomicSimpleCPU without any caches:

./run \
  --arch aarch64 \
  --emulator gem5 \
  --userland userland/arch/aarch64/freestanding/linux/hello.S \
  --trace-insts-stdout \
;

which shows:

      0: system.cpu: A0 T0 : @asm_main_after_prologue    :   movz   x0, #1, #0        : IntAlu :  D=0x0000000000000001  flags=(IsInteger)
    500: system.cpu: A0 T0 : @asm_main_after_prologue+4    :   adr   x1, #28            : IntAlu :  D=0x0000000000400098  flags=(IsInteger)
   1000: system.cpu: A0 T0 : @asm_main_after_prologue+8    :   ldr   w2, #4194464       : MemRead :  D=0x0000000000000006 A=0x4000a0  flags=(IsInteger|IsMemRef|IsLoad)
   1500: system.cpu: A0 T0 : @asm_main_after_prologue+12    :   movz   x8, #64, #0       : IntAlu :  D=0x0000000000000040  flags=(IsInteger)
   2000: system.cpu: A0 T0 : @asm_main_after_prologue+16    :   svc   #0x0               : IntAlu :   flags=(IsSerializeAfter|IsNonSpeculative|IsSyscall)
hello
   2500: system.cpu: A0 T0 : @asm_main_after_prologue+20    :   movz   x0, #0, #0        : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
   3000: system.cpu: A0 T0 : @asm_main_after_prologue+24    :   movz   x8, #93, #0       : IntAlu :  D=0x000000000000005d  flags=(IsInteger)
   3500: system.cpu: A0 T0 : @asm_main_after_prologue+28    :   svc   #0x0               : IntAlu :   flags=(IsSerializeAfter|IsNonSpeculative|IsSyscall)

so we see that it runs one instruction every 500 ps which makes up 2GHz.

So if we change the frequency to say 1GHz and re-run it:

./run \
  --arch aarch64 \
  --emulator gem5 \
  --userland userland/arch/aarch64/freestanding/linux/hello.S \
  --trace-insts-stdout \
  -- \
  --cpu-clock 1GHz \
;

we get as expected:

      0: system.cpu: A0 T0 : @asm_main_after_prologue    :   movz   x0, #1, #0        : IntAlu :  D=0x0000000000000001  flags=(IsInteger)
   1000: system.cpu: A0 T0 : @asm_main_after_prologue+4    :   adr   x1, #28            : IntAlu :  D=0x0000000000400098  flags=(IsInteger)
   2000: system.cpu: A0 T0 : @asm_main_after_prologue+8    :   ldr   w2, #4194464       : MemRead :  D=0x0000000000000006 A=0x4000a0  flags=(IsInteger|IsMemRef|IsLoad)
   3000: system.cpu: A0 T0 : @asm_main_after_prologue+12    :   movz   x8, #64, #0       : IntAlu :  D=0x0000000000000040  flags=(IsInteger)
   4000: system.cpu: A0 T0 : @asm_main_after_prologue+16    :   svc   #0x0               : IntAlu :   flags=(IsSerializeAfter|IsNonSpeculative|IsSyscall)
hello
   5000: system.cpu: A0 T0 : @asm_main_after_prologue+20    :   movz   x0, #0, #0        : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
   6000: system.cpu: A0 T0 : @asm_main_after_prologue+24    :   movz   x8, #93, #0       : IntAlu :  D=0x000000000000005d  flags=(IsInteger)
   7000: system.cpu: A0 T0 : @asm_main_after_prologue+28    :   svc   #0x0               : IntAlu :   flags=(IsSerializeAfter|IsNonSpeculative|IsSyscall)

As of gem5 872cb227fdc0b4d60acc7840889d567a6936b6e1, but like gem5 cache size, does not get propagated to the guest, and is not for example visible at:

ls /sys/devices/system/cpu/cpu0/cpufreq

Analogous to QEMU:

./run --arch arm --kernel-cli 'init=/lkmc/linux/poweroff.out' --emulator gem5

Internals: when we give --command-line= to gem5, it overrides default command lines, including some mandatory ones which are required to boot properly.

Our run script hardcodes the require options in the default --command-line and appends extra options given by -e.

To find the default options in the first place, we removed --command-line and ran:

./run --arch arm --emulator gem5

and then looked at the line of the Linux kernel that starts with:

Kernel command line:

Analogous to QEMU, on the first shell:

./run --arch arm --emulator gem5 --gdb-wait

On the second shell:

./run-gdb --arch arm --emulator gem5

On a third shell:

./gem5-shell

When you want to break, just do a Ctrl-C on GDB shell, and then continue.

And we now see the boot messages, and then get a shell. Now try the ./count.sh procedure described for QEMU at: Section 3.2, “GDB step debug kernel post-boot”.

We are unable to use gdbserver because of networking as mentioned at: Section 15.3.1.3, “gem5 host to guest networking”

The alternative is to do as in GDB step debug userland processes.

Next, follow the exact same steps explained at GDB step debug userland non-init without --gdb-wait, but passing --emulator gem5 to every command as usual.

But then TODO (I’ll still go crazy one of those days): for arm, while debugging ./linux/myinsmod.out hello.ko, after then line:

23     if (argc < 3) {
24         params = "";

I press n, it just runs the program until the end, instead of stopping on the next line of execution. The module does get inserted normally.

TODO:

./run-gdb --arch arm --emulator gem5 --userland gem5-1.0/gem5/util/m5/m5 main

breaks when m5 is run on guest, but does not show the source code.

gem5’s secondary core GDB setup is a hack and spawns one gdbserver for each core in separate ports, e.g. 7000, 7001, etc.

Partly because of this, it is basically unusable/very hard to use, because you can’t attach to a core that is stopped either because it hasn’t been initialized, or if you are already currently debugging another core.

This affects both full system and userland, and is described in more detail at: https://gem5.atlassian.net/browse/GEM5-626

In LKMC 0a3ce2f41f12024930bcdc74ff646b66dfc46999, we can easily test attaching to another core by passing --run-id, e.g. to connect to the second core we can use --run-id 1:

./run-gdb --arch aarch64 --emulator gem5 --userland userland/gcc/busy_loop.c --run-id 1

Analogous to QEMU’s Snapshot, but better since it can be started from inside the guest, so we can easily checkpoint after a specific guest event, e.g. just before init is done.

To see it in action try:

./run --arch aarch64 --emulator gem5

In the guest, wait for the boot to end and run:

m5 checkpoint

where gem5 m5 executable is a guest utility present inside the gem5 tree which we cross-compiled and installed into the guest.

To restore the checkpoint, kill the VM and run:

./run --arch arm --emulator gem5 --gem5-restore 1

The --gem5-restore option restores the checkpoint that was created most recently.

Let’s create a second checkpoint to see how it works, in guest:

date >f
m5 checkpoint

Kill the VM, and try it out:

./run --arch arm --emulator gem5 --gem5-restore 1

Here we use --gem5-restore 1 again, since the second snapshot we took is now the most recent one

Now in the guest:

cat f

contains the date. The file f wouldn’t exist had we used the first checkpoint with --gem5-restore 2, which is the second most recent snapshot taken.

If you automate things with Kernel command line parameters as in:

./run --arch arm --eval 'm5 checkpoint;m5 resetstats;dhrystone 1000;m5 exit' --emulator gem5

Then there is no need to pass the kernel command line again to gem5 for replay:

./run --arch arm --emulator gem5 --gem5-restore 1

since boot has already happened, and the parameters are already in the RAM of the snapshot.

In order to debug checkpoint restore bugs, this minimal setup using userland/freestanding/gem5_checkpoint.S can be handy:

./build-userland --arch aarch64 --static
./run --arch aarch64 --emulator gem5 --static --userland userland/freestanding/gem5_checkpoint.S --trace-insts-stdout
./run --arch aarch64 --emulator gem5 --static --userland userland/freestanding/gem5_checkpoint.S --trace-insts-stdout --gem5-restore 1
./run --arch aarch64 --emulator gem5 --static --userland userland/freestanding/gem5_checkpoint.S --trace-insts-stdout --gem5-restore 1 -- --cpu-type=DerivO3CPU --restore-with-cpu=DerivO3CPU --caches

On the initial run, we see that all instructions are executed and the checkpoint is taken:

      0: system.cpu: A0 T0 : @asm_main_after_prologue    :   movz   x0, #0, #0        : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
    500: system.cpu: A0 T0 : @asm_main_after_prologue+4    :   movz   x1, #0, #0        : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
   1000: system.cpu: A0 T0 : @asm_main_after_prologue+8    :   m5checkpoint             : IntAlu :   flags=(IsInteger|IsNonSpeculative|IsUnverifiable)
Writing checkpoint
warn: Checkpoints for file descriptors currently do not work.
info: Entering event queue @ 1000.  Starting simulation...
   1500: system.cpu: A0 T0 : @asm_main_after_prologue+12    :   movz   x0, #0, #0        : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
   2000: system.cpu: A0 T0 : @asm_main_after_prologue+16    :   m5exit                   : No_OpClass :   flags=(IsInteger|IsNonSpeculative)
Exiting @ tick 2000 because m5_exit instruction encountered

Then, on the first restore run, the checkpoint is restored, and only instructions after the checkpoint are executed:

info: Entering event queue @ 1000.  Starting simulation...
   1500: system.cpu: A0 T0 : @asm_main_after_prologue+12    :   movz   x0, #0, #0        : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
   2000: system.cpu: A0 T0 : @asm_main_after_prologue+16    :   m5exit                   : No_OpClass :   flags=(IsInteger|IsNonSpeculative)
Exiting @ tick 2000 because m5_exit instruction encountered

and a similar thing happens for the restore with a different CPU type:

info: Entering event queue @ 1000.  Starting simulation...
  79000: system.cpu: A0 T0 : @asm_main_after_prologue+12    :   movz   x0, #0, #0        : IntAlu :  D=0x0000000000000000  FetchSeq=1  CPSeq=1  flags=(IsInteger)
Exiting @ tick 84500 because m5_exit instruction encountered

Here we don’t see the last m5 exit instruction on the log, but it must just be something to do with the O3 logging.

A quick way to get a gem5 syscall emulation mode or full system checkpoint to observe is:

./run --arch aarch64 --emulator gem5 --baremetal userland/freestanding/gem5_checkpoint.S --trace-insts-stdout
./run --arch aarch64 --emulator gem5 --userland userland/freestanding/gem5_checkpoint.S --trace-insts-stdout

Checkpoints are stored inside the m5out directory at:

"$(./getvar --emulator gem5 m5out_dir)/cpt.<checkpoint-time>"

where <checkpoint-time> is the cycle number at which the checkpoint was taken.

fs.py exposes the -r N flag to restore checkpoints, which N-th checkpoint with the largest <checkpoint-time>: https://github.com/gem5/gem5/blob/e02ec0c24d56bce4a0d8636a340e15cd223d1930/configs/common/Simulation.py#L118

However, that interface is bad because if you had taken previous checkpoints, you have no idea what N to use, unless you memorize which checkpoint was taken at which cycle.

Therefore, just use our superior --gem5-restore flag, which uses directory timestamps to determine which checkpoint you created most recently.

The -r N integer value is just pure fs.py sugar, the backend at m5.instantiate just takes the actual tracepoint directory path as input.

The file m5out/cpt.1000/m5.cpt contains almost everything in the checkpoint except memory.

It is a Python configparser compatible file with a section structure that matches the SimObject tree e.g.:

[system.cpu.itb.walker.power_state]
currState=0
prvEvalTick=0

When a checkpoint is taken, each SimObject calls its overridden serialize method to generate the checkpoint, and when loading, unserialize is called.

You want to automate running several tests from a single pristine post-boot state.

The problem is that boot takes forever, and after the checkpoint, the memory and disk states are fixed, so you can’t for example:

  • hack up an existing rc script, since the disk is fixed

  • inject new kernel boot command line options, since those have already been put into memory by the bootloader

There is however a few loopholes, m5 readfile being the simplest, as it reads whatever is present on the host.

So we can do it like:

# Boot, checkpoint and exit.
printf 'echo "setup run";m5 exit' > "$(./getvar gem5_readfile_file)"
./run --emulator gem5 --eval 'm5 checkpoint;m5 readfile > /tmp/gem5.sh && sh /tmp/gem5.sh'

# Restore and run the first benchmark.
printf 'echo "first benchmark";m5 exit' > "$(./getvar gem5_readfile_file)"
./run --emulator gem5 --gem5-restore 1

# Restore and run the second benchmark.
printf 'echo "second benchmark";m5 exit' > "$(./getvar gem5_readfile_file)"
./run --emulator gem5 --gem5-restore 1

# If something weird happened, create an interactive shell to examine the system.
printf 'sh' > "$(./getvar gem5_readfile_file)"
./run --emulator gem5 --gem5-restore 1

Since this is such a common setup, we provide the following helpers for this operation:

  • ./run --gem5-readfile is a convenient way to set the m5 readfile file contents from a string in the command line, e.g.:

    # Boot, checkpoint and exit.
    ./run --emulator gem5 --eval './gem5.sh' --gem5-readfile 'echo "setup run"'
    
    # Restore and run the first benchmark.
    ./run --emulator gem5 --gem5-restore 1 --gem5-readfile 'echo "first benchmark"'
    
    # Restore and run the second benchmark.
    ./run --emulator gem5 --gem5-restore 1 --gem5-readfile 'echo "second benchmark"'
  • rootfs_overlay/lkmc/gem5.sh. This script is analogous to gem5’s in-tree hack_back_ckpt.rcS, but with less noise.

    Usage:

    # Boot, checkpoint and exit.
    ./run --emulator gem5 --eval './gem5.sh' --gem5-readfile 'echo "setup run"'
    
    # Restore and run the first benchmark.
    ./run --emulator gem5 --gem5-restore 1 --gem5-readfile 'echo "first benchmark"'
    
    # Restore and run the second benchmark.
    ./run --emulator gem5 --gem5-restore 1 --gem5-readfile 'echo "second benchmark"'

Their usage is also exemplified at gem5 run benchmark.

If you forgot to use an appropriate --eval for your boot and the simulation is already running, rootfs_overlay/lkmc/gem5.sh can be used directly from an interactive guest shell.

First we reset the readfile to something that runs quickly:

printf 'echo "first benchmark"' > "$(./getvar gem5_readfile_file)"

and then in the guest, take a checkpoint and exit with:

./gem5.sh

Now the guest is in a state where readfile will be executed automatically without interactive intervention:

./run --emulator gem5 --gem5-restore 1 --gem5-readfile 'echo "first benchmark"'
./run --emulator gem5 --gem5-restore 1 --gem5-readfile 'echo "second benchmark"'

Other loophole possibilities to execute different benchmarks non-interactively include:

gem5 can switch to a different CPU model when restoring a checkpoint.

A common combo is to boot Linux with a fast CPU, make a checkpoint and then replay the benchmark of interest with a slower CPU.

This can be observed interactively in full system with:

./run --arch aarch64 --emulator gem5

Then in the guest terminal after boot ends:

sh -c 'm5 checkpoint;sh'
m5 exit

And then restore the checkpoint with a different slower CPU:

./run --arch arm --emulator gem5 --gem5-restore 1 -- --caches --cpu-type=DerivO3CPU

And now you will notice that everything happens much slower in the guest terminal!

One even more direct and minimal way to observe this is with userland/freestanding/gem5_checkpoint.S which was mentioned at gem5 checkpoint userland minimal example plus some logging:

./run \
  --arch aarch64 \
  --emulator gem5 \
  --static \
  --trace ExecAll,FmtFlag,O3CPU,SimpleCPU \
  --userland userland/freestanding/gem5_checkpoint.S \
;
cat "$(./getvar --arch aarch64 --emulator gem5 trace_txt_file)"
./run \
  --arch aarch64 \
  --emulator gem5 \
  --gem5-restore 1 \
  --static \
  --trace ExecAll,FmtFlag,O3CPU,SimpleCPU \
  --userland userland/freestanding/gem5_checkpoint.S \
  -- \
  --caches \
  --cpu-type DerivO3CPU \
  --restore-with-cpu DerivO3CPU \
;
cat "$(./getvar --arch aarch64 --emulator gem5 trace_txt_file)"

At gem5 2235168b72537535d74c645a70a85479801e0651, the first run does everything in AtomicSimpleCPU:

...
      0: SimpleCPU: system.cpu.dcache_port: received snoop pkt for addr:0x1f92 WriteReq
      0: SimpleCPU: system.cpu.dcache_port: received snoop pkt for addr:0x1e40 WriteReq
      0: SimpleCPU: system.cpu.dcache_port: received snoop pkt for addr:0x1e30 WriteReq
      0: SimpleCPU: system.cpu: Tick
      0: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue    :   movz   x0, #0, #0        : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
    500: SimpleCPU: system.cpu: Tick
    500: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+4    :   movz   x1, #0, #0        : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
   1000: SimpleCPU: system.cpu: Tick
   1000: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+8    :   m5checkpoint             : IntAlu :   flags=(IsInteger|IsNonSpeculative|IsUnverifiable)
   1000: SimpleCPU: system.cpu: Resume
   1500: SimpleCPU: system.cpu: Tick
   1500: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+12    :   movz   x0, #0, #0        : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
   2000: SimpleCPU: system.cpu: Tick
   2000: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+16    :   m5exit                   : No_OpClass :   flags=(IsInteger|IsNonSpeculative)

and after restore we see as expected a single ExecEnable instruction executed amidst O3CPU noise:

FullO3CPU: Ticking main, FullO3CPU.
  79000: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+12    :   movz   x0, #0, #0        : IntAlu :  D=0x0000000000000000  FetchSeq=1  CPSeq=1  flags=(IsInteger)
  82500: O3CPU: system.cpu: Removing committed instruction [tid:0] PC (0x400084=>0x400088).(0=>1) [sn:1]
  82500: O3CPU: system.cpu: Removing instruction, [tid:0] [sn:1] PC (0x400084=>0x400088).(0=>1)
  82500: O3CPU: system.cpu: Scheduling next tick!
  83000: O3CPU: system.cpu:

which is the movz after the checkpoint. The final m5exit does not appear due to DerivO3CPU logging insanity.

Bibliography:

Besides switching CPUs after a checkpoint restore, fs.py also has the --fast-forward option to automatically run the script from the start on a less detailed CPU, and switch to a more detailed CPU at a given tick.

This is generally useless compared to checkpoint restoring because:

  • checkpoint restore allows to run multiple contents after the restore, and restoring to multiple different system states, which you almost always want to do

  • we generally don’t know the exact tick at which the region of interest will start, especially as the binaries change. It is much easier to just instrument the content with a checkoint m5op

But let’s give it a try anyway with userland/freestanding/gem5_checkpoint.S which was mentioned at gem5 checkpoint userland minimal example

./run \
  --arch aarch64 \
  --emulator gem5 \
  --static \
  --trace ExecAll,FmtFlag,O3CPU,SimpleCPU \
  --userland userland/freestanding/gem5_checkpoint.S \
  -- \
  --caches
  --cpu-type DerivO3CPU \
  --fast-forward 1000 \
;
cat "$(./getvar --arch aarch64 --emulator gem5 trace_txt_file)"

At gem5 2235168b72537535d74c645a70a85479801e0651 we see something like:

      0: O3CPU: system.switch_cpus: Creating O3CPU object.
      0: O3CPU: system.switch_cpus: Workload[0] process is 0      0: SimpleCPU: system.cpu: ActivateContext 0
      0: SimpleCPU: system.cpu.dcache_port: received snoop pkt for addr:0 WriteReq
      0: SimpleCPU: system.cpu.dcache_port: received snoop pkt for addr:0x40 WriteReq
...

      0: SimpleCPU: system.cpu.dcache_port: received snoop pkt for addr:0x1f92 WriteReq
      0: SimpleCPU: system.cpu.dcache_port: received snoop pkt for addr:0x1e40 WriteReq
      0: SimpleCPU: system.cpu.dcache_port: received snoop pkt for addr:0x1e30 WriteReq
      0: SimpleCPU: system.cpu: Tick
      0: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue    :   movz   x0, #0, #0        : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
    500: SimpleCPU: system.cpu: Tick
    500: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+4    :   movz   x1, #0, #0        : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
   1000: SimpleCPU: system.cpu: Tick
   1000: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+8    :   m5checkpoint             : IntAlu :   flags=(IsInteger|IsNonSpeculative|IsUnverifiable)
   1000: O3CPU: system.switch_cpus: [tid:0] Calling activate thread.
   1000: O3CPU: system.switch_cpus: [tid:0] Adding to active threads list
   1500: O3CPU: system.switch_cpus:

FullO3CPU: Ticking main, FullO3CPU.
   1500: O3CPU: system.switch_cpus: Scheduling next tick!
   2000: O3CPU: system.switch_cpus:

FullO3CPU: Ticking main, FullO3CPU.
   2000: O3CPU: system.switch_cpus: Scheduling next tick!
   2500: O3CPU: system.switch_cpus:

...

FullO3CPU: Ticking main, FullO3CPU.
  44500: ExecEnable: system.switch_cpus: A0 T0 : @asm_main_after_prologue+12    :   movz   x0, #0, #0        : IntAlu :  D=0x00000000000
  48000: O3CPU: system.switch_cpus: Removing committed instruction [tid:0] PC (0x400084=>0x400088).(0=>1) [sn:1]
  48000: O3CPU: system.switch_cpus: Removing instruction, [tid:0] [sn:1] PC (0x400084=>0x400088).(0=>1)
  48000: O3CPU: system.switch_cpus: Scheduling next tick!
  48500: O3CPU: system.switch_cpus:

...

We can also compare that to the same log but without --fast-forward and other CPU switch options:

      0: SimpleCPU: system.cpu.dcache_port: received snoop pkt for addr:0x1e40 WriteReq
      0: SimpleCPU: system.cpu.dcache_port: received snoop pkt for addr:0x1e30 WriteReq
      0: SimpleCPU: system.cpu: Tick
      0: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue    :   movz   x0, #0, #0        : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
    500: SimpleCPU: system.cpu: Tick
    500: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+4    :   movz   x1, #0, #0        : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
   1000: SimpleCPU: system.cpu: Tick
   1000: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+8    :   m5checkpoint             : IntAlu :   flags=(IsInteger|IsNonSpeculative|IsUnverifiable)
   1000: SimpleCPU: system.cpu: Resume
   1500: SimpleCPU: system.cpu: Tick
   1500: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+12    :   movz   x0, #0, #0        : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
   2000: SimpleCPU: system.cpu: Tick
   2000: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+16    :   m5exit                   : No_OpClass :   flags=(IsInteger|IsNonSpeculative)

Therefore, it is clear that what we wanted happen:

  • up until the tick 1000, SimpleCPU was ticking

  • after tick 1000, cpu O3CPU started ticking

Bibliography:

The in-tree util/cpt_upgrader.py is a tool to upgrade checkpoints taken from an older version of gem5 to be compatible with the newest version, so you can update gem5 without having to re-run the simulation that generated the checkpoints.

For example, whenever a system register is added in ARMv8, old checkpoints break unless upgraded.

Unfortunately, since the process is not very automated (automatable?), and requires manually patching the upgrader every time a new breaking change is done, the upgrader tends to break soon if you try to move many versions of gem5 ahead as of 2020. This is evidenced in bug reports such as this one: https://gem5.atlassian.net/browse/GEM5-472

The script can be used as:

util/cpt_upgrader.py m5out/cpt.1000/m5.cpt

This updates the m5.cpt file in-place, and a m5out/cpt.1000/m5.cpt.bak is generated as a backup of the old file.

The upgrader determines which upgrades are needed by checking the version_tags entry of the checkpoint:

[Globals]
version_tags=arm-ccregs arm-contextidr-el2 arm-gem5-gic-ext ...

Each of those tags corresponds to a Python file under util/cpt_upgraders/ e.g. util/cpt_upgraders/arm-ccregs.py.

Remember that in the gem5 command line, we can either pass options to the script being run as in:

build/X86/gem5.opt configs/examples/fs.py --some-option

or to the gem5 executable itself:

build/X86/gem5.opt --some-option configs/examples/fs.py

Pass options to the script in our setup use:

  • get help:

    ./run --emulator gem5 -- -h
  • boot with the more detailed and slow HPI CPU model:

    ./run --arch arm --emulator gem5 -- --caches --cpu-type=HPI

To pass options to the gem5 executable we expose the --gem5-exe-args option:

  • get help:

    ./run --gem5-exe-args='-h' --emulator gem5

m5ops are magic instructions which lead gem5 to do magic things, like quitting or dumping stats.

Documentation: http://gem5.org/M5ops

There are two main ways to use m5ops:

m5 is convenient if you only want to take snapshots before or after the benchmark, without altering its source code. It uses the m5ops instructions as its backend.

m5 cannot should / should not be used however:

  • in bare metal setups

  • when you want to call the instructions from inside interest points of your benchmark. Otherwise you add the syscall overhead to the benchmark, which is more intrusive and might affect results.

    Why not just hardcode some m5ops instructions as in our example instead, since you are going to modify the source of the benchmark anyway?

m5 is a guest command line utility that is installed and run on the guest, that serves as a CLI front-end for the m5ops

It is possible to guess what most tools do from the corresponding m5ops, but let’s at least document the less obvious ones here.

In LKMC we build m5 with:

./build-m5 --arch aarch64

The m5 executable can be run on User mode simulation as normal with:

./run --arch aarch64 --emulator gem5 --userland "$(./getvar --arch aarch64 out_rootfs_overlay_bin_dir)/m5" --cli-args dumpstats

This can be a good test m5ops since it executes very quickly.

End the simulation.

Sane Python scripts will exit gem5 with status 0, which is what fs.py does.

Makes gem5 dump one more statistics entry to the gem5 m5out/stats.txt file.

End the simulation with a failure exit event:

m5 fail 1

Sane Python scripts would use that as the exit status of gem5, which would be useful for testing purposes, but fs.py at 200281b08ca21f0d2678e23063f088960d3c0819 just prints an error message:

Simulated exit code not 0! Exit code is 1

and exits with status 0.

We then parse that string ourselves in run and exit with the correct status…​

TODO: it used to be like that, but it actually got changed to just print the message. Why? https://gem5-review.googlesource.com/c/public/gem5/+/4880

m5 fail is just a superset of m5 exit, which is just:

m5 fail 0

Send a guest file to the host. 9P is a more advanced alternative.

Guest:

echo mycontent > myfileguest
m5 writefile myfileguest myfilehost

Host:

cat "$(./getvar --arch aarch64 --emulator gem5 m5out_dir)/myfilehost"

Does not work for subdirectories, gem5 crashes:

m5 writefile myfileguest mydirhost/myfilehost

Read a host file pointed to by the fs.py --script option to stdout.

Host:

date > "$(./getvar gem5_readfile_file)"

Guest:

m5 readfile

Outcome: date shows on guest.

Ermm, just another m5 readfile that only takes integers and only from CLI options? Is this software so redundant?

Host:

./run --emulator gem5 --gem5-restore 1 -- --initparam 13
./run --emulator gem5 --gem5-restore 1 -- --initparam 42

Guest:

m5 initparm

Outputs the given paramter.

Trivial combination of m5 readfile + execute the script.

Host:

printf '#!/bin/sh
echo asdf
' > "$(./getvar gem5_readfile_file)"

Guest:

touch /tmp/execfile
chmod +x /tmp/execfile
m5 execfile

Outcome:

adsf

There are few different possible instructions that can be used to implement identical m5ops:

All of those those methods are exposed through the gem5 m5 executable in-tree executable. You can select which method to use when calling the executable, e.g.:

m5 exit
# Same as the above.
m5 --inst exit
# The address is mandatory if not configured at build time.
m5 --addr 0x10010000 exit
m5 --semi exit

To make things simpler to understand, you can play around with our own minimized educational m5 subset:

The instructions used by ./c/m5ops.out are present in lkmc/m5ops.h in a very simple to understand and reuse inline assembly form.

To use that file, first rebuild m5ops.out with the m5ops instructions enabled and install it on the root filesystem:

./build-userland \
  --arch aarch64 \
  --force-rebuild \
  userland/c/m5ops.c \
;
./build-buildroot --arch aarch64

We don’t enable -DLKMC_M5OPS_ENABLE=1 by default on userland executables because we try to use a single image for both gem5, QEMU and native, and those instructions would break the latter two. We enable it in the Baremetal setup by default since we already have different images for QEMU and gem5 there.

Then, from inside gem5 Buildroot setup, test it out with:

# checkpoint
./c/m5ops.out c

# dumpstats
./c/m5ops.out d

# exit
./c/m5ops.out e

# dump resetstats
./c/m5ops.out r

In theory, the cleanest way to add m5ops to your benchmarks would be to do exactly what the m5 tool does:

However, I think it is usually not worth the trouble of hacking up the build system of the benchmark to do this, and I recommend just hardcoding in a few raw instructions here and there, and managing it with version control + sed.

Bibliography:

These are magic addresses that when accessed lead to an m5op.

The base address is given by system.m5ops_base, and then each m5op happens at a different address offset form that base.

If system.m5ops_base is 0, then the memory m5ops are disabled.

Note that the address is physical, and therefore when running in full system on top of the Linux kernel, you must first map a virtual to physical address with /dev/mem as mentioned at: Userland physical address experiments.

One advantage of this method is that it can work with gem5 KVM, whereas the magic instructions don’t, since the host cannot handle them and it is hard to hook into that.

As of gem5 0d5a80cb469f515b95e03f23ddaf70c9fd2ecbf2, fs.py --baremetal disables the memory m5ops however for some reason, therefore you should run that program as:

./run --arch aarch64 --baremetal baremetal/arch/aarch64/no_bootloader/m5_exit_addr.S --emulator gem5 --trace-insts-stdout -- --param 'system.m5ops_base=0x10010000'

TODO failing with:

info: Entering event queue @ 0.  Starting simulation...
fatal: Unable to find destination for [0x10012100:0x10012108] on system.iobus

Let’s study how the gem5 m5 executable uses them:

We notice that there are two different implementations for each arch:

  • magic instructions, which don’t exist in the corresponding arch

  • magic memory addresses on a given page: m5ops magic addresses

Then, in aarch64 magic instructions for example, the lines:

.macro  m5op_func, name, func, subfunc
        .globl \name
        \name:
        .long 0xff000110 | (\func << 16) | (\subfunc << 12)
        ret

define a simple function function for each m5op. Here we see that:

  • 0xff000110 is a base mask for the magic non-existing instruction

  • \func and \subfunc are OR-applied on top of the base mask, and define m5op this is.

    Those values will loop over the magic constants defined in m5ops.h with the deferred preprocessor idiom.

    For example, exit is 0x21 due to:

    #define M5OP_EXIT               0x21

Finally, m5.c calls the defined functions as in:

m5_exit(ints[0]);

Therefore, the runtime "argument" that gets passed to the instruction, e.g. the delay in ticks until the exit for m5 exit, gets passed directly through the aarch64 calling convention.

Keep in mind that for all archs, m5.c does the calls with 64-bit integers:

uint64_t ints[2] = {0,0};
parse_int_args(argc, argv, ints, argc);
m5_fail(ints[1], ints[0]);

Therefore, for example:

  • aarch64 uses x0 for the first argument and x1 for the second, since each is 64 bits log already

  • arm uses r0 and r1 for the first argument, and r2 and r3 for the second, since each register is only 32 bits long

That convention specifies that x0 to x7 contain the function arguments, so x0 contains the first argument, and x1 the second.

In our m5ops example, we just hardcode everything in the assembly one-liners we are producing.

We ignore the \subfunc since it is always 0 on the ops that interest us.

include/gem5/asm/generic/m5ops.h also describes some annotation instructions.

https://gem5.googlesource.com/arm/linux/ contains an ARM Linux kernel forks with a few gem5 specific Linux kernel patches on top of mainline created by ARM Holdings on top of a few upstream kernel releases.

Our build script automatically adds that remote for us as gem5-arm.

The patches are optional: the vanilla kernel does boot. But they add some interesting gem5-specific optimizations, instrumentations and device support.

The patches also add defconfigs that are known to work well with gem5.

In order to use those patches and their associated configs, and, we recommend using [linux-kernel-build-variants] as:

git -C "$(./getvar linux_source_dir)" fetch gem5-arm:gem5/v4.15
git -C "$(./getvar linux_source_dir)" checkout gem5/v4.15
./build-linux \
  --arch aarch64 \
  --custom-config-file-gem5 \
  --linux-build-id gem5-v4.15 \
;
git -C "$(./getvar linux_source_dir)" checkout -
./run \
  --arch aarch64 \
  --emulator gem5 \
  --linux-build-id gem5-v4.15 \
;

QEMU also boots that kernel successfully:

./run \
  --arch aarch64 \
  --linux-build-id gem5-v4.15 \
;

but glibc kernel version checks make init fail with:

FATAL: kernel too old

because glibc was built to expect a newer Linux kernel as shown at: Section 11.4.1, “FATAL: kernel too old failure in userland simulation”. Your choices to solve this are:

  • see if there is a more recent gem5 kernel available, or port your patch of interest to the newest kernel

  • modify this repo to use uClibc, which is not hard because of Buildroot

  • patch glibc to remove that check, which is easy because glibc is in a submodule of this repo

It is obviously not possible to understand what the Linux kernel fork commits actually do from their commit message, so let’s explain them one by one here as we understand them:

Tested on 649d06d6758cefd080d04dc47fd6a5a26a620874 + 1.

We have observed that with the kernel patches, boot is 2x faster, falling from 1m40s to 50s.

With ts, we see that a large part of the difference is at the message:

clocksource: Switched to clocksource arch_sys_counter

which takes 4s on the patched kernel, and 30s on the unpatched one! TODO understand why, especially if it is a config difference, or if it actually comes from a patch.

When you run gem5, it generates an m5out directory at:

echo $(./getvar --arch arm --emulator gem5 m5out_dir)"

The location of that directory can be set with ./gem5.opt -d, and defaults to ./m5out.

The files in that directory contains some very important information about the run, and you should become familiar with every one of them.

Contains UART output, both from the Linux kernel or from the baremetal system.

Can also be seen live on m5term.

This file used to be called just m5out/system.dmesg, but the name was changed after the workload refactorings of March 2020.

This file is capable of showing terminal messages that are printk before the serial is enabled as described at: Linux kernel early boot messages.

The file is dumped only on kernel panics which gem5 can detect by the PC address: Exit gem5 on panic.

This mechanism can be very useful to debug the Linux kernel boot if problems happen before the serial is enabled.

This magic mechanism works by activating an event when the PC reaches the printk address, much like gem5 can detect panic by PC and then parsing printk function arguments and buffers!

The relevant source is at src/kern/linux/printk.c.

We can test this mechanism in a controlled way by hacking a panic() into the kernel next to a printk that shows up before the serial is enabled, e.g. on Linux v5.4.3 we could do:

diff --git a/kernel/trace/ftrace.c b/kernel/trace/ftrace.c
index f296d89be757..3e79916322c2 100644
--- a/kernel/trace/ftrace.c
+++ b/kernel/trace/ftrace.c
@@ -6207,6 +6207,7 @@ void __init ftrace_init(void)

    pr_info("ftrace: allocating %ld entries in %ld pages\n",
        count, count / ENTRIES_PER_PAGE + 1);
+   panic("foobar");

    last_ftrace_enabled = ftrace_enabled = 1;

With this, after the panic, system.workload.dmesg contains on LKMC d09a0d97b81582cc88381c4112db631da61a048d aarch64:

[0.000000] Booting Linux on physical CPU 0x0000000000 [0x410fd070]
[0.000000] Linux version 5.4.3-dirty (lkmc@f7688b48ac46e9a669e279f1bc167722d5141eda) (gcc version 8.3.0 (Buildroot 2019.11-00002-g157ac499cf)) #1 SMP Thu Jan 1 00:00:00 UTC 1970
[0.000000] Machine model: V2P-CA15
[0.000000] Memory limited to 256MB
[0.000000] efi: Getting EFI parameters from FDT:
[0.000000] efi: UEFI not found.
[0.000000] On node 0 totalpages: 65536
[0.000000]   DMA32 zone: 1024 pages used for memmap
[0.000000]   DMA32 zone: 0 pages reserved
[0.000000]   DMA32 zone: 65536 pages, LIFO batch:15
[0.000000] percpu: Embedded 29 pages/cpu s79960 r8192 d30632 u118784
[0.000000] pcpu-alloc: s79960 r8192 d30632 u118784 alloc=29*4096
[0.000000] pcpu-alloc: [0] 0
[0.000000] Detected PIPT I-cache on CPU0
[0.000000] CPU features: detected: ARM erratum 832075
[0.000000] CPU features: detected: EL2 vector hardening
[0.000000] ARM_SMCCC_ARCH_WORKAROUND_1 missing from firmware
[0.000000] Built 1 zonelists, mobility grouping on.  Total pages: 64512
[0.000000] Kernel command line: earlyprintk=pl011,0x1c090000 lpj=19988480 rw loglevel=8 mem=256MB root=/dev/sda console_msg_format=syslog nokaslr norandmaps panic=-1 printk.devkmsg=on printk.time=y rw console=ttyAMA0 - lkmc_home=/lkmc
[0.000000] Dentry cache hash table entries: 32768 (order: 6, 262144 bytes, linear)
[0.000000] Inode-cache hash table entries: 16384 (order: 5, 131072 bytes, linear)
[0.000000] mem auto-init: stack:off, heap alloc:off, heap free:off
[0.000000] Memory: 233432K/262144K available (6652K kernel code, 792K rwdata, 2176K rodata, 896K init, 659K bss, 28712K reserved, 0K cma-reserved)
[0.000000] SLUB: HWalign=64, Order=0-3, MinObjects=0, CPUs=1, Nodes=1
[0.000000] ftrace: allocating 22067 entries in 87 pages

So we see that messages up to the ftrace do show up!

This file contains important statistics about the run:

cat "$(./getvar --arch aarch64 m5out_dir)/stats.txt"

Whenever we run m5 dumpstats or when fs.py and se.py are exiting (TODO other scripts?), a section with the following format is added to that file:

---------- Begin Simulation Statistics ----------
[the stats]
---------- End Simulation Statistics   ----------

That file contains several important execution metrics, e.g. number of cycles and several types of cache misses:

system.cpu.numCycles
system.cpu.dtb.inst_misses
system.cpu.dtb.inst_hits

For x86, it is interesting to try and correlate numCycles with:

In LKMC f42c525d7973d70f4c836d2169cc2bd2893b4197 gem5 5af26353b532d7b5988cf0f6f3d0fbc5087dd1df, the stat file for a [c] hello world:

./run --arch aarch64 --emulator gem5 --userland userland/c/hello.c

which has a single dump done at the exit, has size 59KB and stat lines of form:

final_tick                                   91432000                       # Number of ticks from beginning of simulation (restored from checkpoints and never reset)

We can reduce the file size by adding the ?desc=False magic suffix to the stat flie name:

--stats-file stats.txt?desc=false

as explained in:

gem5.opt --stats-help

and this reduces the file size to 39KB by removing those excessive comments:

final_tick                                   91432000

although trailing spaces are still prse

We can further reduce this size by removing spaces from the dumps with this hack:

         ccprintf(stream, " |%12s %10s %10s",
                  ValueToString(value, precision), pdfstr.str(), cdfstr.str());
     } else {
-        ccprintf(stream, "%-40s %12s %10s %10s", name,
-                 ValueToString(value, precision), pdfstr.str(), cdfstr.str());
+        ccprintf(stream, "%s %s", name, ValueToString(value, precision));
+        if (pdfstr.rdbuf()->in_avail())
+            stream << " " << pdfstr.str();
+        if (cdfstr.rdbuf()->in_avail())
+            stream << " " << cdfstr.str();

         if (descriptions) {
             if (!desc.empty())

and after that the file size went down to 21KB.

We can make gem5 dump statistics in the [hdf5] format by adding the magic h5:// prefix to the file name as in:

gem5.opt --stats-file h5://stats.h5

as explained in:

gem5.opt --stats-help

This is not exposed in LKMC f42c525d7973d70f4c836d2169cc2bd2893b4197 however, you just have to hack the gem5 CLI for now.

TODO what is the advantage? The generated file for --stats-file h5://stats.h5?desc=False in LKMC f42c525d7973d70f4c836d2169cc2bd2893b4197 gem5 5af26353b532d7b5988cf0f6f3d0fbc5087dd1df for a single dump was 946K, so much larger than the text version seen at gem5 m5out/stats.txt file which was only 59KB max!

We then try to see if it is any better when you have a bunch of dump events:

./run --arch aarch64 --emulator gem5 --userland userland/c/m5ops.c --cli-args 'd 1000'

and there yes, we see that the file size fell from 39MB on stats.txt to 3.2MB on stats.m5, so the increase observed previously was just due to some initial size overhead (considering the patched gem5 with no spaces in the text file).

We also note however that the stat dump made the such a simulation that just loops and dumps considerably slower, from 3s to 15s on [p51]. Fascinating, we are definitely not disk bound there.

We enable HDF5 on the build by default with USE_HDF5=1. To disable it, you can add USE_HDF5=0 to the build as in:

./build-gem5 -- USE_HDF5=0

Library support is automatically detected, and only built if you have it installed. But there have been some compilation bugs with HDF5, which is why you might want to turn it off sometimes, e.g.: https://gem5.atlassian.net/browse/GEM5-365

Well, run minimal examples, and reverse engineer them up!

./run \
  --arch aarch64 \
  --emulator gem5 \
  --userland userland/arch/aarch64/freestanding/linux/hello.S \
  --trace ExecAll \
  --trace-stdout \
;

which gives:

      0: system.cpu: A0 T0 : @_start    :   movz   x0, #1, #0        : IntAlu :  D=0x0000000000000001  flags=(IsInteger)
    500: system.cpu: A0 T0 : @_start+4    :   adr   x1, #28            : IntAlu :  D=0x0000000000400098  flags=(IsInteger)
   1000: system.cpu: A0 T0 : @_start+8    :   ldr   w2, #4194464       : MemRead :  D=0x0000000000000006 A=0x4000a0  flags=(IsInteger|IsMemRef|IsLoad)
   1500: system.cpu: A0 T0 : @_start+12    :   movz   x8, #64, #0       : IntAlu :  D=0x0000000000000040  flags=(IsInteger)
   2000: system.cpu: A0 T0 : @_start+16    :   svc   #0x0               : IntAlu :   flags=(IsSerializeAfter|IsNonSpeculative|IsSyscall)
   2500: system.cpu: A0 T0 : @_start+20    :   movz   x0, #0, #0        : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
   3000: system.cpu: A0 T0 : @_start+24    :   movz   x8, #93, #0       : IntAlu :  D=0x000000000000005d  flags=(IsInteger)
   3500: system.cpu: A0 T0 : @_start+28    :   svc   #0x0               : IntAlu :   flags=(IsSerializeAfter|IsNonSpeculative|IsSyscall)

The most important stat of all is usually the cycle count, which is a direct measure of performance if you modelled you system well:

sim_ticks 3500 # Number of ticks simulated

Next, sim_insts and sim_ops are often critical:

sim_insts 6 # Number of instructions simulated
sim_ops   6 # Number of ops (including micro ops) simulated

sim_ops is like sim_insts but it also includes [gem5-microops].

In gem5 syscall emulation mode, syscall instructions are magic, and therefore appear to not be counted, that is why we get 6 instructions instead of 8.

This describes the internals of the gem5 m5out/stats.txt file.

GDB call stack to dumpstats:

Stats::pythonDump () at build/ARM/python/pybind11/stats.cc:58
Stats::StatEvent::process() ()
GlobalEvent::BarrierEvent::process (this=0x555559fa6a80) at build/ARM/sim/global_event.cc:131
EventQueue::serviceOne (this=this@entry=0x555558c36080) at build/ARM/sim/eventq.cc:228
doSimLoop (eventq=0x555558c36080) at build/ARM/sim/simulate.cc:219
simulate (num_cycles=<optimized out>) at build/ARM/sim/simulate.cc:132

Stats::pythonDump does:

void
pythonDump()
{
    py::module m = py::module::import("m5.stats");
    m.attr("dump")();
}

This calls src/python/m5/stats/init.py in def dump does the main dumping

That function does notably:

    for output in outputList:
        if output.valid():
            output.begin()
            for stat in stats_list:
                stat.visit(output)
            output.end()

begin and end are defined in C++ and output the header and tail respectively

void
Text::begin()
{
    ccprintf(*stream, "\n---------- Begin Simulation Statistics ----------\n");
}

void
Text::end()
{
    ccprintf(*stream, "\n---------- End Simulation Statistics   ----------\n");
    stream->flush();
}

stats_list contains the stats, and stat.visit prints them, outputList contains by default just the text output. I don’t see any other types of output in gem5, but likely JSON / binary formats could be envisioned.

Tested in gem5 b4879ae5b0b6644e6836b0881e4da05c64a6550d.

The m5out/config.ini file, contains a very good high level description of the system:

less $(./getvar --arch arm --emulator gem5 m5out_dir)"

That file contains a tree representation of the system, sample excerpt:

[root]
type=Root
children=system
full_system=true

[system]
type=ArmSystem
children=cpu cpu_clk_domain
auto_reset_addr_64=false
semihosting=Null

[system.cpu]
type=AtomicSimpleCPU
children=dstage2_mmu dtb interrupts isa istage2_mmu itb tracer
branchPred=Null

[system.cpu_clk_domain]
type=SrcClockDomain
clock=500

Each node has:

  • a list of child nodes, e.g. system is a child of root, and both cpu and cpu_clk_domain are children of system

  • a list of parameters, e.g. system.semihosting is Null, which means that [semihosting] was turned off

Set custom configs with the --param option of fs.py, e.g. we can make gem5 wait for GDB to connect with:

fs.py --param 'system.cpu[0].wait_for_remote_gdb = True'

More complex settings involving new classes however require patching the config files, although it is easy to hack this up. See for example: patches/manual/gem5-semihost.patch.

Modifying the config.ini file manually does nothing since it gets overwritten every time.

The m5out/config.dot file contains a graphviz .dot file that provides a simplified graphical view of a subset of the gem5 config.ini.

This file gets automatically converted to .svg and .pdf, which you can view after running gem5 with:

xdg-open "$(./getvar --arch arm --emulator gem5 m5out_dir)/config.dot.pdf"
xdg-open "$(./getvar --arch arm --emulator gem5 m5out_dir)/config.dot.svg"

An example of such file can be seen at: [config-dot-svg-timingsimplecpu].

On Ubuntu 20.04, you can also see the dot file "directly" with xdot:

xdot "$(./getvar --arch arm --emulator gem5 m5out_dir)/config.dot"

which is kind of really cool because it allows you to view graph arrows on hover. This can be very useful because the PDF and SVG often overlap so many arrows together that you just can’t know which one is coming from/going to where.

It is worth noting that if you are running a bunch of short simulations, dot/SVG/PDF generation could have a significant impact in simulation startup time, so it is something to watch out for. As per https://gem5-review.googlesource.com/c/public/gem5/+/29232 it can be turned off with:

gem5.opt --dot-config=''

or in LKMC:

./run --gem5-exe-args='--dot-config= --json-config= --dump-config='

The time difference can be readily observed on minimal examples by running gem5 with time.

By looking into gem5 872cb227fdc0b4d60acc7840889d567a6936b6e1 src/python/m5/util/dot_writer.py are can try to remove the SVG/PDF conversion to see if those dominate the runtime:

def do_dot(root, outdir, dotFilename):
    if not pydot:
        warn("No dot file generated. " +
             "Please install pydot to generate the dot file and pdf.")
        return
    # * use ranksep > 1.0 for for vertical separation between nodes
    # especially useful if you need to annotate edges using e.g. visio
    # which accepts svg format
    # * no need for hoizontal separation as nothing moves horizonally
    callgraph = pydot.Dot(graph_type='digraph', ranksep='1.3')
    dot_create_nodes(root, callgraph)
    dot_create_edges(root, callgraph)
    dot_filename = os.path.join(outdir, dotFilename)
    callgraph.write(dot_filename)
    try:
        # dot crashes if the figure is extremely wide.
        # So avoid terminating simulation unnecessarily
        callgraph.write_svg(dot_filename + ".svg")
        callgraph.write_pdf(dot_filename + ".pdf")
    except:
        warn("failed to generate dot output from %s", dot_filename)

but nope, they don’t, dot_create_nodes and dot_create_edges are the culprits, so the only way to gain speed is to remove .dot generation altogether. It is tempting to do this by default on LKMC and add an option to enable dot generation when desired so we can be a bit faster by default…​ but I’m lazy to document the option right now. When it annoys me further maybe :-)

We use the m5term in-tree executable to connect to the terminal instead of a direct telnet.

If you use telnet directly, it mostly works, but certain interactive features don’t, e.g.:

  • up and down arrows for history navigation

  • tab to complete paths

  • Ctrl-C to kill processes

TODO understand in detail what m5term does differently than telnet.

We have made a crazy setup that allows you to just cd into submodules/gem5, and edit Python scripts directly there.

This is not normally possible with Buildroot, since normal Buildroot packages first copy files to the output directory ($(./getvar -a <arch> buildroot_build_build_dir)/<pkg>), and then build there.

So if you modified the Python scripts with this setup, you would still need to ./build to copy the modified files over.

For gem5 specifically however, we have hacked up the build so that we cd into the submodules/gem5 tree, and then do an out of tree build to out/common/gem5.

Another advantage of this method is the we factor out the arm and aarch64 gem5 builds which are identical and large, as well as the smaller arch generic pieces.

Using Buildroot for gem5 is still convenient because we use it to:

  • to cross build m5 for us

  • check timestamps and skip the gem5 build when it is not requested

The out of build tree is required, because otherwise Buildroot would copy the output build of all archs to each arch directory, resulting in arch^2 build copies, which is significant.

By default, we use configs/example/fs.py script.

The --gem5-script biglittle option enables the alternative configs/example/arm/fs_bigLITTLE.py script instead:

./run --arch aarch64 --emulator gem5 --gem5-script biglittle

Advantages over fs.py:

  • more representative of mobile ARM SoCs, which almost always have big little cluster

  • simpler than fs.py, and therefore easier to understand and modify

Disadvantages over fs.py:

  • only works for ARM, not other archs

  • not as many configuration options as fs.py, many things are hardcoded

We setup 2 big and 2 small CPUs, but cat /proc/cpuinfo shows 4 identical CPUs instead of 2 of two different types, likely because gem5 does not expose some informational register much like the caches: https://www.mail-archive.com/[email protected]/msg15426.html gem5 config.ini does show that the two big ones are DerivO3CPU and the small ones are MinorCPU.

TODO: why is the --dtb required despite fs_bigLITTLE.py having a DTB generation capability? Without it, nothing shows on terminal, and the simulation terminates with simulate() limit reached @ 18446744073709551615. The magic vmlinux.vexpress_gem5_v1.20170616 works however without a DTB.

All those tests could in theory be added to this repo instead of to gem5, and this is actually the superior setup as it is cross emulator.

But can the people from the project be convinced of that?

These are just very small GTest tests that test a single class in isolation, they don’t run any executables.

Build the unit tests and run them:

./build-gem5 --unit-tests

Running individual unit tests is not yet exposed, but it is easy to do: while running the full tests, GTest prints each test command being run, e.g.:

/path/to/build/ARM/base/circlebuf.test.opt --gtest_output=xml:/path/to/build/ARM/unittests.opt/base/circlebuf.test.xml
[==========] Running 4 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 4 tests from CircleBufTest
[ RUN      ] CircleBufTest.BasicReadWriteNoOverflow
[       OK ] CircleBufTest.BasicReadWriteNoOverflow (0 ms)
[ RUN      ] CircleBufTest.SingleWriteOverflow
[       OK ] CircleBufTest.SingleWriteOverflow (0 ms)
[ RUN      ] CircleBufTest.MultiWriteOverflow
[       OK ] CircleBufTest.MultiWriteOverflow (0 ms)
[ RUN      ] CircleBufTest.PointerWrapAround
[       OK ] CircleBufTest.PointerWrapAround (0 ms)
[----------] 4 tests from CircleBufTest (0 ms total)

[----------] Global test environment tear-down
[==========] 4 tests from 1 test case ran. (0 ms total)
[  PASSED  ] 4 tests.

so you can just copy paste the command.

Building individual tests is possible with --unit-test (singular, no 's'):

./build-gem5 --unit-test base/circlebuf.test

This does not run the test however.

Note that the command and it’s corresponding results don’t need to show consecutively on stdout because tests are run in parallel. You just have to match them based on the class name CircleBufTest to the file circlebuf.test.cpp.

This section is about running the gem5 in-tree tests.

Running the larger 2019 regression tests is exposed for example with:

./build-gem5 --arch aarch64
./gem5-regression --arch aarch64 -- --length quick --length long

Sample run time: 87 minutes on [p51] Ubuntu 20.04 gem5 872cb227fdc0b4d60acc7840889d567a6936b6e1.

After the first run has downloaded the test binaries for you, you can speed up the process a little bit by skipping an useless SCons call:

./gem5-regression --arch aarch64 -- --length quick --length long --skip-build

Note however that running without --skip-build is required at least once to download the test binaries, because the test interface is bad.

List available instead of running them:

./gem5-regression --arch aarch64 --cmd list -- --length quick --length long

You can then pick one suite (has to be a suite, not an "individual test") from the list and run just it e.g. with:

./gem5-regression --arch aarch64 -- --uid SuiteUID:tests/gem5/cpu_tests/test.py:cpu_test_AtomicSimpleCPU_Bubblesort-ARM-opt

This error happens when the following instruction limits are reached:

system.cpu[0].max_insts_all_threads
system.cpu[0].max_insts_any_thread

If the parameter is not set, it defaults to 0, which is magic and means the huge maximum value of uint64_t: 0xFFFFFFFFFFFFFFFF, which in practice would require a very long simulation if at least one CPU were live.

So this usually means all CPUs are in a sleep state, and no events are scheduled in the future, which usually indicates a bug in either gem5 or guest code, leading gem5 to blow up.

Still, fs.py at gem5 08c79a194d1a3430801c04f37d13216cc9ec1da3 does not exit with non-zero status due to this…​ and so we just parse it out just as for m5 fail…​

A trivial and very direct way to see message would be:

./run \
  --emulator gem5 \
  --userland userland/arch/x86_64/freestanding/linux/hello.S \
  --trace-insts-stdout \
  -- \
  --param 'system.cpu[0].max_insts_all_threads = 3' \
;

which as of lkmc 402059ed22432bb351d42eb10900e5a8e06aa623 runs only the first three instructions and quits!

info: Entering event queue @ 0.  Starting simulation...
      0: system.cpu A0 T0 : @asm_main_after_prologue    : mov   rdi, 0x1
      0: system.cpu A0 T0 : @asm_main_after_prologue.0  :   MOV_R_I : limm   rax, 0x1 : IntAlu :  D=0x0000000000000001  flags=(IsInteger|IsMicroop|IsLastMicroop|IsFirstMicroop)
   1000: system.cpu A0 T0 : @asm_main_after_prologue+7    : mov rdi, 0x1
   1000: system.cpu A0 T0 : @asm_main_after_prologue+7.0  :   MOV_R_I : limm   rdi, 0x1 : IntAlu :  D=0x0000000000000001  flags=(IsInteger|IsMicroop|IsLastMicroop|IsFirstMicroop)
   2000: system.cpu A0 T0 : @asm_main_after_prologue+14    : lea        rsi, DS:[rip + 0x19]
   2000: system.cpu A0 T0 : @asm_main_after_prologue+14.0  :   LEA_R_P : rdip   t7, %ctrl153,  : IntAlu :  D=0x000000000040008d  flags=(IsInteger|IsMicroop|IsDelayedCommit|IsFirstMicroop)
   2500: system.cpu A0 T0 : @asm_main_after_prologue+14.1  :   LEA_R_P : lea   rsi, DS:[t7 + 0x19] : IntAlu :  D=0x00000000004000a6  flags=(IsInteger|IsMicroop|IsLastMicroop)
Exiting @ tick 3000 because all threads reached the max instruction count

The exact same can be achieved with the older hardcoded --maxinsts mechanism present in se.py and fs.py:

./run \
  --emulator gem5 \
  --userland \userland/arch/x86_64/freestanding/linux/hello.S \
  --trace-insts-stdout \
  -- \
  --maxinsts 3
;

Other related fs.py options are:

  • --abs-max-tick: set the maximum guest simulation time. The same scale as the ExecAll trace is used. E.g., for the above example with 3 instructions, the same trace would be achieved with a value of 3000.

The message also shows on User mode simulation deadlocks, for example in userland/posix/pthread_deadlock.c:

./run \
  --emulator gem5 \
  --userland userland/posix/pthread_deadlock.c \
  --cli-args 1 \
;

ends in:

Exiting @ tick 18446744073709551615 because simulate() limit reached

where 18446744073709551615 is 0xFFFFFFFFFFFFFFFF in decimal.

And there is a [baremetal] example at baremetal/arch/aarch64/no_bootloader/wfe_loop.S that dies on WFE:

./run \
  --arch aarch64 \
  --baremetal baremetal/arch/aarch64/no_bootloader/wfe_loop.S \
  --emulator gem5 \
  --trace-insts-stdout \
;

which gives:

info: Entering event queue @ 0.  Starting simulation...
      0: system.cpu A0 T0 : @lkmc_start    :   wfe                      : IntAlu :  D=0x0000000000000000  flags=(IsSerializeAfter|IsNonSpeculative|IsQuiesce|IsUnverifiable)
   1000: system.cpu A0 T0 : @lkmc_start+4    :   b   <lkmc_start>         : IntAlu :   flags=(IsControl|IsDirectControl|IsUncondControl)
   1500: system.cpu A0 T0 : @lkmc_start    :   wfe                      : IntAlu :  D=0x0000000000000000  flags=(IsSerializeAfter|IsNonSpeculative|IsQuiesce|IsUnverifiable)
Exiting @ tick 18446744073709551615 because simulate() limit reached

Other examples of the message:

In order to use different build options, you might also want to use [gem5-build-variants] to keep the build outputs separate from one another.

How to use it in LKMC: Section 23.8, “Debug the emulator”.

If you build gem5 with scons build/ARM/gem5.debug, then that is a .debug build.

It relates to the more common .opt build just as explained at Section 23.8, “Debug the emulator”: both .opt and .debug have -g, but .opt uses -O2 while .debug uses -O0.

./build-gem5 --gem5-build-type fast

Disables debug symbols (no -g) for some reason.

Benchmarks present at:

Profiling builds as of 3cea7d9ce49bda49c50e756339ff1287fd55df77 both use: -g -O3 and disable asserts and logging like the gem5 fast build and:

  • prof uses -pg for gprof

  • perf uses -lprofile for google-pprof

Profiling techniques are discussed in more detail at: [profiling-userland-programs].

For the prof build, you can get the gmon.out file with:

./run --arch aarch64 --emulator gem5 --userland userland/c/hello.c --gem5-build-type prof
gprof "$(./getvar --arch aarch64 gem5_executable)" > tmp.gprof

TODO test properly, benchmark vs GCC.

sudo apt-get install clang
./build-gem5 --gem5-clang
./run --emulator gem5 --gem5-clang

If there gem5 appears to have a C++ undefined behaviour bug, which is often very difficult to track down, you can try to build it with the following extra SCons options:

./build-gem5 --gem5-build-id san --verbose -- --with-ubsan --without-tcmalloc

This will make GCC do a lot of extra sanitation checks at compile and run time.

As a result, the build and runtime will be way slower than normal, but that still might be the fastest way to solve undefined behaviour problems.

Ideally, we should also be able to run it with asan with --with-asan, but if we try then the build fails at gem5 16eeee5356585441a49d05c78abc328ef09f7ace (with two ubsan trivial fixes I’ll push soon):

=================================================================
==9621==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 371712 byte(s) in 107 object(s) allocated from:
    #0 0x7ff039804448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
    #1 0x7ff03950d065 in dictresize ../Objects/dictobject.c:643

Direct leak of 23728 byte(s) in 26 object(s) allocated from:
    #0 0x7ff039804448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
    #1 0x7ff03945e40d in _PyObject_GC_Malloc ../Modules/gcmodule.c:1499
    #2 0x7ff03945e40d in _PyObject_GC_Malloc ../Modules/gcmodule.c:1493

Direct leak of 2928 byte(s) in 43 object(s) allocated from:
    #0 0x7ff03980487e in __interceptor_realloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c87e)
    #1 0x7ff03951d763 in list_resize ../Objects/listobject.c:62
    #2 0x7ff03951d763 in app1 ../Objects/listobject.c:277
    #3 0x7ff03951d763 in PyList_Append ../Objects/listobject.c:289

Direct leak of 2002 byte(s) in 3 object(s) allocated from:
    #0 0x7ff039804448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
    #1 0x7ff0394fd813 in PyString_FromStringAndSize ../Objects/stringobject.c:88
    #2 0x7ff0394fd813 in PyString_FromStringAndSize ../Objects/stringobject.c:
    Direct leak of 40 byte(s) in 2 object(s) allocated from
    #0 0x7ff039804448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
    #1 0x7ff03951ea4b in PyList_New ../Objects/listobject.c:152

Indirect leak of 10384 byte(s) in 11 object(s) allocated from
    #0 0x7ff039804448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448
    #1 0x7ff03945e40d in _PyObject_GC_Malloc ../Modules/gcmodule.c:
    #2 0x7ff03945e40d in _PyObject_GC_Malloc ../Modules/gcmodule.c:1493

Indirect leak of 4089 byte(s) in 6 object(s) allocated from:
    #0 0x7ff039804448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
    #1 0x7ff0394fd648 in PyString_FromString ../Objects/stringobject.c:143

Indirect leak of 2090 byte(s) in 3 object(s) allocated from:
    #0 0x7ff039804448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448
    #1 0x7ff0394eb36f in type_new ../Objects/typeobject.c:
    #2 0x7ff0394eb36f in type_new ../Objects/typeobject.c:2094
Indirect leak of 1346 byte(s) in 2 object(s) allocated from:
    #0 0x7ff039804448 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c448)
    #1 0x7ff0394fd813 in PyString_FromStringAndSize ../Objects/stringobject.c:
    #2 0x7ff0394fd813 in PyString_FromStringAndSize ../Objects/stringobject.c:
    SUMMARY: AddressSanitizer: 418319 byte(s) leaked in 203 allocation(s).

From the message, this appears however to be a Python / pyenv11 bug however and not in gem5 specifically. I think it worked when I tried it in the past in an older gem5 / Ubuntu.

--without-tcmalloc is needed / a good idea when using --with-asan: https://stackoverflow.com/questions/42712555/address-sanitizer-fsanitize-address-works-with-tcmalloc since both do more or less similar jobs, see also [memory-leaks].

gem5 has two types of memory system:

The Ruby memory system includes the SLICC domain specific language to describe memory systems: http://gem5.org/Ruby SLICC transpiles to C++ auto-generated files under build/<isa>/mem/ruby/protocol/.

Ruby seems to have usage outside of gem5, but the naming overload with the Ruby programming language, which also has domain specific languages as a concept, makes it impossible to google anything about it!

Since it is not the default, Ruby is generally less stable that the classic memory model. However, because it allows describing a wide variety of important cache coherence protocols, while the classic system only describes a single protocol, Ruby is very importanonly describes a single protocol, Ruby is a very important feature of gem5.

Ruby support must be enabled at compile time with the scons PROTOCOL= flag, which compiles support for the desired memory system type.

Note however that most ISAs already implicitly set PROTOCOL via the build_opts/ directory, e.g. build_opts/ARM contains:

PROTOCOL = 'MOESI_CMP_directory'

and therefore ARM already compiles MOESI_CMP_directory by default.

Then, with fs.py and se.py, you can choose to use either the classic or the ruby system type selected at build time with PROTOCOL= at runtime by passing the --ruby option:

  • if --ruby is given, use the ruby memory system that was compiled into gem5. Caches are always present when Ruby is used, since the main goal of Ruby is to specify the cache coherence protocol, and it therefore hardcodes cache hierarchies.

  • otherwise, use the classic memory system. Caches may be optional for certain CPU types and are enabled with --caches.

Note that the --ruby option has some crazy side effects besides enabling Ruby, e.g. it sets the default --cpu-type to TimingSimpleCPU instead of the otherwise default AtomicSimpleCPU. TODO: I have been told that this is because sends the packet atomically,atomic requests do not work with Ruby, only timing.

It is not possible to build more than one Ruby system into a single build, and this is a major pain point for testing Ruby: https://gem5.atlassian.net/browse/GEM5-467

For example, to use a two level [mesi-cache-coherence-protocol] we can do:

./build-gem5 --arch aarch64 --gem5-build-id ruby -- PROTOCOL=MESI_Two_Level
./run --arch aarch64 --emulator -gem5 --gem5-build-id ruby -- --ruby

and during build we see a humongous line of type:

[   SLICC] src/mem/protocol/MESI_Two_Level.slicc -> ARM/mem/protocol/AccessPermission.cc, ARM/mem/protocol/AccessPermission.hh, ...

which shows that dozens of C++ files are being generated from Ruby SLICC.

The relevant Ruby source files live in the source tree under:

src/mem/protocol/MESI_Two_Level*

We already pass the SLICC_HTML flag by default to the build, which generates an HTML summary of each memory protocol under (TODO broken: https://gem5.atlassian.net/browse/GEM5-357):

xdg-open "$(./getvar --arch aarch64 --gem5-build-id ruby gem5_build_build_dir)/ARM/mem/protocol/html/index.html"

A minimized ruby config which was not merged upstream can be found for study at: https://gem5-review.googlesource.com/c/public/gem5/+/13599/1

One easy way to see that Ruby is being used without understanding it in detail is to enable some logging:

./run \
  --arch aarch64 \
  --emulator gem5 \
  --gem5-worktree master \
  --userland userland/arch/aarch64/freestanding/linux/hello.S \
  --static \
  --trace ExecAll,FmtFlag,Ruby,XBar \
  -- \
  --ruby \
;
cat "$(./getvar --arch aarch64 --emulator gem5 trace_txt_file)"

Then:

  • when the --ruby flag is given, we see a gazillion Ruby related messages prefixed e.g. by RubyPort:.

    We also observe from ExecEnable lines that instruction timing is not simple anymore, so the memory system must have latencies

  • without --ruby, we instead see XBar (Coherent Crossbar) related messages such as CoherentXBar:, which I believe is the more precise name for the memory model that the classic memory system uses: gem5 crossbar interconnect.

Certain features may not work in Ruby. For example, gem5 checkpoint creation is only possible in Ruby protocols that support flush, which is the case for PROTOCOL=MOESI_hammer but not PROTOCOL=MESI_Three_Level: https://www.mail-archive.com/[email protected]/msg17418.html

Tested in gem5 d7d9bc240615625141cd6feddbadd392457e49eb.

This is the simplest of all protocols, and therefore the first one you should study to learn how Ruby works.

Our full command line will be something like

./build-gem5 --arch aarch64 --gem5-build-id MI_example
./run \
  --arch aarch64 \
  --cli-args '2 100' \
  --cpus 3 \
  --emulator gem5 \
  --userland userland/cpp/atomic/aarch64_add.cpp \
  --gem5-build-id MI_example \
  -- \
  --ruby \
;

which produces a config.dot.svg like the following by with 3 CPUs instead of 2:

gem5 config TimingSimpleCPU 3 CPUs MI example b1623cb2087873f64197e503ab8894b5e4d4c7b4
Figure 2. config.dot.svg for a system with three TimingSimpleCPU CPUs with the Ruby MI_example protocol.

Crossbar or XBar in the code, is the default CPU interconnect that gets used by fs.py if --ruby is not given.

It presumably implements a crossbar switch along the lines of: https://en.wikipedia.org/wiki/Crossbar_switch

This is the best introductory example analysis we have so far: [gem5-event-queue-timingsimplecpu-syscall-emulation-freestanding-example-analysis-with-caches-and-multiple-cpus]. It contains more or less the most minimal example in which something interesting can be observed: multiple cores fighting over a single data memory variable.

Long story short: the interconnect contains the snoop mechanism, and it forwards packets coming form caches of a CPU to the caches of other CPUs in which the block is present.

It is therefore the heart of the [cache-coherence] mechanism, as it informs other caches of bus transactions they need to know about.

TODO: describe it in more detail. It appears to be a very simple mechanism.

Under src/mem/ we see that there is both a coherent and a non-coherent XBar.

In se.py it is set at:

if options.ruby:
    ...
else:
    MemClass = Simulation.setMemClass(options)
    system.membus = SystemXBar()

and SystemXBar is defined at src/mem/XBar.py with a nice comment:

# One of the key coherent crossbar instances is the system
# interconnect, tying together the CPU clusters, GPUs, and any I/O
# coherent masters, and DRAM controllers.
class SystemXBar(CoherentXBar):

Tested in gem5 12c917de54145d2d50260035ba7fa614e25317a3.

Python 3 support was mostly added in 2019 Q3 at arounda347a1a68b8a6e370334be3a1d2d66675891e0f1 but remained buggy for some time afterwards.

In an Ubuntu 18.04 host where python is python2 by default, build with Python 3 instead with:

./build-gem5 --gem5-build-id python3 -- PYTHON_CONFIG=python3-config

Python 3 is then automatically used when running if you use that build.

gem5 has a few in tree CPU models for different purposes.

In fs.py and se.py, those are selectable with the --cpu-type option.

The information to make highly accurate models isn’t generally public for non-free CPUs, so either you must either rely vendor provided models or on experiments/reverse engineering.

There is no simple answer for "what is the best CPU", in theory you have to understand each model and decide which one is closer your target system.

Whenever possible, stick to:

  • vendor provide ones obviously, e.g. ARM Holdings models of ARM cores, unless there is good reason not to, as they are the most likely to be accurate

  • newer models instead of older models

Both of those can be checked with git log and git blame.

All CPU types inherit from the BaseCPU class, and looking at the class hierarchy in Eclipse gives a good overview of what we have:

From this we see that there are basically only 4 C++ CPU models in gem5: Atomic, Timing, Minor and O3. All others are basically parametrizations of those base types.

Simple abstract CPU without a pipeline.

They are therefore completely unrealistic. But they also run much faster. KVM CPUs are an alternative way of fast forwarding boot when they work.

Implementations:

AtomicSimpleCPU: the default one. Memory accesses happen instantaneously. The fastest simulation except for KVM, but not realistic at all.

TimingSimpleCPU: memory accesses are realistic, but the CPU has no pipeline. The simulation is faster than detailed models, but slower than AtomicSimpleCPU.

Without caches, the CPU just stalls all the time waiting for memory requests for every advance of the PC or memory read from a instruction!

Caches do make a difference here of course, and lead to much faster memory return times.

Generic in-order superscalar core.

Its C++ implementation that can be parametrized to more closely match real cores.

Note that since gem5 is highly parametrizable, the parametrization could even change which instructions a CPU can execute by altering its available functional units, which are used to model performance.

For example, MinorCPU allows all implemented instructions, including [arm-sve] instructions, but a derived class modelling, say, an ARM Cortex A7 core, might not, since SVE is a newer feature and the A7 core does not have SVE.

The weird name "Minor" stands for "M (TODO what is M) IN ONder".

Its 4 stage pipeline is described at the "MinorCPU" section of gem5 ARM RSK.

There is also an in-tree doxygen at: src/doc/inside-minor.doxygen and rendered at: http://pages.cs.wisc.edu/~swilson/gem5-docs/minor.html

As of 2019, in-order cores are mostly present in low power/cost contexts, for example little cores of ARM bigLITTLE.

The following models extend the MinorCPU class by parametrization to make it match existing CPUs more closely:

  • HPI: derived from MinorCPU.

    Created by Ashkan Tousi in 2017 while working at ARM.

    According to gem5 ARM RSK:

    The HPI CPU timing model is tuned to be representative of a modern in-order Armv8-A implementation.

  • ex5_LITTLE: derived from MinorCPU. Description reads:

    ex5 LITTLE core (based on the ARM Cortex-A7)

    Implemented by Pierre-Yves Péneau from LIRMM, which is a research lab in Montpellier, France, in 2017.

Generic out-of-order core. "O3" Stands for "Out Of Order"!

Basic documentation on the old gem5 wiki: http://www.m5sim.org/O3CPU

Analogous to MinorCPU, but modelling an out of order core instead of in order.

The default functional units are described at: [gem5-derivo3cpu-default-functional-units]. All default widths are set to 8 instructions, from the config.ini:

[system.cpu]
type=DerivO3CPU
commitWidth=8
decodeWidth=8
dispatchWidth=8
fetchWidth=8
issueWidth=8
renameWidth=8
squashWidth=8
wbWidth=8

Existing parametrizations:

  • ex5_big: big corresponding to ex5_LITTLE, by same author at same time. It description reads:

    ex5 big core (based on the ARM Cortex-A15)

  • O3_ARM_v7a: implemented by Ronald Dreslinski from the University of Michigan in 2012

    Not sure why it has v7a in the name, since I believe the CPUs are just the microarchitectural implementation of any ISA, and the v8 hello world did run.

    The CLI option is named slightly differently as: --cpu-type O3_ARM_v7a_3.

  • fetch: besides obviously fetching the instruction, this is also where branch prediction runs. Presumably because you need to branch predict before deciding what to fetch next.

  • retire: the instruction is completely and totally done with.

    Mispeculated instructions never reach this stage as can be seen at: [gem5-event-queue-derivo3cpu-syscall-emulation-freestanding-example-analysis-speculative].

    The ExecAll happens at this time as well. And therefore ExecAll does not happen for mispeculated instructions.

./run \
  --arch aarch64 \
  --emulator gem5 \
  --userland userland/arch/aarch64/freestanding/linux/hello.S \
  --trace O3PipeView \
  --trace-stdout \
  -- \
  --cpu-type DerivO3CPU \
  --caches \
;
"$(./getvar gem5_source_dir)/util/o3-pipeview.py" -c 500 -o o3pipeview.tmp.log --color "$(./getvar --arch aarch64 trace_txt_file)"
less -R o3pipeview.tmp.log

Or without color:

"$(./getvar gem5_source_dir)/util/o3-pipeview.py" -c 500 -o o3pipeview.tmp.log "$(./getvar --arch aarch64 trace_txt_file)"
less o3pipeview.tmp.log

A sample output for this can be seen at: [hazardless-o3-pipeline].

Appears to be browser based, so you can zoom in and out, rather than the forced wrapping as for gem5 util/o3-pipeview.py O3 pipeline viewer.

Uses the same data source as util/o3-pipeview.py.

[gem5-event-queue-derivo3cpu-syscall-emulation-freestanding-example-analysis-stall-gain] shows how the text-based visualization can get problematic due to stalls requiring wraparounds.

The gem5 platform is selectable with the --machine option, which is named after the analogous QEMU -machine option, and which sets the --machine-type.

Each platform represents a different system with different devices, memory and interrupt setup.

TODO: describe the main characteristics of each platform, as of gem5 5e83d703522a71ec4f3eb61a01acd8c53f6f3860:

  • VExpress_GEM5_V1: good sane base platform

  • VExpress_GEM5_V1_DPU: VExpress_GEM5_V1 with DP650 instead of HDLCD, selected automatically by ./run --dp650, see also: gem5 graphic mode DP650

  • VExpress_GEM5_V2: VExpress_GEM5_V1 with GICv3, uses a different bootloader arm/aarch64_bootloader/boot_emm_v2.arm64 TODO is it because of GICv3?

  • anything that does not start with: VExpress_GEM5_: old and bad, don’t use them

Present at:

Depending on which archive you download from there, you can find some of:

  • Ubuntu based images

  • precompiled Linux kernels, with the gem5 arm Linux kernel patches for arm

  • precompiled gem5 bootloaders for ISAs that have them, e.g. ARM

  • precompiled DTBs if you don’t want to use autogeneration for some crazy reason

Some of those images are also used on the gem5 unit tests continuous integration.

Could be used as an alternative to this repository. But why would you do that? :-)

E.g. to use a precompiled ARM kernel:

mkdir aarch-system-201901106
cd aarch-system-201901106
wget http://dist.gem5.org/dist/current/arm/aarch-system-201901106.tar.bz2
tar xvf aarch-system-201901106.tar.bz2
cd ..
./run --arch aarch64 --emulator gem5 --linux-exec aarch-system-201901106/binaries/vmlinux.arm64

Certain ISAs like ARM have bootloaders that are automatically run before the main image to setup basic system state.

We cross compile those bootloaders from source automatically during ./build-gem5.

As of gem5 bcf041f257623e5c9e77d35b7531bae59edc0423, the source code of the bootloaderes can be found under:

system/arm/

and their selection can be seen under: src/dev/arm/RealView.py, e.g.:

    def setupBootLoader(self, cur_sys, loc):
        if not cur_sys.boot_loader:
            cur_sys.boot_loader = [ loc('boot_emm.arm64'), loc('boot_emm.arm') ]

The bootloader basically just sets up a bit of CPU state and jumps to the kernel entry point.

In aarch64 at least, CPUs other than CPU0 are also started up briefly, run some initialization, and are made wait on a WFE. This can be seen easily by booting a multicore Linux kernel run with gem5 ExecAll trace format.

Parent section: gem5 internals.

The gem5 memory system is connected in a very flexible way through the port system.

This system exists to allow seamlessly connecting any combination of CPU, caches, interconnects, DRAM and peripherals.

A Packet is the basic information unit that gets sent across ports.

gem5 memory requests can be classified in the following broad categories:

This trichotomy can be notably seen in the definition of the MasterPort class:

class MasterPort : public Port, public AtomicRequestProtocol,
    public TimingRequestProtocol, public FunctionalRequestProtocol

and the base classes are defined under src/mem/protocol/.

Then, by reading the rest of the class, we see that the send methods are all boring, and just forward to some polymorphic receiver that does the actual interesting activity:

    Tick
    sendAtomicSnoop(PacketPtr pkt)
    {
        return AtomicResponseProtocol::sendSnoop(_masterPort, pkt);
    }

    Tick
    AtomicResponseProtocol::sendSnoop(AtomicRequestProtocol *peer, PacketPtr pkt)
    {
        assert(pkt->isRequest());
        return peer->recvAtomicSnoop(pkt);
    }

The receive methods are therefore the interesting ones, and must be overridden on derived classes if they ever expect to receive such requests:

    Tick
    recvAtomicSnoop(PacketPtr pkt) override
    {
        panic("%s was not expecting an atomic snoop request\n", name());
        return 0;
    }

    void
    recvFunctionalSnoop(PacketPtr pkt) override
    {
        panic("%s was not expecting a functional snoop request\n", name());
    }

    void
    recvTimingSnoopReq(PacketPtr pkt) override
    {
        panic("%s was not expecting a timing snoop request.\n", name());
    }

One question that comes up now is: but why do CPUs need to care about snoop requests?

And one big answer is: to be able to implement LLSC atomicity as mentioned at: [arm-ldxr-and-stxr-instructions], since when other cores update memory, they could invalidate the lock of the current core.

Then, as you might expect, we can see that for example AtomicSimpleCPU does not override recvTimingSnoopReq.

Now let see which requests are generated by ordinary [arm-ldr-instruction]. We run:

./run \
  --arch aarch64 \
  --debug-vm \
  --emulator gem5 \
  --gem5-build-type debug \
  --useland userland/arch/aarch64/freestanding/linux/hello.S \

and then break at the methods of the LDR class LDRXL64_LIT: [gem5-execute-vs-initiateacc-vs-completeacc].

Before starting, we of course guess that:

  • AtomicSimpleCPU will be making atomic accesses from execute

  • TimingSimpleCPU will be making timing accesses from initiateAcc, which must generate the event which leads to completeAcc

so let’s confirm it.

We break on ArmISAInst::LDRXL64_LIT::execute which is what AtomicSimpleCPU uses, and that leads as expected to:

MasterPort::sendAtomic
AtomicSimpleCPU::sendPacket
AtomicSimpleCPU::readMem
SimpleExecContext::readMem
readMemAtomic<(ByteOrder)1, ExecContext, unsigned long>
readMemAtomicLE<ExecContext, unsigned long>
ArmISAInst::LDRXL64_LIT::execute
AtomicSimpleCPU::tick

Notably, AtomicSimpleCPU::readMem immediately translates the address, creates a packet, sends the atomic request, and gets the response back without any events.

And now if we do the same with --cpu-type TimingSimpleCPU and break at ArmISAInst::LDRXL64_LIT::initiateAcc, and then add another break for the next event schedule b EventManager::schedule (which we imagine is the memory read) we reach:

EventManager::schedule
DRAMCtrl::addToReadQueue
DRAMCtrl::recvTimingReq
DRAMCtrl::MemoryPort::recvTimingReq
TimingRequestProtocol::sendReq
MasterPort::sendTimingReq
CoherentXBar::recvTimingReq
CoherentXBar::CoherentXBarSlavePort::recvTimingReq
TimingRequestProtocol::sendReq
MasterPort::sendTimingReq
TimingSimpleCPU::handleReadPacket
TimingSimpleCPU::sendData
TimingSimpleCPU::finishTranslation
DataTranslation<TimingSimpleCPU*>::finish
ArmISA::TLB::translateComplete
ArmISA::TLB::translateTiming
ArmISA::TLB::translateTiming
TimingSimpleCPU::initiateMemRead
SimpleExecContext::initiateMemRead
initiateMemRead<ExecContext, unsigned long>
ArmISAInst::LDRXL64_LIT::initiateAcc
TimingSimpleCPU::completeIfetch
TimingSimpleCPU::IcachePort::ITickEvent::process
EventQueue::serviceOne

so as expected we have TimingRequestProtocol::sendReq.

Remember however that timing requests are a bit more complicated due to paging, since the page table walk can itself lead to further memory requests.

In this particular instance, the address being read with ldr x2, =len [arm-ldr-pseudo-instruction] is likely placed just after the text section, and therefore the pagewalk is already in the TLB due to previous instruction fetches, and this is because the translation just finished immediately going through TimingSimpleCPU::finishTranslation, some key snippets are:

TLB::translateComplete(const RequestPtr &req, ThreadContext *tc,
        Translation *translation, Mode mode, TLB::ArmTranslationType tranType,
        bool callFromS2)
{
    bool delay = false;
    Fault fault;
    if (FullSystem)
        fault = translateFs(req, tc, mode, translation, delay, true, tranType);
    else
        fault = translateSe(req, tc, mode, translation, delay, true);
    if (!delay)
        translation->finish(fault, req, tc, mode);
    else
        translation->markDelayed();

and then translateSe does not use delay at all, so we learn that in syscall emulation, delay is always false and things progress immediately there. And then further down TimingSimpleCPU::finishTranslation does some more fault checking:

void
TimingSimpleCPU::finishTranslation(WholeTranslationState *state)
{
    if (state->getFault() != NoFault) {
        translationFault(state->getFault());
    } else {
        if (!state->isSplit) {
            sendData(state->mainReq, state->data, state->res,
                     state->mode == BaseTLB::Read);

Tested in gem5 b1623cb2087873f64197e503ab8894b5e4d4c7b4.

As seen at gem5 functional vs atomic vs timing memory requests, functional requests are not used in common simulation, since the core must always go through caches.

Functional access are therefore only used for more magic simulation functionalities.

One such functionality, is the gem5 syscall emulation mode implementation of the [futex-system-call] which is done at futexFunc in src/sim/sycall_emul.hh.

As seen from man futex, the Linux kernel reads the value from an address that is given as the first argument of the call.

Therefore, here it makes sense for gem5 syscall implementation, which does not actually have a real kernel running, to just make a functional request and be done with it, since the impact of cache changes done by this read would be insignificant to the cost of an actual full context switch that would happen on a real syscall.

It is generally hard to implement functional requests for Ruby runs, because packets are flying through the memory system in a transient state, and there is no simple way of finding exactly which ones might have the latest version of the memory. See for example:

The typical error message in that case is:

fatal: Ruby functional read failed for address

Packet is what goes through ports: a single packet is sent out to the memory system, gets modified when it hits valid data, and then returns with the reply.

Packet is what CPUs create and send to get memory values. E.g. on gem5 AtomicSimpleCPU:

void
AtomicSimpleCPU::tick()
{
    ...
    Packet ifetch_pkt = Packet(ifetch_req, MemCmd::ReadReq);
    ifetch_pkt.dataStatic(&inst);

    icache_latency = sendPacket(icachePort, &ifetch_pkt);

Tick
AtomicSimpleCPU::sendPacket(MasterPort &port, const PacketPtr &pkt)
{
    return port.sendAtomic(pkt);
}

On TimingSimpleCPU, we note that the packet is dynamically created unlike for the AtomicSimpleCPU, since it must exist across multiple events which happen on separate function calls, unlike atomic memory which is done immediately in a single call:

void
TimingSimpleCPU::sendFetch(const Fault &fault, const RequestPtr &req,
                           ThreadContext *tc)
{
    if (fault == NoFault) {
        DPRINTF(SimpleCPU, "Sending fetch for addr %#x(pa: %#x)\n",
                req->getVaddr(), req->getPaddr());
        ifetch_pkt = new Packet(req, MemCmd::ReadReq);
        ifetch_pkt->dataStatic(&inst);
        DPRINTF(SimpleCPU, " -- pkt addr: %#x\n", ifetch_pkt->getAddr());

        if (!icachePort.sendTimingReq(ifetch_pkt)) {

It must later delete the return packet that it gets later on, e.g. for the ifetch:

TimingSimpleCPU::completeIfetch(PacketPtr pkt)
{
    if (pkt) {
        delete pkt;
    }

The most important properties of a Packet are:

  • PacketDataPtr data;: the data coming back from a reply packet or being sent via it

  • Addr addr;: the physical address of the data. TODO comment says could be virtual too, when?

    /// The address of the request.  This address could be virtual or
    /// physical, depending on the system configuration.
    Addr addr;
  • Flags flags;: flags describing properties of the Packet

  • MemCmd cmd;: see gem5 MemCmd

Each gem5 Packet contains a MemCmd

The MemCmd is basically an enumeration of possible commands, stuff like:

enum Command
{
    InvalidCmd,
    ReadReq,
    ReadResp,

Each command has a fixed number of attributes defined in the static array:

static const CommandInfo commandInfo[];

which gets initialized in the .cc file in the same order as the Command enum.

const MemCmd::CommandInfo
MemCmd::commandInfo[] =
{
    /* InvalidCmd */
    { 0, InvalidCmd, "InvalidCmd" },
    /* ReadReq - Read issued by a non-caching agent such as a CPU or
     * device, with no restrictions on alignment. */
    { SET3(IsRead, IsRequest, NeedsResponse), ReadResp, "ReadReq" },
    /* ReadResp */
    { SET3(IsRead, IsResponse, HasData), InvalidCmd, "ReadResp" },

From this we see for example that both ReadReq and ReadResp are marked with the IsRead attribute.

The second field of this array also specifies the corresponding reply of each request. E.g. the reply of a ReadReq is a ReadResp. InvalidCmd is just a placeholders for requests that are already replies.

struct CommandInfo
{
    /// Set of attribute flags.
    const std::bitset<NUM_COMMAND_ATTRIBUTES> attributes;
    /// Corresponding response for requests; InvalidCmd if no
    /// response is applicable.
    const Command response;
    /// String representation (for printing)
    const std::string str;
};

Some important commands include:

One good way to think about Request vs Packet could be "it is what the instruction definitions see", a bit like ExecContext vs ThreadContext.

Request is passed to the constructor of Packet, and Packet keeps a reference to it:

    Packet(const RequestPtr &_req, MemCmd _cmd)
        :  cmd(_cmd), id((PacketId)_req.get()), req(_req),
           data(nullptr), addr(0), _isSecure(false), size(0),
           _qosValue(0), headerDelay(0), snoopDelay(0),
           payloadDelay(0), senderState(NULL)
    {
        if (req->hasPaddr()) {
            addr = req->getPaddr();
            flags.set(VALID_ADDR);
            _isSecure = req->isSecure();
        }
        if (req->hasSize()) {
            size = req->getSize();
            flags.set(VALID_SIZE);
        }
    }

where RequestPtr is defined as:

typedef std::shared_ptr<Request> RequestPtr;

so we see that shared pointers to requests are basically passed around.

Some key fields include:

  • _paddr:

    /**
        * The physical address of the request. Valid only if validPaddr
        * is set.
        */
    Addr _paddr = 0;
  • _vaddr:

    /** The virtual address of the request. */
    Addr _vaddr = MaxAddr;

In AtomicSimpleCPU, a single packet of each type is kept for the entire CPU, e.g.:

RequestPtr ifetch_req;

and it gets created at construction time:

AtomicSimpleCPU::AtomicSimpleCPU(AtomicSimpleCPUParams *p)
{
    ifetch_req = std::make_shared<Request>();

and then it gets modified for each request:

setupFetchRequest(ifetch_req);

which does:

req->setVirt(fetchPC, sizeof(MachInst), Request::INST_FETCH,
                instMasterId(), instAddr);

Virtual to physical address translation done by the CPU stores the physical address:

fault = thread->dtb->translateAtomic(req, thread->getTC(),
                                        BaseTLB::Read);

which eventually calls e.g. on fs with MMU enabled:

Fault
TLB::translateMmuOn(ThreadContext* tc, const RequestPtr &req, Mode mode,
                    Translation *translation, bool &delay, bool timing,
                    bool functional, Addr vaddr,
                    ArmFault::TranMethod tranMethod)
{
    req->setPaddr(pa);

In TimingSimpleCPU, the request gets created per memory read:

Fault
TimingSimpleCPU::initiateMemRead(Addr addr, unsigned size,
                                 Request::Flags flags,
                                 const std::vector<bool>& byte_enable)
{
    ...
    RequestPtr req = std::make_shared<Request>(
        addr, size, flags, dataMasterId(), pc, thread->contextId());

and from gem5 functional vs atomic vs timing memory requests and gem5 functional vs atomic vs timing memory requests we remember that initiateMemRead is actually started from the initiateAcc instruction definitions for timing:

Fault LDRWL64_LIT::initiateAcc(ExecContext *xc,
    Trace::InstRecord *traceData) const
{
    ...
    fault = initiateMemRead(xc, traceData, EA, Mem, memAccessFlags);

From this we see that initiateAcc memory instructions are basically extracting the required information for the request, notably the address EA and flags.

Each cache object owns a MSHRQueue:

class BaseCache : public ClockedObject
{
    /** Miss status registers */
    MSHRQueue mshrQueue;

BaseCache is the base class of Cache and NoncoherentCache.

MSHRQueue is a Queue of MSHR:

class MSHRQueue : public Queue<MSHR>

and Queue is also a gem5 class under src/mem/cache/queue.hh.

The MSHR basically keeps track of all information the cache receives, and helps it take appropriate action. I’m not sure why it is separate form the cache at all, as it is basically performing essential cache bookkeeping.

A clear example of MSHR in action can be seen at: [gem5-event-queue-timingsimplecpu-syscall-emulation-freestanding-example-analysis-with-caches-and-multiple-cpus]. In that example what happened was:

  • CPU1 writes to an address and it completes

  • CPU2 sends read

  • CPU1 writes to the address again

  • CPU2 snoops the write, and notes it down in its MSHR

  • CPU2 receives a snoop reply for its read, also from CPU1 which has the data and the line becomes valid

  • CPU2 gets its data. But the MSHR remembers that it had also received a write snoop, so it also immediately invalidates that line

From this we understand that MSHR is the part of the cache that synchronizes stuff pending snoops and ensures that things get invalidated.

You can place this SimObject in between two ports to get extra statistics about the packets that are going through.

It only works on timing requests, and does not seem to dump any memory values, only add extra statistics.

For example, the patch patches/manual/gem5-commmonitor-se.patch hack a CommMonitor between the CPU and the L1 cache on top of gem5 1c3662c9557c85f0d25490dc4fbde3f8ab0cb350:

patch -d "$(./getvar gem5_source_dir)" -p 1 < patches/manual/gem5-commmonitor-se.patch

That patch was done largely by copying what fs.py --memcheck does with a MemChecker object.

You can then run with:

./run \
  --arch aarch64 \
  --emulator gem5 \
  --userland userland/arch/aarch64/freestanding/linux/hello.S \
  -- \
  --caches \
  --cpu-type TimingSimpleCPU \
;

and now we have some new extra histogram statistics such as:

system.cpu.dcache_mon.readBurstLengthHist::samples            1

One neat thing about this is that it is agnostic to the memory object type, so you don’t have to recode those statistics for every new type of object that operates on memory packets.

SimpleMemory is a highly simplified memory system. It can replace a more complex DRAM model if you use it e.g. as:

./run --emulator gem5 -- --mem-type SimpleMemory

and it also gets used in certain system-y memories present in ARM systems by default e.g. Flash memory:

[system.realview.flash0]
type=SimpleMemory

As of gem5 3ca404da175a66e0b958165ad75eb5f54cb5e772 LKMC 059a7ef9d9c378a6d1d327ae97d90b78183680b2 it did not provide any speedup to the Linux kernel boot according to a quick test.

Internals under other sections:

In order to develop complex C++ software such as gem5, a good IDE setup is fundamental.

The best setup I’ve reached is with Eclipse. It is not perfect, and there is a learning curve, but is worth it.

Notably, it is very hard to get perfect due to: [why-are-all-c-symlinked-into-the-gem5-build-dir].

I recommend the following settings, tested in Eclipse 2019.09, Ubuntu 18.04:

To run and GDB step debug the executable, just copy the full command line without newlines from your run command (Eclipse does not like newlines for the arguments), e.g.:

./run --emulator gem5 --print-cmd-oneline

and configure it into Eclipse as usual.

One downside of this setup is that if you want to nuke your build directory to get a clean build, then the Eclipse configuration files present in it might get deleted. Maybe it is possible to store configuration files outside of the directory, but we are now mitigating that by making a backup copy of those configuration files before removing the directory, and restoring it when you do ./build-gem --clean.

The interaction uses the Python C extension interface https://docs.python.org/2/extending/extending.html interface through the [pybind11] helper library: https://github.com/pybind/pybind11

The C++ executable both:

  • starts running the Python executable

  • provides Python classes written in C++ for that Python code to use

An example of this can be found at:

then gem5 magic SimObject class adds some crazy stuff on top of it further, is is a mess. In particular, it auto generates params/ headers. TODO: why is this mess needed at all? pybind11 seems to handle constructor arguments just fine:

Let’s study BadDevice for example:

src/dev/BadDevice.py defines devicename:

class BadDevice(BasicPioDevice):
    type = 'BadDevice'
    cxx_header = "dev/baddev.hh"
    devicename = Param.String("Name of device to error on")

The object is created in Python for example from src/dev/alpha/Tsunami.py as:

    fb = BadDevice(pio_addr=0x801fc0003d0, devicename='FrameBuffer')

Since BadDevice has no __init__ method, and neither BasicPioDevice, it all just falls through until the SimObject.__init__ constructor.

This constructor will loop through the inheritance chain and give the Python parameters to the C++ BadDeviceParams class as follows.

The auto-generated build/ARM/params/BadDevice.hh file defines BadDeviceParams in C++:

#ifndef __PARAMS__BadDevice__
#define __PARAMS__BadDevice__

class BadDevice;

#include <cstddef>
#include <string>

#include "params/BasicPioDevice.hh"

struct BadDeviceParams
    : public BasicPioDeviceParams
{
    BadDevice * create();
    std::string devicename;
};

#endif // __PARAMS__BadDevice__

and ./python/_m5/param_BadDevice.cc defines the param Python from C++ with pybind11:

namespace py = pybind11;

static void
module_init(py::module &m_internal)
{
    py::module m = m_internal.def_submodule("param_BadDevice");
    py::class_<BadDeviceParams, BasicPioDeviceParams, std::unique_ptr<BadDeviceParams, py::nodelete>>(m, "BadDeviceParams")
        .def(py::init<>())
        .def("create", &BadDeviceParams::create)
        .def_readwrite("devicename", &BadDeviceParams::devicename)
        ;

    py::class_<BadDevice, BasicPioDevice, std::unique_ptr<BadDevice, py::nodelete>>(m, "BadDevice")
        ;

}

static EmbeddedPyBind embed_obj("BadDevice", module_init, "BasicPioDevice");

src/dev/baddev.hh then uses the parameters on the constructor:

class BadDevice : public BasicPioDevice
{
  private:
    std::string devname;

  public:
    typedef BadDeviceParams Params;

  protected:
    const Params *
    params() const
    {
        return dynamic_cast<const Params *>(_params);
    }

  public:
     /**
      * Constructor for the Baddev Class.
      * @param p object parameters
      * @param a base address of the write
      */
    BadDevice(Params *p);

src/dev/baddev.cc then uses the parameter:

BadDevice::BadDevice(Params *p)
    : BasicPioDevice(p, 0x10), devname(p->devicename)
{
}

It has been found that this usage of [pybind11] across hundreds of SimObject files accounted for 50% of the gem5 build time at one point: [pybind11-accounts-for-50-of-gem5-build-time].

To get a feeling of how SimObject objects are run, see: gem5 event queue AtomicSimpleCPU syscall emulation freestanding example analysis.

Bibliography:

Tested on gem5 08c79a194d1a3430801c04f37d13216cc9ec1da3.

The main is at: src/sim/main.cc. It calls:

ret = initM5Python();

src/sim/init.cc:

230 int
231 initM5Python()
232 {
233     EmbeddedPyBind::initAll();
234     return EmbeddedPython::initAll();
235 }

initAll basically just initializes the _m5 Python object, which is used across multiple .py.

Back on main:

ret = m5Main(argc, argv);

which goes to:

result = PyRun_String(*command, Py_file_input, dict, dict);

with commands looping over:

import m5
m5.main()

which leads into:

src/python/m5/main.py#main

which finally calls your config file like fs.py with:

filename = sys.argv[0]
filedata = file(filename, 'r').read()
filecode = compile(filedata, filename, 'exec')
[...]
exec filecode in scope

TODO: the file path name appears to be passed as a command line argument to the Python script, but I didn’t have the patience to fully understand the details.

The Python config files then set the entire system up in Python, and finally call m5.simulate() to run the actual simulation. This function has a C++ native implementation at:

src/sim/simulate.cc

and that is where the main event loop, doSimLoop, gets called and starts kicking off the gem5 event queue.

Tested at gem5 b4879ae5b0b6644e6836b0881e4da05c64a6550d.

All SimObjects seem to be automatically added to the m5.objects namespace, and this is done in a very convoluted way, let’s try to understand a bit:

src/python/m5/objects/__init__.py

contains:

modules = __loader__.modules

for module in modules.keys():
    if module.startswith('m5.objects.'):
        exec("from %s import *" % module)

And from IPDB we see that this appears to loop over every object string of type m5.objects.modulename.

This __init__ gets called from src/python/importer.py at the exec:

class CodeImporter(object):
    def load_module(self, fullname):
            override = os.environ.get('M5_OVERRIDE_PY_SOURCE', 'false').lower()
            if override in ('true', 'yes') and  os.path.exists(abspath):
                src = open(abspath, 'r').read()
                code = compile(src, abspath, 'exec')

            if os.path.basename(srcfile) == '__init__.py':
                mod.__path__ = fullname.split('.')
                mod.__package__ = fullname
            else:
                mod.__package__ = fullname.rpartition('.')[0]
            mod.__file__ = srcfile

            exec(code, mod.__dict__)

import sys
importer = CodeImporter()
add_module = importer.add_module
sys.meta_path.append(importer)

Here as a bonus here we also see how M5_OVERRIDE_PY_SOURCE works.

In src/SConscript we see that SimObject is just a PySource with module equals to m5.objects:

class SimObject(PySource):
    def __init__(self, source, tags=None, add_tags=None):
        '''Specify the source file and any tags (automatically in
        the m5.objects package)'''
        super(SimObject, self).__init__('m5.objects', source, tags, add_tags)

The add_module method seems to be doing the magic and is called from src/sim/init.cc:

bool
EmbeddedPython::addModule() const
{
    PyObject *code = getCode();
    PyObject *result = PyObject_CallMethod(importerModule, PyCC("add_module"),

which is called from:

int
EmbeddedPython::initAll()
{
    // Load the importer module
    PyObject *code = importer->getCode();
    importerModule = PyImport_ExecCodeModule(PyCC("importer"), code);
    if (!importerModule) {
        PyErr_Print();
        return 1;
    }

    // Load the rest of the embedded python files into the embedded
    // python importer
    list<EmbeddedPython *>::iterator i = getList().begin();
    list<EmbeddedPython *>::iterator end = getList().end();
    for (; i != end; ++i)
        if (!(*i)->addModule())

and getList comes from:

EmbeddedPython::EmbeddedPython(const char *filename, const char *abspath,
    const char *modpath, const unsigned char *code, int zlen, int len)
    : filename(filename), abspath(abspath), modpath(modpath), code(code),
      zlen(zlen), len(len)
{
    // if we've added the importer keep track of it because we need it
    // to bootstrap.
    if (string(modpath) == string("importer"))
        importer = this;
    else
        getList().push_back(this);
}

list<EmbeddedPython *> &
EmbeddedPython::getList()
{
    static list<EmbeddedPython *> the_list;
    return the_list;
}

and the constructor in turn gets called from per SimObject autogenerated files such as e.g. dev/storage/Ide.py.cc for src/dev/storage/Ide.py:

EmbeddedPython embedded_m5_objects_Ide(
    "m5/objects/Ide.py",
    "/home/ciro/bak/git/linux-kernel-module-cheat/data/gem5/master4/src/dev/storage/Ide.py",
    "m5.objects.Ide",
    data_m5_objects_Ide,
    947,
    2099);

} // anonymous namespace

which get autogenerated at src/SConscript:

def embedPyFile(target, source, env):

for source in PySource.all:
    base_py_env.Command(source.cpp, [ py_marshal, source.tnode ],
                        MakeAction(embedPyFile, Transform("EMBED PY")))

where the PySource.all thing as you might expect is a static list of all PySource source files as they get updated in the constructor.

Tested in gem5 d9cb548d83fa81858599807f54b52e5be35a6b03.

gem5 is an event based simulator, and as such the event queue is of of the crucial elements in the system.

Every single action that takes time (e.g. notably reading from memory) models that time delay by scheduling an event in the future.

The gem5 event queue stores one callback event for each future point in time.

The event queue is implemented in the class EventQueue in the file src/sim/eventq.hh.

Not all times need to have an associated event: if a given time has no events, gem5 just skips it and jumps to the next event: the queue is basically a linked list of events.

Important examples of events include:

  • CPU ticks

  • peripherals and memory

At gem5 event queue AtomicSimpleCPU syscall emulation freestanding example analysis we see for example that at the beginning of an AtomicCPU simulation, gem5 sets up exactly two events:

Then, at the end of the callback of one tick event, another tick is scheduled.

And so the simulation progresses tick by tick, until an exit event happens.

The EventQueue class has one awesome dump() function that prints a human friendly representation of the queue, and can be easily called from GDB. TODO example.

We can also observe what is going on in the event queue with the Event debug flag.

Event execution is done at EventQueue::serviceOne():

Event *exit_event = eventq->serviceOne();

This calls the Event::process method of the event.

Another important technique is to use GDB and break at interesting points such as:

b Trace::OstreamLogger::logMessage
b EventManager::schedule
b EventFunctionWrapper::process

although stepping into EventFunctionWrapper::process which does std::function is a bit of a pain: https://stackoverflow.com/questions/59429401/how-to-step-into-stdfunction-user-code-from-c-functional-with-gdb

Another potentially useful technique is to use:

--trace Event,ExecAll,FmtFlag,FmtStackTrace --trace-stdout

which automates the logging of Trace::OstreamLogger::logMessage() backtraces.

But alas, it misses which function callback is being scheduled, which is the awesome thing we actually want:

Then, once we had that, the most perfect thing ever would be to make the full event graph containing which events schedule which events!

Let’s now analyze every single event on a minimal gem5 syscall emulation mode in the simplest CPU that we have:

./run \
  --arch aarch64 \
  --emulator gem5 \
  --userland userland/arch/aarch64/freestanding/linux/hello.S \
  --trace Event,ExecAll,FmtFlag \
  --trace-stdout \
;

which gives:

      0: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 scheduled @ 0
**** REAL SIMULATION ****
      0: Event: Event_70: generic 70 scheduled @ 0
info: Entering event queue @ 0.  Starting simulation...
      0: Event: Event_70: generic 70 rescheduled @ 18446744073709551615
      0: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 executed @ 0
      0: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue    :   movz   x0, #1, #0        : IntAlu :  D=0x0000000000000001  flags=(IsInteger)
      0: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 rescheduled @ 500
    500: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 executed @ 500
    500: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+4    :   adr   x1, #28            : IntAlu :  D=0x0000000000400098  flags=(IsInteger)
    500: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 rescheduled @ 1000
   1000: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 executed @ 1000
   1000: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+8    :   ldr   w2, #4194464       : MemRead :  D=0x0000000000000006 A=0x4000a0  flags=(IsInteger|IsMemRef|IsLoad)
   1000: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 rescheduled @ 1500
   1500: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 executed @ 1500
   1500: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+12    :   movz   x8, #64, #0       : IntAlu :  D=0x0000000000000040  flags=(IsInteger)
   1500: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 rescheduled @ 2000
   2000: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 executed @ 2000
   2000: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+16    :   svc   #0x0               : IntAlu :   flags=(IsSerializeAfter|IsNonSpeculative|IsSyscall)
hello
   2000: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 rescheduled @ 2500
   2500: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 executed @ 2500
   2500: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+20    :   movz   x0, #0, #0        : IntAlu :  D=0x0000000000000000  flags=(IsInteger)
   2500: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 rescheduled @ 3000
   3000: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 executed @ 3000
   3000: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+24    :   movz   x8, #93, #0       : IntAlu :  D=0x000000000000005d  flags=(IsInteger)
   3000: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 rescheduled @ 3500
   3500: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 executed @ 3500
   3500: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+28    :   svc   #0x0               : IntAlu :   flags=(IsSerializeAfter|IsNonSpeculative|IsSyscall)
   3500: Event: Event_71: generic 71 scheduled @ 3500
   3500: Event: Event_71: generic 71 executed @ 3500

On the event trace, we can first see:

0: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 scheduled @ 0

This schedules a tick event for time 0, and leads to the first clock tick.

Then:

0: Event: Event_70: generic 70 scheduled @ 0
0: Event: Event_70: generic 70 rescheduled @ 18446744073709551615

schedules the end of time event for time 0, which is later rescheduled to the actual end of time.

At:

0: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 executed @ 0
0: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue    :   movz   x0, #1, #0        : IntAlu :  D=0x0000000000000001  flags=(IsInteger)
0: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 rescheduled @ 500

the tick event happens, the instruction runs, and then the instruction is rescheduled in 500 time units. This is done at the end of AtomicSimpleCPU::tick():

if (_status != Idle)
    reschedule(tickEvent, curTick() + latency, true);

At:

3500: ExecEnable: system.cpu: A0 T0 : @asm_main_after_prologue+28    :   svc   #0x0               : IntAlu :   flags=(IsSerializeAfter|IsNonSpeculative|IsSyscall)
3500: Event: Event_71: generic 71 scheduled @ 3500
3500: Event: Event_71: generic 71 executed @ 3500

the exit system call is called, and then it schedules an exit evit, which gets executed and the simulation ends.

We guess then that Event_71 comes from the SE implementation of the exit syscall, so let’s just confirm, the trace contains:

exitSimLoop() at sim_events.cc:97 0x5555594746e0
exitImpl() at syscall_emul.cc:215 0x55555948c046
exitFunc() at syscall_emul.cc:225 0x55555948c147
SyscallDesc::doSyscall() at syscall_desc.cc:72 0x5555594949b6
Process::syscall() at process.cc:401 0x555559484717
SimpleThread::syscall() at 0x555559558059
ArmISA::SupervisorCall::invoke() at faults.cc:856 0x5555572950d7
BaseSimpleCPU::advancePC() at base.cc:681 0x555559083133
AtomicSimpleCPU::tick() at atomic.cc:757 0x55555907834c

and exitSimLoop() does:

new GlobalSimLoopExitEvent(when + simQuantum, message, exit_code, repeat);

Tested in gem5 12c917de54145d2d50260035ba7fa614e25317a3.

Let’s have a closer look at the initial magically scheduled events of the simulation.

Most events come from other events, but at least one initial event must be scheduled somehow from elsewhere to kick things off.

The initial tick event:

0: Event: AtomicSimpleCPU tick.wrapped_function_event: EventFunctionWrapped 39 scheduled @ 0

we’ll study by breaking at at the point that prints messages: b Trace::OstreamLogger::logMessage() to see where events are being scheduled from:

Trace::OstreamLogger::logMessage() at trace.cc:149 0x5555593b3b1e
void Trace::Logger::dprintf_flag<char const*, char const*, unsigned long>() at 0x55555949e603
void Trace::Logger::dprintf<char const*, char const*, unsigned long>() at 0x55555949de58
Event::trace() at eventq.cc:395 0x55555946d109
EventQueue::schedule() at eventq_impl.hh:65 0x555557195441
EventManager::schedule() at eventq.hh:746 0x555557194aa2
AtomicSimpleCPU::activateContext() at atomic.cc:239 0x555559075531
SimpleThread::activate() at simple_thread.cc:177 0x555559545a63
Proces

linux-kernel-module-cheat's People

Contributors

************ avatar reveriel avatar andrewzigerelli avatar parzival3 avatar mgalgs avatar dovgalyuk avatar wataash avatar stubbfel avatar

Stargazers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.