#![no_std] は、そのクレートが std を自動的にリンクせず、core の prelude を使用することを意味します。これは「OS がない」こと、あるいは「メモリを割り当てられない」ことを意味しません。no_std ライブラリは通常の Linux プログラムで使用することもできますし、適切なランタイムサポートを提供するボトムレス(裸機)環境で使用することもできます。
カーネルモジュールの難しさは、単に std を外すだけではありません。カーネルのリソースライフサイクル、割り当てコンテキスト、ロックルール、ビルド設定に従わなければなりません。ユーザー空間の API に名前を変えただけでは、正しいモジュールにはなりません。
core 言語の基礎、イテレータ、Option/Result、利用可能なアトミック型 alloc(オプション) Box、Vec、String など;最終的な環境が割り当てサポートを提供する必要がある ターゲット実行環境 no_std はライブラリ依存関係を変更するだけで、ボトムレスまたはカーネルの実 行環境を自動的に構築するものではない エントリーポイント、リンクレイアウト、パニック戦略、デバイスと同期の抽象化 std アプリケーションも no_std ライブラリを使用できる;カーネルは独自の API とビルドシステムに依存する。
core、alloc、std はそれぞれ何を提供するか
階層 一般的な機能 依存条件
core Option、Result、Iterator、基本型、フォーマットインターフェース ヒープに依存しない;一部のアトミック機能はターゲットに制限される
alloc Box、Vec、String、Rc、ターゲットに応じた Arc、BTreeMap 最終的なプログラムの割り当てサポートが必要
std ファイル、ネットワーク、スレッドなどのプラットフォームインターフェース、および core/alloc の再エクスポート ターゲットプラットフォームに対応する実装が必要
HashMap は alloc に含まれていません。ターゲットに応じて追加の実装を選択するか、他のコレクションを使用する必要があります。format_args! はフォーマット引数を構築しますが、String の割り当ては要求しません。alloc::format! だけが文字列を割り当てます。core::fmt::Write を提供することで、フォーマット出力を固定バッファやデバイスに書き込むことができますが、これはヒープ割り当てを最初に実装する必要があることを意味しません。alloc ドキュメント
no_std もまた、「依存関係グラフに std が完全に含まれていないことを保証する」チェッカーではありません。ある依存関係のデフォルトの feature が std を導入する可能性があるため、ターゲットと feature の組み合わせを確認する必要があります。std が根本的に利用できないターゲットでは、関連する依存関係がビルド段階で露出します。Rust クレート規則
no_std はどの依存層を外すか
スライス解析から始めて要件を足します。固定バッファへの整形は core に置けますが、Vec で alloc の責任が生じ、std::fs はプラットフォーム API を必要とします。ヒープ、OS、プログラム入口の有無を no_std だけで一括して決めることはできません。
図を準備しています 再読み込み
no_std はどの依存層を外すか no_std の核は固定バッファを使えます。Vec は alloc と最終環境の割り当て、ファイルは std または対象向けの実装が必要です。
{"id":"rust-no-std-layers","title":"no_std はどの依存層を外すか","summary":"no_std の核は固定バッファを使えます。Vec は alloc と最終環境の割り当て、ファイルは std または対象向けの実装が必要です。","height":1000,"html":"<h2 data-i18n=\"heading\"></h2><p class=\"intro\" data-i18n=\"intro\"></p><label class=\"check\"><input type=\"checkbox\" id=\"vector\"><span data-i18n=\"vector\"></span></label><label class=\"check\"><input type=\"checkbox\" id=\"file\"><span data-i18n=\"file\"></span></label><label class=\"check\"><input type=\"checkbox\" id=\"format\" checked><span data-i18n=\"format\"></span></label><div class=\"track-row\"><span data-i18n=\"layers\"></span><div id=\"layers\" class=\"track\"></div></div><section class=\"panel\"><h3 data-i18n=\"requirements\"></h3><div id=\"requirements\"></div></section><details class=\"scope\"><summary data-i18n=\"scopeLabel\"></summary><p data-i18n=\"scope\"></p></details>","css":".intro{margin:8px 0 18px;color:var(--muted);font-size:14px}.caption,.hint{font-size:12px;color:var(--muted);margin-top:12px}.control{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px 12px;align-items:center;margin:14px 0;font-size:13px}.control label{font-size:13px}.control output{color:var(--accent);min-width:5em;text-align:right;font-variant-numeric:tabular-nums}.control input{grid-column:1/-1;width:100%;margin:0}.presets{display:flex;gap:4px;align-items:stretch}.presets button{flex:1 1 0;min-width:0;overflow-wrap:anywhere;font-size:13px}.actions{display:flex;gap:8px;flex-wrap:wrap;margin:14px 0}.actions button{flex:1;min-width:0;font-size:13px;min-height:42px}.copy{display:grid;font-size:14px;margin:16px 0}.copy>*{grid-area:1/1;margin:0}.reserve{visibility:hidden}.scope{margin-top:14px;color:var(--muted);font-size:12px}.scope summary{padding:8px 0;cursor:pointer}.scope p{margin-top:10px}.two{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.card{border:1px solid var(--rule);border-radius:9px;padding:14px;min-width:0}.card header{font-size:14px;font-weight:600;margin-bottom:10px}.card button{font-size:12px;width:100%;min-width:0}.card small{display:block;font-size:12px;color:var(--muted)}.card code{font-size:12px;overflow-wrap:anywhere}.metrics{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.metrics>div{border-left:2px solid var(--accent);padding-left:10px;min-width:0}.metrics span{display:block;min-height:3.2em;color:var(--muted);font-size:12px}.metrics strong{font-size:23px;display:block;font-weight:550;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.formula{border-top:1px solid var(--rule);padding-top:12px;margin-top:14px;font-size:13px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.value{font:550 20px ui-monospace,monospace}.legend{display:flex;flex-wrap:wrap;gap:6px 14px;font-size:12px;color:var(--muted);margin:12px 0}.legend span:before{content:'';display:inline-block;width:8px;height:8px;border-radius:2px;background:var(--accent);margin-right:6px}.legend .second:before{background:var(--second)}.check{display:flex;align-items:center;gap:8px;font-size:13px;margin:12px 0}.check input{width:16px;height:16px;flex-shrink:0;accent-color:var(--accent)}select,input[type=text],input[type=number]{background:var(--paper);color:var(--ink);font:inherit;font-size:13px;padding:10px;border:1px solid var(--rule);border-radius:7px;max-width:100%;min-width:0}select{width:100%;min-height:42px}.band{height:20px;display:flex;background:var(--surface);border-radius:4px;overflow:hidden}.band i{height:100%;display:block;background:var(--accent);transition:width .25s}.band i.second{background:var(--second)}button:disabled{cursor:default}.status{font-size:13px;min-height:4.8em}.mono{font-family:ui-monospace,monospace;font-variant-numeric:tabular-nums}.muted{color:var(--muted)}\n@media(max-width:480px){.two{gap:8px}.card{padding:12px 9px}.actions button,.presets button{font-size:12px}.metrics strong{font-size:20px}.metrics{gap:8px}}\n@media(prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important;animation:none!important}}\n.track-row{margin:16px 0}.track-row>span{display:block;font-size:12px;color:var(--muted);margin-bottom:7px}.track{display:flex;gap:5px;min-width:0}.cell{flex:1;min-width:0;min-height:48px;border:1px solid var(--rule);border-radius:5px;background:var(--surface);display:flex;align-items:center;justify-content:center;text-align:center;padding:5px 3px;font-size:12px;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.cell.on{background:var(--accent-soft);border-color:var(--accent)}.cell.gold{background:var(--second-soft);border-color:var(--second)}.cell.empty{border-style:dashed;color:var(--muted)}.cell.error{border-color:var(--second);text-decoration:line-through}.choices{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px;margin:14px 0}.choices button{min-width:0;padding:10px 4px;font-size:12px;overflow-wrap:anywhere}.choices button[aria-current=true]{border-color:var(--accent);background:var(--accent-soft)}.relation{display:grid;grid-template-columns:minmax(0,1fr) 28px minmax(0,1fr);align-items:center;gap:6px;margin:12px 0}.relation .cell{min-height:72px}.relation>i{text-align:center;font-style:normal;color:var(--accent)}.readout{font-size:13px;white-space:pre-line;min-height:6.4em;overflow-wrap:anywhere}.plot{position:relative;border-left:1px solid var(--rule);border-bottom:1px solid var(--rule);padding:8px 0;margin:18px 0}.plot-row{height:28px;position:relative;margin:4px 0;background:var(--surface)}.plot-row i{position:absolute;inset-block:5px;background:var(--accent);min-width:2px;transition:width .2s,left .2s}.plot-row b{position:relative;padding:4px 6px;font:11px/28px ui-monospace,monospace;background:var(--paper);border-radius:3px}.axis{display:flex;justify-content:space-between;font-size:11px;color:var(--muted)}\n\n/* Action labels must remain readable across locales and narrow embeds. */\n.actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}\n.actions button{overflow-wrap:anywhere;white-space:normal;min-height:58px;padding:8px}\nbutton{overflow-wrap:anywhere}\n@media(min-width:640px){.actions{grid-template-columns:repeat(3,minmax(0,1fr))}}\n\n.metrics span{overflow-wrap:anywhere}\n.panel{border:1px solid var(--rule);border-radius:9px;padding:12px;margin:14px 0;min-width:0}.panel h3{font-size:13px;margin:0 0 10px;color:var(--muted)}.source{font:13px/1.8 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:12px 0}.source mark{background:var(--accent-soft);color:var(--ink);border-bottom:2px solid var(--accent)}.source .fault{background:var(--second-soft);border-color:var(--second)}.diagram{display:block;width:100%;height:auto;max-height:320px;margin:14px 0;overflow:visible}.diagram text{fill:var(--ink);font:12px ui-monospace,monospace}.diagram .edge{stroke:var(--muted);stroke-width:1.5;fill:none}.diagram .edge.on{stroke:var(--accent);stroke-width:3}.diagram .node{fill:var(--surface);stroke:var(--rule);stroke-width:1.5}.diagram .node.on{fill:var(--accent-soft);stroke:var(--accent)}.diagram .node.gold{fill:var(--second-soft);stroke:var(--second)}.log{font:12px/1.8 ui-monospace,monospace;white-space:pre-line;overflow-wrap:anywhere;min-height:7.2em}.table{display:grid;gap:5px;margin:14px 0}.table .tr{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:5px}.table .tr>*{padding:8px 5px;background:var(--surface);border-radius:4px;min-width:0;overflow-wrap:anywhere;font-size:12px}.table .tr .on{background:var(--accent-soft)}.table .tr .gold{background:var(--second-soft)}.choices button{min-height:44px}.metrics strong{min-height:1.6em}.code-line{display:block}.code-line.on{background:var(--accent-soft);border-left:2px solid var(--accent);padding-left:6px}.status-badge{font-size:12px;color:var(--accent)}.tile-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px}.tile-grid .cell{min-height:40px}.actions button{min-height:48px}.form-field{display:grid;gap:8px;margin:14px 0;font-size:13px}.form-field input{width:100%;font-family:ui-monospace,monospace}.metrics.three{grid-template-columns:repeat(3,minmax(0,1fr))}.formula{min-height:3.2em}.presets{flex-wrap:wrap}.presets button{flex-basis:25%;min-height:44px}\n\n.budget{display:flex;height:28px;margin:16px 0;background:var(--surface);border-radius:5px;overflow:hidden}.budget i{display:block;background:var(--accent);transition:width .2s}.budget i.gold{background:var(--second)}.intervals{margin:16px 0}.interval{position:relative;height:36px;background:var(--surface);margin:6px 0;border-radius:4px;overflow:hidden}.interval i{position:absolute;height:100%;background:var(--accent-soft);border-left:2px solid var(--accent)}.interval i.gold{background:var(--second-soft);border-color:var(--second)}.interval span{position:relative;z-index:1;font:12px/36px ui-monospace,monospace;padding-left:7px}.table .tr>*{min-height:4.8em}.formula{white-space:pre-line;min-height:7.2em}.actions:has(>button:only-child){grid-template-columns:1fr}.metrics strong{min-height:3.2em}.rangegrid{display:grid;grid-template-columns:repeat(12,minmax(0,1fr));gap:3px;margin:14px 0}.rangegrid .cell{min-height:30px;padding:3px 1px;font-size:10px}.message{min-height:7.2em;white-space:pre-line;font:13px/1.8 ui-monospace,monospace;overflow-wrap:anywhere}\n/* Allow CJK hanging punctuation without overflowing a metric's border box. */\n.metrics>div{padding-right:4px}.metrics span{line-break:anywhere}\n\n.chart-wrap{margin:18px 0}.chart-label{font-size:12px;color:var(--muted);min-height:3.2em}.curve{display:block;width:100%;height:auto;max-height:320px;overflow:visible}.curve text{font:11px ui-monospace,monospace;fill:var(--muted)}.gridline{stroke:var(--rule);stroke-width:1}.metrics strong{font-size:20px;min-height:3.2em}.formula{font:12px/1.8 ui-monospace,monospace;min-height:9em}.readout{min-height:8em}.presets button{flex-basis:30%}.scope p{overflow-wrap:anywhere} .unit-note{font-size:12px;color:var(--muted);margin:10px 0}\n\n.metrics span{word-break:break-all;line-break:strict}.metrics>div{padding-right:6px}\n\n.cell{min-height:72px}.metrics strong{min-height:3.6em}\n\n#requirements{min-height:20em;font-size:13px;white-space:pre-line}","js":"const $=s=>document.querySelector(s);const set=(id,v)=>$('#'+id).textContent=v;const t=k=>viz.t(k);function cells(id,values){$('#'+id).replaceChildren(...values.map(v=>{const e=document.createElement('div');e.className='cell '+(v.cls||'');e.textContent=v.text;e.title=v.title||v.text;return e;}));}function pressed(mode){document.querySelectorAll('[data-mode]').forEach(e=>e.setAttribute('aria-pressed',String(e.dataset.mode===mode)));}const esc=s=>String(s).replace(/[&<>\"']/g,c=>({'&':'&','<':'<','>':'>','\"':'"',\"'\":'''}[c]));const fmt=s=>'{'+[...s].sort().join(', ')+'}';function graph(id,nodes,edges){const el=$('#'+id);el.setAttribute('viewBox','0 0 360 200');el.innerHTML='<defs><marker id=\"arrow-'+id+'\" viewBox=\"0 0 10 10\" refX=\"8\" refY=\"5\" markerWidth=\"5\" markerHeight=\"5\" orient=\"auto-start-reverse\"><path d=\"M 0 0 L 10 5 L 0 10 z\" fill=\"var(--muted)\"/></marker></defs>'+edges.map(e=>{const a=nodes[e[0]],b=nodes[e[1]],dx=b.x-a.x,dy=b.y-a.y,d=Math.hypot(dx,dy)||1;if(edges.some(r=>r[0]===e[1]&&r[1]===e[0])){const nx=-dy/d,ny=dx/d;return '<path class=\"edge '+(e[2]?'on':'')+'\" d=\"M '+(a.x+dx/d*22+nx*12)+' '+(a.y+dy/d*22+ny*12)+' Q '+((a.x+b.x)/2+nx*38)+' '+((a.y+b.y)/2+ny*38)+' '+(b.x-dx/d*25+nx*12)+' '+(b.y-dy/d*25+ny*12)+'\" marker-end=\"url(#arrow-'+id+')\"/>';}return '<line class=\"edge '+(e[2]?'on':'')+'\" x1=\"'+(a.x+dx/d*25)+'\" y1=\"'+(a.y+dy/d*25)+'\" x2=\"'+(b.x-dx/d*28)+'\" y2=\"'+(b.y-dy/d*28)+'\" marker-end=\"url(#arrow-'+id+')\"/>';}).join('')+nodes.map(n=>'<g><circle class=\"node '+(n.cls||'')+'\" cx=\"'+n.x+'\" cy=\"'+n.y+'\" r=\"25\"/><text x=\"'+n.x+'\" y=\"'+(n.y+4)+'\" text-anchor=\"middle\">'+esc(n.name)+'</text>'+(n.sub?'<text x=\"'+n.x+'\" y=\"'+(n.y+43)+'\" text-anchor=\"middle\">'+esc(n.sub)+'</text>':'')+'</g>').join('');}function table(id,rows){$('#'+id).classList.add('table');$('#'+id).replaceChildren(...rows.map(r=>{const row=document.createElement('div');row.className='tr';row.style.gridTemplateColumns='repeat('+r.length+',minmax(0,1fr))';r.forEach(x=>{const c=document.createElement('div');if(typeof x==='object'){c.textContent=x.text;c.className=x.cls||'';}else c.textContent=x;row.append(c)});return row;}));}function band(id,parts,total){$('#'+id).replaceChildren(...parts.map((p,i)=>{const e=document.createElement('i');e.style.width=(100*p.value/total)+'%';e.className=i%2?'gold':'on';e.title=p.name+': '+p.value;return e}));}function intervals(id,items,total){$('#'+id).replaceChildren(...items.map(p=>{const row=document.createElement('div');row.className='interval';const bar=document.createElement('i');bar.style.left=(100*p.start/total)+'%';bar.style.width=(100*(p.end-p.start)/total)+'%';bar.className=p.cls||'';const label=document.createElement('span');label.textContent=p.label;row.append(bar,label);return row;}));}function plot(id,series,xr,yr,opts={}){const e=$('#'+id),X=x=>42+(x-xr[0])/(xr[1]-xr[0])*298,Y=y=>175-(y-yr[0])/(yr[1]-yr[0])*148;let out='<defs><clipPath id=\"clip-'+id+'\"><rect x=\"42\" y=\"27\" width=\"298\" height=\"148\"/></clipPath></defs>';for(let i=0;i<3;i++){let x=xr[0]+i*(xr[1]-xr[0])/2,y=yr[0]+i*(yr[1]-yr[0])/2;out+='<path class=\"gridline\" d=\"M '+X(x)+' 27V175M42 '+Y(y)+'H340\"/><text x=\"'+X(x)+'\" y=\"194\" text-anchor=\"middle\">'+esc(opts.xfmt?opts.xfmt(x):Number(x.toFixed(2)))+'</text><text x=\"36\" y=\"'+(Y(y)+4)+'\" text-anchor=\"end\">'+esc(opts.yfmt?opts.yfmt(y):Number(y.toFixed(2)))+'</text>';}out+='<g clip-path=\"url(#clip-'+id+')\">';for(const s of series){out+='<path fill=\"none\" stroke=\"'+(s.color||'var(--accent)')+'\" stroke-width=\"2.5\" '+(s.dash?'stroke-dasharray=\"5 4\"':'')+' d=\"'+s.pts.map((p,i)=>(i?'L':'M')+X(p[0]).toFixed(2)+','+Y(p[1]).toFixed(2)).join(' ')+'\"/>';}for(const p of opts.points||[])out+='<circle cx=\"'+X(p[0])+'\" cy=\"'+Y(p[1])+'\" r=\"4\" fill=\"var(--second)\" stroke=\"var(--paper)\" stroke-width=\"1.5\"/>';if(opts.cursor!==undefined)out+='<path d=\"M'+X(opts.cursor)+' 27V175\" stroke=\"var(--muted)\" stroke-dasharray=\"3 3\"/>';e.innerHTML=out+'</g>';e.dataset.curves=JSON.stringify(series.map(s=>s.pts));}const curve=(fn,lo,hi,n=120)=>Array.from({length:n+1},(_,i)=>{const x=lo+(hi-lo)*i/n;return[x,fn(x)]});function inputs(draw){document.querySelectorAll('input,select').forEach(e=>{e.addEventListener('input',draw);e.addEventListener('change',draw)});draw()}const n=id=>+$('#'+id).value;const show=(id,v,d=3)=>set(id,Number(v.toFixed(d)));function draw(){let v=$('#vector').checked,f=$('#file').checked,fmt=$('#format').checked;cells('layers',[{text:'core',cls:'on'},{text:'alloc',cls:v||f?'gold':'empty'},{text:'std',cls:f?'gold':'empty'}]);set('requirements',[t('base'),fmt?t('fmt'):'',v?t('alloc'):'',f?t('std'):''].filter(Boolean).join('\\n\\n'));document.body.dataset.std=f;}inputs(draw);","audio":false,"strings":{"alloc":"alloc::Vec:最終プログラムが割り当てを提供します。","base":"core:ヒープ割り当てなしでスライスを解析します。","file":"std::fs が必要","fmt":"core::fmt::Write:呼び出し元が固定バッファを提供します。","format":"固定バッファへの整形が必要","heading":"no_std はどの依存層を外すか","intro":"必要な機能を選び、core、alloc、プラットフォームの std API を区別します。","layers":"必要な層","requirements":"最終環境に必要なもの","reset":"リセット","scope":"標準ライブラリの機能の所在を示し、入口・panic handler・原子操作は対象と成果物の種類で決まります。","scopeLabel":"モデルの範囲と前提","std":"std::fs:対象の実装が必要で、no_std 自体はファイルシステムを提供しません。","vector":"Vec が必要"}}
ランタイムを必要としないライブラリから始める
以下は、ヒープ割り当てを行わない解析関数の例です。呼び出し元が入力スライスを提供し、解析結果または明確なエラーを返します。
#! [ no_std ]
pub fn read_be_u16 ( input : & [u8 ]) -> Option< u16 > {
let bytes: [ u8 ; 2 ] = input.get ( .. 2 ) ? .try_into ( ) .ok ( ) ? ;
Some ( u16 :: from_be_bytes( bytes) )
}
これを nostd.rs として保存し、rustc --edition=2024 --crate-type=rlib nostd.rs でコンパイルします。ここで構築するのは、他のプログラムがリンクできるライブラリであり、_start、panic_handler、またはリンカースクリプトを自分で定義する必要はありません。通常の std テストプログラムから呼び出して、空の入力、短い入力、正しいビッグエンディアンをテストできます。
この分離には実用的な価値があります。プロトコル解析、ステートマシン、データ処理はテスト可能なコアライブラリに、デバイスアクセス、スケジューリング、割り当てポリシーはターゲットアダプタ層に配置します。no_std はこの依存関係の境界を実現する方法の一つです。
std ホスト上で no_std コアを検証する
前述のファイルを parser という名前のライブラリとしてコンパイルし、以下の check.rs を別途作成します。ライブラリは依然として std に依存しませんが、テストのエントリポイントはホストランタイムを使用します。
fn main ( ) {
assert_eq! ( parser:: read_be_u16( & [ ] ) , None ) ;
assert_eq! ( parser:: read_be_u16( & [ 0x12 ] ) , None ) ;
assert_eq! ( parser:: read_be_u16( & [ 0x12 , 0x34 ] ) , Some ( 0x1234 ) ) ;
assert_eq! ( parser:: read_be_u16( & [ 0x12 , 0x34 , 0xff ] ) , Some ( 0x1234 ) ) ;
}
rustc -- edition= 2024 -- crate-name parser -- crate-type= rlib nostd.rs - o libparser.rlib
rustc -- edition= 2024 check.rs -- extern parser=libparser.rlib - o check
./check
最後のアサートは、このインターフェースが最初の 2 バイトのみを読み取り、その後に追加の入力があってもよいことを明確に示しています。プロトコルでパケットが正確に 2 バイトでなければならない場合は、エントリーポイントで長さを別途チェックする必要があります。ホストでの実行は解析契約を検証できますが、ターゲット上でのアラインメント、アトミック機能、リンク、ハードウェア動作のチェックに代わるものではありません。
固定バッファでもフォーマットインターフェースを使用できる
以下を fixed.rs として個別に保存すると、alloc を全く使用しないライブラリになります。バッファは完全な UTF-8 スニペットのみを受け付けます。スペースが不足している場合、現在の write_str 呼び出しは元の値を保持します。フィールドはプライベートであり、呼び出し元が len を偽造したり、既に使用されている領域に不正なエンコーディングを書き込んだりできないようにします。
#! [ no_std ]
use core:: fmt:: { self , Write} ;
pub struct FixedText < const N: usize > {
bytes : [u8 ; N],
len : usize ,
}
impl < const N: usize > FixedText < N> {
pub fn new ( ) -> Self { Self { bytes: [ 0 ; N] , len: 0 } }
pub fn as_str ( & self ) -> & str {
core:: str:: from_utf8( & self .bytes[ .. self .len] ) .expect ( " UTF-8 invariant" )
}
pub fn replace_fmt ( & mut self , args : fmt:: Arguments< '_ > ) -> fmt:: Result {
let mut next = Self :: new( ) ;
next.write_fmt ( args) ? ;
* self = next;
Ok ( ( ) )
}
}
impl < const N: usize > Write for FixedText < N> {
fn write_str ( & mut self , text : & str ) -> fmt:: Result {
let end = self .len.checked_add ( text.len ( ) ) .ok_or ( fmt:: Error) ? ;
let destination = self .bytes.get_mut ( self .len.. end) .ok_or ( fmt:: Error) ? ;
destination.copy_from_slice ( text.as_bytes ( ) ) ;
self .len = end;
Ok ( ( ) )
}
}
ホストプログラムがこのライブラリを使用する場合、フォーマット結果を固定領域に書き込むことも、容量不足の結果を検証することもできます。
use core:: fmt:: { self , Write} ;
use fixed:: FixedText;
struct TwoParts ;
impl fmt:: Display for TwoParts {
fn fmt ( & self , out : & mut fmt:: Formatter< '_ > ) -> fmt:: Result {
out.write_str ( " ok" ) ? ;
out.write_str ( " toolong" )
}
}
fn main ( ) {
let mut text = FixedText:: < 8> :: new( ) ;
write! ( &mut text, " n={} " , 42 ) .unwrap ( ) ;
assert_eq! ( text.as_str ( ) , " n=42" ) ;
assert! ( text.write_str ( " 中中" ) .is_err ( ) ) ;
assert_eq! ( text.as_str ( ) , " n=42" ) ;
let mut partial = FixedText:: < 4> :: new( ) ;
assert! ( write! ( &mut partial, " {TwoParts} " ) .is_err ( ) ) ;
assert_eq! ( partial.as_str ( ) , " ok" ) ;
let mut committed = FixedText:: < 4> :: new( ) ;
committed.write_str ( " old" ) .unwrap ( ) ;
assert! ( committed.replace_fmt ( format_args! ( " {TwoParts}" ) ) .is_err ( ) ) ;
assert_eq! ( committed.as_str ( ) , " old" ) ;
}
parser と同様に、まず --crate-name fixed --crate-type=rlib でライブラリをコンパイルし、次に --extern fixed=libfixed.rlib でホストプログラムにリンクします。TwoParts は意図的に 2 回に分けて書き出されており、「1 回の write_str の失敗は不変」不等于「全体の write! の失敗は不変」であることを示しています。最初のスニペットは既に書き込まれており、2 番目でオーバーフローします。
replace_fmt はまず一時固定バッファに書き込み、成功してから現在の値を置き換えることで、出力全体のアトミック性を提供します。その代償として、一時的に N バイトのストレージを余分に消費します。ヒープ割り当てがないからといって、メモリ使用量が無視できるわけではありません。大きな N のローカルオブジェクトは依然としてスタックスペースを圧迫します。ここで fmt::Error はフォーマットが続行できないことを示すだけです。デバイスへの書き込みに詳細な I/O エラーを伴わせる必要がある場合は、エラーの保存またはインターフェースを別途設計する必要があります。core::fmt::Write
alloc はオプションだが、最終的な割り当て責任は消えない
割り当てを使用する no_std ライブラリは以下のように書けます。
#! [ no_std ]
extern crate alloc;
use alloc:: vec:: Vec;
pub fn copy_bytes ( input : & [u8 ])
-> Result< Vec< u8 > , alloc:: collections:: TryReserveError>
{
let mut out = Vec :: new( ) ;
out.try_reserve_exact ( input.len ( ) ) ? ;
out.extend_from_slice ( input) ;
Ok ( out)
}
スペースの予約に成功した後、u8 のコピーにさらに拡張は必要ありません。この関数は、容量不足や割り当て失敗を Result を通じて呼び出し元に渡しますが、プログラム全体のすべての割り当てが回復可能であることを証明するものではありません。最終的な実行環境は、alloc が必要とするグローバル割り当てなどのリンク条件を満たす必要があります。通常の std プログラムは通常、これを提供しています。
ボトムレスのカスタムアロケータは、アラインメント、レイアウトの一致、並行性、割り込みコンテキストなどの規約を満たす必要があります。bump ポインターの例を、任意のマルチスレッドプログラムで利用可能な GlobalAlloc 実装として扱ってはなりません。
no_main、パニック、ハードウェア起動は別の決定事項のグループ
#![no_main] は通常の main エントリポイントの配置を無効にし、no_std から自動的に暗黙的に導出されるものではありません。ボトムレスの実行ファイルには、通常、ターゲットの起動コード、初期スタック、リンクレイアウト、データ初期化、割り込みベクトルが必要です。これらはチップおよび実行フレームワークに依存し、空の loop ですべての起動作業を代表することはできません。
最終的に std がないプログラムでは、どこかで panic handler を提供する必要があります。各ライブラリが独自に定義すると重複します。panic handler はプラットフォームに応じてログ記録、リセット、または停止を行うことができ、必ずしも出力できないわけではありません。展開のサポートは、ターゲット、ランタイム、ビルド戦略によって共同で決定されます。Embedded Rust の no_std
同様に、ビジーウェイトループは低消費電力待機とは異なり、割り込みが開いているかどうか、ウォッチドッグがリセットするかどうかは、実際の動作に影響を与える可能性があります。これらはターゲット実行環境に属し、プラットフォームのチュートリアルで明確にする必要があります。
Rust-for-Linux:ターゲットカーネルソースコードをインターフェースとして
Linux 6.1 で初步的な Rust サポートがマージされましたが、それがすべてのアーキテクチャ、構成、またはディストリビューションで任意の Rust モジュールを直接ビルドできることを意味するものではありません。カーネル Rust API は継続的に進化しており、古いブログ記事にある kernel::file::Operations などのコードは、すべてのバージョンでコンパイル可能なテンプレートとして扱えません。
Linux v6.18 の rust_minimal を読み始めの起点とします。module! はモジュールのメタデータを宣言し、Module::init はモジュールの状態を返し、Drop は終了時のクリーンアップを処理します。例では KVec を使用し、push 時に明示的に GFP_KERNEL を渡して ? で失敗を伝播します。これは、ユーザー空間の Vec、ファイル操作トレイト、架空のシグネチャを貼り合わせたものよりも、実際のインターフェースをよりよく反映しています。v6.18 最小モジュール
学習時は、まずターゲットカーネルソースツリー内で依存関係を確認し、その後、そのバージョンに付属するサンプルをビルドします。
make LLVM=1 rustavailable
その後、そのツリーの構成依存関係に従って Rust と対応するサンプルを有効にし、カーネルビルドシステムを使用してビルドします。rustavailable チェックツールのサポートは、構成や実際のコンパイルに代わるものではありません。Rust、bindgen、LLVM の要件は、ターゲット版本文書を読んで確認すべきであり、「最新バージョンを適当にインストールする」と固定して記述すべきではありません。カーネル Rust クイックスタート
カーネル内での所有権は実行コンテキストによって制約される
ユーザー空間の直感 カーネル内でさらに問うべきこと
割り当て成功後に使用する 現在の位置でスリープは許可されているか?割り当て失敗をどう返すか?
Mutex をロックすればよい 現在、割り込み/アトミックコンテキストにあるか?ロック順序はどのように保証するか?
Drop で自動クリーンアップ オブジェクトは依然としてコールバック、ワークキュー、またはデバイスアクセスによって保持されているか?クリーンアップはブロックできるか?
参照カウントが 1 つあれば十分 デバイスの取り外し、モジュールのアンロード、非同期実行をどのように調整するか?
カーネルは独自の割り当て、同期、エラー抽象化を提供しており、std::sync::Mutex やユーザー空間のスレッドモデルで直接置き換えることはできません。unsafe によるカプセル化では、これらの追加条件を契約に組み込む必要があり、借用チェッカーはハードウェアが DMA を行っていることや、C のコールバックがまだ終了していないことを自動的に理解しません。
カーネルのパニック動作を「必ず BUG() を呼び出し、カーネル全体を停止する」と一般化することはできません。実装はバージョンと構成によって変化し、例外後の影響は具体的なカーネルパスに依存します。ターゲットバージョンの panic handler と実行戦略を確認する必要があります。結果がどうであれ、パニックはカーネル内で通常予期される失敗を処理するための代替手段ではありません。カーネル Rust 概要
純粋な論理ライブラリ 長さ、オーバーフロー、状態不変条件 対象でコンパイル・リンク ターゲット core / ABI / シンボル ターゲット環境での実行 起動・デバイス・割り込み・終了 各階層は新たな条件を追加するが、前の階層の契約も保持する 段階的検証:ホストでの成功はターゲット実行環境を自動的に補完しない カーネルモジュールはターゲットソースツリーのビルドエントリーポイントを使用し、ユーザー空間のグローバルアロケ ータや起動コードを自分でインストールしない。
初期化と終了をリソース依存関係として捉える
デバイスオブジェクトがまずリソースを取得し、次にコールバックを登録し、最後にワークキューがそれを使用できるように設定すると仮定します。初期化が 2 番目のステップで失敗した場合、1 番目のステップのリソースは確立された所有者によって回収されるべきです。登録に成功した後に失敗した場合は、登録解除を行い、サブシステムの規約に従って進行中の使用が終了するのを待つ必要があります。終了時の鍵は、機械的にいくつかの free を呼び出すことではなく、新しいアクセスを停止し、既存のアクセスを終了させ、最後に参照されている状態を解放することです。
借用と参照カウントはソフトウェアオブジェクトの寿命を表現するのに役立ちますが、DMA、ハードウェア割り込み、C で保存されたコンテキストは自動的に Rust の参照にはなりません。ターゲットサブシステムのシャットダウン、同期、登録解除インターフェースによって「最後のアクセスが終了した」という事実を確立してから、Drop による解放を許可する必要があります。一部の登録解除は待機またはスリープを伴うため、終了はブロックが許可されたコンテキストで発生する必要があります。
検証結果 得られた証拠 未カバー
no_std rlib のコンパイル成功 このライブラリはこのターゲットと feature でコンパイル可能 最終エントリーポイント、アロケータ、実行環境
std ホスト境界テスト通過 テスト入力に対する論理動作 ターゲットハードウェア、割り込み、カーネルコンテキスト
rustavailable 成功 ターゲットソースツリーが現在の Rust ツールサポートを認識 必要な構成、モジュールリンクとロード
モジュールのビルド完了 選択されたソース/構成がモジュール製品を生成可能 デバイス相互作用、アンロード競合、負荷動作
推奨される学習の進行順序
まず、純粋なデータ処理をホストでテスト可能な no_std ライブラリとして記述します。次に、ターゲット実行フレームワークでパニック、ログ、割り当てを接続します。最後に、ターゲットカーネルバージョンに既に存在するデバイスまたはサブシステムのサンプルを読み、そのライフサイクルを一つずつ理解します。これにより、言語の問題、ターゲットランタイムの問題、カーネルインターフェースの問題を区別でき、一度に3つの未知の条件を抱え込むことを避けることができます。