<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://baymine.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://baymine.github.io/" rel="alternate" type="text/html" /><updated>2025-06-26T01:25:37+00:00</updated><id>https://baymine.github.io/feed.xml</id><title type="html">Baymine’s Blog</title><subtitle>Data Engineer sharing thoughts on technology, programming, and life</subtitle><author><name>York Cao</name></author><entry><title type="html">Gemini CLI: Key Takeaways from Hacker News Discussion</title><link href="https://baymine.github.io/2025/06/26/gemini-cli/" rel="alternate" type="text/html" title="Gemini CLI: Key Takeaways from Hacker News Discussion" /><published>2025-06-26T00:58:00+00:00</published><updated>2025-06-26T00:58:00+00:00</updated><id>https://baymine.github.io/2025/06/26/gemini-cli</id><content type="html" xml:base="https://baymine.github.io/2025/06/26/gemini-cli/"><![CDATA[<h1 id="gemini-cli-key-takeaways-from-hacker-news-discussion">Gemini CLI: Key Takeaways from Hacker News Discussion</h1>

<p>Google recently announced their <a href="https://blog.google/technology/developers/introducing-gemini-cli-open-source-ai-agent/">Gemini CLI</a>, an open-source AI agent for command-line interactions. The Hacker News discussion (<a href="https://news.ycombinator.com/item?id=44376919">item #44376919</a>) revealed significant insights about Google’s AI strategy, developer adoption challenges, and the competitive landscape.</p>

<h2 id="1-key-arguments--logic">1. Key Arguments &amp; Logic</h2>

<h3 id="product-fragmentation-concerns">Product Fragmentation Concerns</h3>
<p>The most prominent argument centers on Google’s confusing product ecosystem. Users consistently point to:</p>

<p><strong>Deductive reasoning pattern</strong>: Multiple overlapping products → User confusion → Reduced adoption</p>
<ul>
  <li>Evidence: “I love how fragmented Google’s Gemini offerings are” - users struggle to understand which product serves what purpose</li>
  <li>Supporting data: 9 different Google One tiers, 5 called “Premium”, with inconsistent AI feature inclusion</li>
</ul>

<h3 id="pricing-strategy-critique">Pricing Strategy Critique</h3>
<p><strong>Logical structure</strong>: Complex pricing → Barrier to entry → Competitive disadvantage</p>
<ul>
  <li><strong>Analogy used</strong>: Compared to Apple’s App Store ecosystem where complexity creates friction</li>
  <li><strong>Critical thinking pattern</strong>: Users apply cost-benefit analysis, concluding simpler competitors (Claude, OpenAI) offer better value propositions</li>
</ul>

<h3 id="technical-architecture-debates">Technical Architecture Debates</h3>
<p><strong>Reasoning pattern</strong>: API design choices → Developer experience → Platform adoption</p>
<ul>
  <li><strong>Evidence</strong>: Vertex API vs Google AI Studio API confusion creates scaling problems</li>
  <li><strong>Fallacy identified</strong>: False dichotomy - users shouldn’t need to choose between ease-of-use and enterprise features</li>
</ul>

<h2 id="2-knowledge--expertise">2. Knowledge &amp; Expertise</h2>

<h3 id="domain-specific-terms">Domain-Specific Terms</h3>
<ul>
  <li><strong>Vertex AI</strong>: Google’s enterprise ML platform with comprehensive model management</li>
  <li><strong>Google AI Studio</strong>: Simplified interface for prototyping, separate from GCP billing</li>
  <li><strong>MCP (Model Context Protocol)</strong>: Fine-grained permission system for AI tools</li>
  <li><strong>OpenTelemetry</strong>: Observability framework now integrated into AI CLI tools</li>
</ul>

<h3 id="cross-disciplinary-connections">Cross-Disciplinary Connections</h3>
<ul>
  <li><strong>DevOps Integration</strong>: CLI tools increasingly adopting enterprise observability standards</li>
  <li><strong>Product Management</strong>: Discussion reveals tension between feature velocity and user experience coherence</li>
  <li><strong>Enterprise Architecture</strong>: Comparison with Microsoft’s unified ecosystem approach</li>
</ul>

<h3 id="credible-sources-referenced">Credible Sources Referenced</h3>
<ul>
  <li>Google Cloud TAM (Technical Account Manager) direct engagement in thread</li>
  <li>Real user experiences with billing systems across platforms</li>
  <li>Comparative analysis with established tools (Aider, Claude Code, Cursor)</li>
</ul>

<h2 id="3-diverse-perspectives">3. Diverse Perspectives</h2>

<h3 id="pro-google-arguments">Pro-Google Arguments</h3>
<p><strong>Motivation</strong>: Technical superiority focus</p>
<ul>
  <li>“Gemini 2.5 Pro is the best model I’ve used (even better than o3 IMO)”</li>
  <li>Generous free tier: “60 model requests per minute and 1,000 requests per day at no charge”</li>
  <li>Google Workspace integration provides comprehensive value at $14/month</li>
</ul>

<h3 id="critical-perspectives">Critical Perspectives</h3>
<p><strong>Motivation</strong>: User experience and business sustainability concerns</p>
<ul>
  <li>Fragmented product strategy creates adoption barriers</li>
  <li>Privacy concerns: “Google’s free offers have no privacy protections whatsoever”</li>
  <li>Reliability issues: “reliability for the gemini api is garbage, whereas for vertex ai it is fantastic”</li>
</ul>

<h3 id="developer-tool-preferences">Developer Tool Preferences</h3>
<p><strong>Underlying motivations</strong>:</p>
<ul>
  <li><strong>Simplicity seekers</strong>: Prefer Claude Code’s flat-rate pricing to avoid billing anxiety</li>
  <li><strong>Power users</strong>: Value Aider’s flexibility and model-agnostic approach</li>
  <li><strong>Enterprise users</strong>: Need Vertex AI’s reliability and compliance features</li>
</ul>

<h2 id="4-actionable-insights">4. Actionable Insights</h2>

<h3 id="practical-tips">Practical Tips</h3>
<ol>
  <li><strong>For Google API usage</strong>: Use personal Gmail account without billing enabled to access generous free limits without surprise charges</li>
  <li><strong>Cost optimization</strong>: “If you do annual billing for ‘Premium (5 TB)’, you end up paying $21/month for 5TB of storage and the same AI features”</li>
  <li><strong>Production deployment</strong>: “The key to running LLM services in prod is setting up Gemini in Vertex, Anthropic models on AWS Bedrock and OpenAI models on Azure”</li>
  <li><strong>Security best practice</strong>: Never put API keys in URL parameters - use headers instead to avoid logging exposure</li>
</ol>

<h3 id="common-pitfalls">Common Pitfalls</h3>
<ol>
  <li><strong>Billing confusion</strong>: Mixing personal and enterprise Google accounts creates subscription management nightmares</li>
  <li><strong>API limitations</strong>: Google AI Studio API has scaling restrictions that force migration to Vertex</li>
  <li><strong>Permission management</strong>: CLI tools with broad system access need careful permission scoping</li>
  <li><strong>Model selection</strong>: Free tiers may automatically route to cheaper models without user awareness</li>
</ol>

<h3 id="recommended-resources">Recommended Resources</h3>
<ul>
  <li><strong>Alternative tools</strong>: Aider for model-agnostic CLI coding assistance</li>
  <li><strong>Enterprise setup</strong>: Use cloud provider managed services (Bedrock, Azure) for production reliability</li>
  <li><strong>Development workflow</strong>: Consider SST’s OpenCode for integrated development experience</li>
  <li><strong>Monitoring</strong>: Leverage OpenTelemetry integration for observability in AI workflows</li>
</ul>

<hr />

<p><strong>Key Takeaway</strong>: While Google’s Gemini CLI offers impressive technical capabilities and generous free tiers, the company’s fragmented product strategy and complex pricing structure create significant adoption barriers. Developers consistently prefer simpler, more predictable alternatives despite potentially superior underlying technology. Success in the AI tools market increasingly depends on user experience coherence rather than just technical performance.</p>]]></content><author><name>York Cao</name></author><category term="HackNews" /><category term="AI" /><category term="Google" /><category term="CLI" /><category term="Developer-Tools" /><summary type="html"><![CDATA[Gemini CLI: Key Takeaways from Hacker News Discussion]]></summary></entry><entry><title type="html">How to Use Mermaid Diagrams in Your Blog</title><link href="https://baymine.github.io/2025/06/20/mermaid-guide/" rel="alternate" type="text/html" title="How to Use Mermaid Diagrams in Your Blog" /><published>2025-06-20T10:30:00+00:00</published><updated>2025-06-20T10:30:00+00:00</updated><id>https://baymine.github.io/2025/06/20/mermaid-guide</id><content type="html" xml:base="https://baymine.github.io/2025/06/20/mermaid-guide/"><![CDATA[<h1 id="how-to-use-mermaid-diagrams-in-your-blog">How to Use Mermaid Diagrams in Your Blog</h1>

<p>Mermaid is now fully configured in your Jekyll blog with a custom hacker theme! This guide shows you how to create various types of diagrams.</p>

<h2 id="basic-syntax">Basic Syntax</h2>

<p>To create a Mermaid diagram, use a code block with the <code class="language-plaintext highlighter-rouge">mermaid</code> language identifier:</p>

<div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">```</span><span class="nl">mermaid
</span><span class="sb">graph TD
    A[Start] --&gt; B[End]</span>
<span class="p">```</span>
</code></pre></div></div>

<h2 id="supported-diagram-types">Supported Diagram Types</h2>

<h3 id="1-flowcharts">1. Flowcharts</h3>

<p>Perfect for showing processes and decision flows:</p>

<pre><code class="language-mermaid">graph TD
    A[User Request] --&gt; B{Authentication}
    B --&gt;|Valid| C[Process Request]
    B --&gt;|Invalid| D[Return Error]
    C --&gt; E[Return Response]
    D --&gt; F[Log Error]
</code></pre>

<h3 id="2-sequence-diagrams">2. Sequence Diagrams</h3>

<p>Great for API interactions and system communications:</p>

<pre><code class="language-mermaid">sequenceDiagram
    participant Client
    participant API
    participant Database
    
    Client-&gt;&gt;API: POST /login
    API-&gt;&gt;Database: Validate credentials
    Database--&gt;&gt;API: User data
    API--&gt;&gt;Client: JWT token
</code></pre>

<h3 id="3-class-diagrams">3. Class Diagrams</h3>

<p>Useful for software architecture documentation:</p>

<pre><code class="language-mermaid">classDiagram
    class User {
        +String username
        +String email
        +login()
        +logout()
    }
    class Admin {
        +manageUsers()
        +viewLogs()
    }
    User &lt;|-- Admin
</code></pre>

<h3 id="4-state-diagrams">4. State Diagrams</h3>

<p>Perfect for showing system states and transitions:</p>

<pre><code class="language-mermaid">stateDiagram-v2
    [*] --&gt; Idle
    Idle --&gt; Loading : fetch_data
    Loading --&gt; Success : data_received
    Loading --&gt; Error : fetch_failed
    Success --&gt; Idle : reset
    Error --&gt; Idle : retry
</code></pre>

<h3 id="5-gantt-charts">5. Gantt Charts</h3>

<p>Great for project timelines:</p>

<pre><code class="language-mermaid">gantt
    title Development Timeline
    dateFormat  YYYY-MM-DD
    section Backend
    API Development    :a1, 2024-01-01, 30d
    Database Setup     :a2, after a1, 15d
    section Frontend
    UI Development     :b1, 2024-01-15, 25d
    Integration        :b2, after a2, 10d
</code></pre>

<h3 id="6-mind-maps">6. Mind Maps</h3>

<p>Excellent for brainstorming and concept mapping:</p>

<pre><code class="language-mermaid">mindmap
  root((Blog Features))
    Content
      Posts
      Pages
      Comments
    Design
      Theme
      Layout
      Responsive
    Technical
      Jekyll
      Mermaid
      GitHub Pages
</code></pre>

<h2 id="styling-features">Styling Features</h2>

<p>Your Mermaid diagrams automatically inherit the hacker theme with:</p>

<ul>
  <li><strong>Green terminal colors</strong> (<code class="language-plaintext highlighter-rouge">#00ff41</code>)</li>
  <li><strong>Dark background</strong> (<code class="language-plaintext highlighter-rouge">#0a0a0a</code>)</li>
  <li><strong>Monospace font</strong> (Fira Code)</li>
  <li><strong>Glitch hover effects</strong></li>
  <li><strong>Terminal-style borders</strong></li>
</ul>

<h2 id="tips-for-better-diagrams">Tips for Better Diagrams</h2>

<ol>
  <li><strong>Keep it simple</strong>: Don’t overcrowd diagrams</li>
  <li><strong>Use meaningful labels</strong>: Make node text descriptive</li>
  <li><strong>Consistent styling</strong>: Stick to the theme colors</li>
  <li><strong>Logical flow</strong>: Arrange elements in reading order</li>
  <li><strong>Test rendering</strong>: Preview your diagrams before publishing</li>
</ol>

<h2 id="advanced-features">Advanced Features</h2>

<h3 id="subgraphs">Subgraphs</h3>

<p>Group related elements:</p>

<pre><code class="language-mermaid">graph TB
    subgraph "Frontend"
        A[React App]
        B[Components]
    end
    subgraph "Backend"
        C[API Server]
        D[Database]
    end
    A --&gt; C
    C --&gt; D
</code></pre>

<h3 id="styling-individual-elements">Styling Individual Elements</h3>

<pre><code class="language-mermaid">graph LR
    A[Normal] --&gt; B[Highlighted]
    B --&gt; C[Important]
    
    classDef highlight fill:#ff9999
    classDef important fill:#99ff99
    
    class B highlight
    class C important
</code></pre>

<h2 id="troubleshooting">Troubleshooting</h2>

<p>If diagrams don’t render:</p>

<ol>
  <li>Check syntax with <a href="https://mermaid.live/">Mermaid Live Editor</a></li>
  <li>Ensure proper code block formatting</li>
  <li>Verify no special characters in diagram code</li>
  <li>Check browser console for JavaScript errors</li>
</ol>

<h2 id="resources">Resources</h2>

<ul>
  <li><a href="https://mermaid.js.org/">Mermaid Documentation</a></li>
  <li><a href="https://mermaid.js.org/syntax/flowchart.html">Syntax Reference</a></li>
  <li><a href="https://mermaid.live/">Live Editor</a></li>
</ul>

<p>Happy diagramming! 🎨</p>]]></content><author><name>York Cao</name></author><category term="mermaid" /><category term="diagrams" /><category term="documentation" /><category term="tutorial" /><summary type="html"><![CDATA[How to Use Mermaid Diagrams in Your Blog]]></summary></entry><entry><title type="html">Doris UDF 工作原理</title><link href="https://baymine.github.io/2025/06/20/doris-udf-%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86/" rel="alternate" type="text/html" title="Doris UDF 工作原理" /><published>2025-06-20T10:12:00+00:00</published><updated>2025-06-20T10:12:00+00:00</updated><id>https://baymine.github.io/2025/06/20/doris-udf-%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86</id><content type="html" xml:base="https://baymine.github.io/2025/06/20/doris-udf-%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86/"><![CDATA[<h2 id="doris-udf-工作原理">Doris UDF 工作原理</h2>

<p>Doris 支持用户自定义函数（User Defined Functions, UDF）来扩展其功能。本文档将详细解释 Doris 中 UDF 的架构和实现原理。</p>

<h3 id="udf-类型">UDF 类型</h3>

<p>Doris 支持以下几种 UDF 类型：</p>
<ol>
  <li>标量 UDF (Scalar UDF) - 对每一行输入返回单个值</li>
  <li>聚合 UDF (UDAF, User Defined Aggregate Function) - 将多行数据聚合为单个值</li>
  <li>表值 UDF (UDTF, User Defined Table Function) - 对每一行输入返回多行或多列数据</li>
</ol>

<h3 id="架构概览">架构概览</h3>

<pre><code class="language-mermaid">graph TD
    A[包含 UDF 的 SQL 查询] --&gt; B[FE: 解析和规划]
    B --&gt; C[BE: 创建函数上下文]
    C --&gt; D[加载 UDF 实现]
    D --&gt; E[执行 UDF]
    E --&gt; F[返回结果]

    subgraph "函数上下文"
    G[线程本地状态]
    H[Fragment 本地状态]
    I[参数和类型]
    end

    subgraph "UDF 执行"
    J[准备阶段]
    K[执行阶段] 
    L[清理阶段]
    end
</code></pre>

<h3 id="实现细节">实现细节</h3>

<h4 id="1-函数上下文">1. 函数上下文</h4>

<p><code class="language-plaintext highlighter-rouge">FunctionContext</code> 类是 UDF 与 Doris 系统之间的接口。主要组件包括：</p>

<pre><code class="language-mermaid">classDiagram
    class FunctionContext {
        +RuntimeState* state
        +TypeDescriptor return_type
        +vector&lt;TypeDescriptor&gt; arg_types
        +void* thread_local_fn_state
        +void* fragment_local_fn_state
        +create_context()
        +get_arg_type()
        +add_warning()
    }
</code></pre>

<h4 id="2-java-udf-实现">2. Java UDF 实现</h4>

<p>Doris 使用 JNI 来桥接 C++ 和 Java：</p>

<pre><code class="language-mermaid">sequenceDiagram
    participant SQL
    participant BE
    participant JNI
    participant Java

    SQL-&gt;&gt;BE: 执行 UDF
    BE-&gt;&gt;JNI: 初始化 JVM
    JNI-&gt;&gt;Java: 加载 UDF 类
    Java-&gt;&gt;JNI: 注册方法
    BE-&gt;&gt;JNI: 调用 UDF 方法
    JNI-&gt;&gt;Java: 执行
    Java-&gt;&gt;JNI: 返回结果
    JNI-&gt;&gt;BE: 转换结果
    BE-&gt;&gt;SQL: 返回值
</code></pre>

<h3 id="核心组件">核心组件</h3>

<ol>
  <li><strong>UDF 注册</strong>
    <ul>
      <li>UDF 通过函数名、返回类型和参数类型进行注册</li>
      <li>对于 Java UDF，jar 文件会被加载并缓存</li>
    </ul>
  </li>
  <li><strong>函数上下文管理</strong>
    <ul>
      <li>支持线程本地和 Fragment 本地状态</li>
      <li>处理内存管理和错误报告</li>
      <li>提供对参数类型和值的访问</li>
    </ul>
  </li>
  <li><strong>执行流程</strong>
    <ul>
      <li>Open：初始化资源并加载实现</li>
      <li>Execute：处理输入数据并生成结果</li>
      <li>Close：清理资源</li>
    </ul>
  </li>
  <li><strong>类型系统</strong>
    <ul>
      <li>通过 TypeDescriptor 支持各种数据类型</li>
      <li>处理空值和类型转换</li>
    </ul>
  </li>
</ol>

<h3 id="实现类">实现类</h3>

<p>主要实现类包括：</p>

<ol>
  <li><strong>JavaFunctionCall</strong>
    <ul>
      <li>处理 Java UDF 生命周期</li>
      <li>管理 JNI ���下文和方法调用</li>
      <li>在 Doris 和 Java 数据类型之间进行转换</li>
    </ul>
  </li>
  <li><strong>AggregateJavaUdaf</strong>
    <ul>
      <li>实现聚合逻辑</li>
      <li>管理多行数据的状态</li>
      <li>处理序列化/反序列化</li>
    </ul>
  </li>
  <li><strong>UDFTableFunction</strong>
    <ul>
      <li>支持表值函数</li>
      <li>管理多行/多列输出</li>
      <li>处理向量化执行</li>
    </ul>
  </li>
</ol>

<h3 id="错误处理和资源管理">错误处理和资源管理</h3>

<ol>
  <li><strong>错误报告</strong>
    <div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">bool</span> <span class="n">FunctionContext</span><span class="o">::</span><span class="n">add_warning</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span><span class="o">*</span> <span class="n">warning_msg</span><span class="p">)</span> <span class="p">{</span>
 <span class="k">if</span> <span class="p">(</span><span class="n">_num_warnings</span><span class="o">++</span> <span class="o">&gt;=</span> <span class="n">MAX_WARNINGS</span><span class="p">)</span> <span class="p">{</span>
     <span class="k">return</span> <span class="nb">false</span><span class="p">;</span>
 <span class="p">}</span>
 <span class="n">std</span><span class="o">::</span><span class="n">stringstream</span> <span class="n">ss</span><span class="p">;</span>
 <span class="n">ss</span> <span class="o">&lt;&lt;</span> <span class="s">"UDF WARNING: "</span> <span class="o">&lt;&lt;</span> <span class="n">warning_msg</span><span class="p">;</span>
 <span class="k">if</span> <span class="p">(</span><span class="n">_state</span> <span class="o">!=</span> <span class="nb">nullptr</span><span class="p">)</span> <span class="p">{</span>
     <span class="k">return</span> <span class="n">_state</span><span class="o">-&gt;</span><span class="n">log_error</span><span class="p">(</span><span class="n">ss</span><span class="p">.</span><span class="n">str</span><span class="p">());</span>
 <span class="p">}</span>
 <span class="k">return</span> <span class="nb">true</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>    </div>
  </li>
  <li><strong>资源清理</strong>
    <pre><code class="language-mermaid">graph TD
 A[开始] --&gt; B[关闭 JNI 上下文]
 B --&gt; C[释放全局引用]
 C --&gt; D[删除本地引用]
 D --&gt; E[清理线程状态]
 E --&gt; F[结束]
</code></pre>
  </li>
</ol>

<h3 id="最佳实践">最佳实践</h3>

<h4 id="1-内存管理">1. 内存管理</h4>

<p>不当的内存管理可能导致内存泄漏或过度的 GC 开销。以下是正确的处理方式：</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// ❌ 错误示范：可能导致内存泄漏</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">LeakyUDF</span> <span class="kd">extends</span> <span class="nc">ScalarFunction</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="nc">ArrayList</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">&gt;</span> <span class="n">cache</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">&lt;&gt;();</span>
    
    <span class="kd">public</span> <span class="nc">String</span> <span class="nf">evaluate</span><span class="o">(</span><span class="nc">String</span> <span class="n">input</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">cache</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">input</span><span class="o">);</span>  <span class="c1">// 列表无限增长</span>
        <span class="k">return</span> <span class="nf">process</span><span class="o">(</span><span class="n">input</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>

<span class="c1">// ✅ 正确示范：合理���内存管理</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">EfficientUDF</span> <span class="kd">extends</span> <span class="nc">ScalarFunction</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="nc">LRUCache</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">,</span> <span class="nc">String</span><span class="o">&gt;</span> <span class="n">cache</span><span class="o">;</span>
    
    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">open</span><span class="o">(</span><span class="nc">FunctionContext</span> <span class="n">context</span><span class="o">)</span> <span class="o">{</span>
        <span class="c1">// 初始化固定大小的缓存</span>
        <span class="n">cache</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">LRUCache</span><span class="o">&lt;&gt;(</span><span class="mi">1000</span><span class="o">);</span>
    <span class="o">}</span>
    
    <span class="kd">public</span> <span class="nc">String</span> <span class="nf">evaluate</span><span class="o">(</span><span class="nc">String</span> <span class="n">input</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">cache</span><span class="o">.</span><span class="na">containsKey</span><span class="o">(</span><span class="n">input</span><span class="o">))</span> <span class="o">{</span>
            <span class="k">return</span> <span class="n">cache</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">input</span><span class="o">);</span>
        <span class="o">}</span>
        <span class="nc">String</span> <span class="n">result</span> <span class="o">=</span> <span class="n">process</span><span class="o">(</span><span class="n">input</span><span class="o">);</span>
        <span class="n">cache</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">input</span><span class="o">,</span> <span class="n">result</span><span class="o">);</span>
        <span class="k">return</span> <span class="n">result</span><span class="o">;</span>
    <span class="o">}</span>
    
    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">close</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">cache</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">cache</span><span class="o">.</span><span class="na">clear</span><span class="o">();</span>
            <span class="n">cache</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<h4 id="2-线程安全">2. 线程安全</h4>

<p>在分布式环境中运行的 UDF 必须确保线程安全。以下是处理共享状态的方法：</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// ❌ 错误示范：线程不安全</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">UnsafeUDF</span> <span class="kd">extends</span> <span class="nc">ScalarFunction</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="kd">static</span> <span class="nc">Map</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">,</span> <span class="nc">String</span><span class="o">&gt;</span> <span class="n">sharedState</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">HashMap</span><span class="o">&lt;&gt;();</span>  <span class="c1">// 线程间共享</span>
    
    <span class="kd">public</span> <span class="nc">String</span> <span class="nf">evaluate</span><span class="o">(</span><span class="nc">String</span> <span class="n">key</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">return</span> <span class="n">sharedState</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">key</span><span class="o">);</span>  <span class="c1">// 可能发生竞态条件</span>
    <span class="o">}</span>
<span class="o">}</span>

<span class="c1">// ✅ 正确示范：线程安全实现</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">ThreadSafeUDF</span> <span class="kd">extends</span> <span class="nc">ScalarFunction</span> <span class="o">{</span>
    <span class="c1">// 线程本地存储的可变数据</span>
    <span class="kd">private</span> <span class="nc">ThreadLocal</span><span class="o">&lt;</span><span class="nc">Map</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">,</span> <span class="nc">String</span><span class="o">&gt;&gt;</span> <span class="n">threadLocalCache</span><span class="o">;</span>
    <span class="c1">// 不可变的共享状态</span>
    <span class="kd">private</span> <span class="kd">static</span> <span class="kd">final</span> <span class="nc">Map</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">,</span> <span class="nc">String</span><span class="o">&gt;</span> <span class="no">SHARED_CONSTANTS</span><span class="o">;</span>
    
    <span class="kd">static</span> <span class="o">{</span>
        <span class="nc">Map</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">,</span> <span class="nc">String</span><span class="o">&gt;</span> <span class="n">constants</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">HashMap</span><span class="o">&lt;&gt;();</span>
        <span class="n">constants</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">"key1"</span><span class="o">,</span> <span class="s">"value1"</span><span class="o">);</span>
        <span class="no">SHARED_CONSTANTS</span> <span class="o">=</span> <span class="nc">Collections</span><span class="o">.</span><span class="na">unmodifiableMap</span><span class="o">(</span><span class="n">constants</span><span class="o">);</span>
    <span class="o">}</span>
    
    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">open</span><span class="o">(</span><span class="nc">FunctionContext</span> <span class="n">context</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">threadLocalCache</span> <span class="o">=</span> <span class="nc">ThreadLocal</span><span class="o">.</span><span class="na">withInitial</span><span class="o">(</span><span class="nl">HashMap:</span><span class="o">:</span><span class="k">new</span><span class="o">);</span>
    <span class="o">}</span>
    
    <span class="kd">public</span> <span class="nc">String</span> <span class="nf">evaluate</span><span class="o">(</span><span class="nc">String</span> <span class="n">key</span><span class="o">)</span> <span class="o">{</span>
        <span class="c1">// 优先检查线程本地缓存</span>
        <span class="nc">Map</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">,</span> <span class="nc">String</span><span class="o">&gt;</span> <span class="n">localCache</span> <span class="o">=</span> <span class="n">threadLocalCache</span><span class="o">.</span><span class="na">get</span><span class="o">();</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">localCache</span><span class="o">.</span><span class="na">containsKey</span><span class="o">(</span><span class="n">key</span><span class="o">))</span> <span class="o">{</span>
            <span class="k">return</span> <span class="n">localCache</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">key</span><span class="o">);</span>
        <span class="o">}</span>
        <span class="c1">// 回退到不可变共享状态</span>
        <span class="k">return</span> <span class="no">SHARED_CONSTANTS</span><span class="o">.</span><span class="na">getOrDefault</span><span class="o">(</span><span class="n">key</span><span class="o">,</span> <span class="s">"default"</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<h4 id="3-性能优化">3. 性能优化</h4>

<p>优化 UDF 以支持向量化执行并最小化 JNI 开销：</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// ❌ 错误示范：逐行处理</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">SlowUDF</span> <span class="kd">extends</span> <span class="nc">ScalarFunction</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="nc">String</span> <span class="nf">evaluate</span><span class="o">(</span><span class="nc">String</span> <span class="n">input</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">return</span> <span class="nf">heavyProcessing</span><span class="o">(</span><span class="n">input</span><span class="o">);</span>  <span class="c1">// 每行一次 JNI 调用</span>
    <span class="o">}</span>
<span class="o">}</span>

<span class="c1">// ✅ 正确示范：向量化处理</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">FastUDF</span> <span class="kd">extends</span> <span class="nc">ScalarFunction</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="no">BATCH_SIZE</span> <span class="o">=</span> <span class="mi">1024</span><span class="o">;</span>
    <span class="kd">private</span> <span class="nc">List</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">&gt;</span> <span class="n">batch</span><span class="o">;</span>
    
    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">open</span><span class="o">(</span><span class="nc">FunctionContext</span> <span class="n">context</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">batch</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">&lt;&gt;(</span><span class="no">BATCH_SIZE</span><span class="o">);</span>
    <span class="o">}</span>
    
    <span class="kd">public</span> <span class="nc">String</span> <span class="nf">evaluate</span><span class="o">(</span><span class="nc">String</span> <span class="n">input</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">batch</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">input</span><span class="o">);</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">batch</span><span class="o">.</span><span class="na">size</span><span class="o">()</span> <span class="o">&gt;=</span> <span class="no">BATCH_SIZE</span><span class="o">)</span> <span class="o">{</span>
            <span class="c1">// 批量处理</span>
            <span class="nc">List</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">&gt;</span> <span class="n">results</span> <span class="o">=</span> <span class="n">processBatch</span><span class="o">(</span><span class="n">batch</span><span class="o">);</span>
            <span class="n">batch</span><span class="o">.</span><span class="na">clear</span><span class="o">();</span>
            <span class="k">return</span> <span class="n">results</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">results</span><span class="o">.</span><span class="na">size</span><span class="o">()</span> <span class="o">-</span> <span class="mi">1</span><span class="o">);</span>
        <span class="o">}</span>
        <span class="k">return</span> <span class="kc">null</span><span class="o">;</span>  <span class="c1">// 由 Doris 处理</span>
    <span class="o">}</span>
    
    <span class="kd">private</span> <span class="nc">List</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">&gt;</span> <span class="nf">processBatch</span><span class="o">(</span><span class="nc">List</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">&gt;</span> <span class="n">inputs</span><span class="o">)</span> <span class="o">{</span>
        <span class="c1">// 批量处理多个输入</span>
        <span class="c1">// 减少 JNI 调用次数，提高 CPU 利用率</span>
        <span class="k">return</span> <span class="n">inputs</span><span class="o">.</span><span class="na">parallelStream</span><span class="o">()</span>
                    <span class="o">.</span><span class="na">map</span><span class="o">(</span><span class="k">this</span><span class="o">::</span><span class="n">heavyProcessing</span><span class="o">)</span>
                    <span class="o">.</span><span class="na">collect</span><span class="o">(</span><span class="nc">Collectors</span><span class="o">.</span><span class="na">toList</span><span class="o">());</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<h4 id="4-错误处理">4. 错误处理</h4>

<p>正确的错误处理确保 UDF 的可靠性：</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// ❌ 错误示范：糟糕的错误处理</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">FragileUDF</span> <span class="kd">extends</span> <span class="nc">ScalarFunction</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="nc">Double</span> <span class="nf">evaluate</span><span class="o">(</span><span class="nc">String</span> <span class="n">input</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">return</span> <span class="nc">Double</span><span class="o">.</span><span class="na">parseDouble</span><span class="o">(</span><span class="n">input</span><span class="o">);</span>  <span class="c1">// 可能抛出 NumberFormatException</span>
    <span class="o">}</span>
<span class="o">}</span>

<span class="c1">// ✅ 正确示范：健壮的错误处理</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">RobustUDF</span> <span class="kd">extends</span> <span class="nc">ScalarFunction</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="nc">Double</span> <span class="nf">evaluate</span><span class="o">(</span><span class="nc">String</span> <span class="n">input</span><span class="o">,</span> <span class="nc">FunctionContext</span> <span class="n">context</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">try</span> <span class="o">{</span>
            <span class="k">if</span> <span class="o">(</span><span class="n">input</span> <span class="o">==</span> <span class="kc">null</span> <span class="o">||</span> <span class="n">input</span><span class="o">.</span><span class="na">isEmpty</span><span class="o">())</span> <span class="o">{</span>
                <span class="k">return</span> <span class="kc">null</span><span class="o">;</span>
            <span class="o">}</span>
            <span class="k">return</span> <span class="nc">Double</span><span class="o">.</span><span class="na">parseDouble</span><span class="o">(</span><span class="n">input</span><span class="o">.</span><span class="na">trim</span><span class="o">());</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">NumberFormatException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="c1">// 记录警告并返回 null，而不是失败</span>
            <span class="n">context</span><span class="o">.</span><span class="na">addWarning</span><span class="o">(</span><span class="s">"无法解析输入: "</span> <span class="o">+</span> <span class="n">input</span><span class="o">);</span>
            <span class="k">return</span> <span class="kc">null</span><span class="o">;</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">Exception</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="c1">// 对于意外错误，记录并重新抛出</span>
            <span class="n">context</span><span class="o">.</span><span class="na">addWarning</span><span class="o">(</span><span class="s">"意外错误: "</span> <span class="o">+</span> <span class="n">e</span><span class="o">.</span><span class="na">getMessage</span><span class="o">());</span>
            <span class="k">throw</span> <span class="k">new</span> <span class="nf">RuntimeException</span><span class="o">(</span><span class="s">"UDF 执行失败"</span><span class="o">,</span> <span class="n">e</span><span class="o">);</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>这些最佳实践确保你的 UDF：</p>
<ul>
  <li>内存高效且不会泄漏资源</li>
  <li>在 Doris 分布式环境中保持线程安全</li>
  <li>通过向量化执行获得高性能</li>
  <li>具有健壮的错误处理机制</li>
</ul>

<p>要点提示：</p>
<ul>
  <li>始终在 <code class="language-plaintext highlighter-rouge">close()</code> 方法中清理资源</li>
  <li>对可变状态使用线程本地存储</li>
  <li>尽可能批量处理以减少 JNI 开销</li>
  <li>优雅地处理错误并适当记录日志</li>
</ul>

<h3 id="使用示例">使用示例</h3>

<p>以下是一个简单的 Java UDF 实现示例：</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyUDF</span> <span class="kd">extends</span> <span class="nc">ScalarFunction</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="nc">String</span> <span class="nf">evaluate</span><span class="o">(</span><span class="nc">String</span> <span class="n">input</span><span class="o">)</span> <span class="o">{</span>
        <span class="c1">// 实现逻辑</span>
        <span class="k">return</span> <span class="n">processedResult</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>在 Doris 中注册：</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="k">FUNCTION</span> <span class="n">my_udf</span>
<span class="k">RETURNS</span> <span class="n">STRING</span>
<span class="n">PROPERTIES</span> <span class="p">(</span>
    <span class="nv">"file"</span><span class="o">=</span><span class="nv">"udf.jar"</span><span class="p">,</span>
    <span class="nv">"symbol"</span><span class="o">=</span><span class="nv">"MyUDF"</span><span class="p">,</span>
    <span class="nv">"type"</span><span class="o">=</span><span class="nv">"JAVA_UDF"</span>
<span class="p">);</span>
</code></pre></div></div>

<h3 id="详细执行流程">详细执行流程</h3>

<p>当用户执行包含 UDF 的 SQL 查询时，以下是详细的步骤流程：</p>

<pre><code class="language-mermaid">sequenceDiagram
    participant User as 用户
    participant FE
    participant BE
    participant JNI
    participant UDF

    User-&gt;&gt;FE: 提交 SQL 查询
    Note over FE: 1. 解析 SQL 并验证 UDF
    Note over FE: 2. 创建查询计划
    Note over FE: 3. 分发到 BE

    FE-&gt;&gt;BE: 发送查询计划
    Note over BE: 4. 初始化函数上下文
    
    rect rgb(200, 220, 255)
        Note over BE: 5. UDF 设置阶段
        BE-&gt;&gt;JNI: 初始化 JVM 环境
        BE-&gt;&gt;JNI: 加载 UDF JAR 文件
        JNI-&gt;&gt;UDF: 创建 UDF 实例
        UDF--&gt;&gt;BE: 返回设置状态
    end

    rect rgb(255, 220, 200)
        Note over BE: 6. 数据处理阶段
        loop 对每个输入批次
            BE-&gt;&gt;BE: 准备输入数据
            BE-&gt;&gt;JNI: 转换为 Java 类型
            JNI-&gt;&gt;UDF: 执行 UDF
            UDF--&gt;&gt;JNI: 返回结果
            JNI-&gt;&gt;BE: 转换为 Doris 类型
            BE-&gt;&gt;BE: 添加到结果集
        end
    end

    rect rgb(220, 255, 200)
        Note over BE: 7. 清理阶段
        BE-&gt;&gt;JNI: 释放资源
        JNI-&gt;&gt;UDF: 关闭 UDF
        BE-&gt;&gt;BE: 释放内存
    end

    BE--&gt;&gt;FE: 返回结果
    FE--&gt;&gt;User: 最终查询结果
</code></pre>

<p>让我们详细分析每个阶段：</p>

<h4 id="1-sql-解析和-udf-验证">1. SQL 解析和 UDF 验证</h4>
<ul>
  <li>Frontend (FE) 解析 SQL 查询</li>
  <li>识别 UDF 调用并验证函数是否存在</li>
  <li>检查参数类型是否匹配 UDF 签名</li>
  <li>验证 UDF JAR 文件是否可访问</li>
</ul>

<h4 id="2-查询计划">2. 查询计划</h4>
<ul>
  <li>FE 创建分布式查询计划</li>
  <li>确定 UDF 执行位置</li>
  <li>优化 UDF 在执行管道中的位置</li>
  <li>规划数据移动和聚合策略</li>
</ul>

<h4 id="3-后端分发">3. 后端分发</h4>
<ul>
  <li>查询计划发送到 Backend (BE) 节点</li>
  <li>BE 节点准备 UDF 执行</li>
  <li>分配执行所需资源</li>
</ul>

<h4 id="4-函数上下文初始化">4. 函数上下文初始化</h4>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">doris</span><span class="o">::</span><span class="n">FunctionContext</span><span class="o">&gt;</span> <span class="n">FunctionContext</span><span class="o">::</span><span class="n">create_context</span><span class="p">(</span>
    <span class="n">RuntimeState</span><span class="o">*</span> <span class="n">state</span><span class="p">,</span> 
    <span class="k">const</span> <span class="n">doris</span><span class="o">::</span><span class="n">TypeDescriptor</span><span class="o">&amp;</span> <span class="n">return_type</span><span class="p">,</span>
    <span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">doris</span><span class="o">::</span><span class="n">TypeDescriptor</span><span class="o">&gt;&amp;</span> <span class="n">arg_types</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">auto</span> <span class="n">ctx</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">doris</span><span class="o">::</span><span class="n">FunctionContext</span><span class="o">&gt;</span><span class="p">(</span><span class="k">new</span> <span class="n">doris</span><span class="o">::</span><span class="n">FunctionContext</span><span class="p">());</span>
    <span class="n">ctx</span><span class="o">-&gt;</span><span class="n">_state</span> <span class="o">=</span> <span class="n">state</span><span class="p">;</span>
    <span class="n">ctx</span><span class="o">-&gt;</span><span class="n">_return_type</span> <span class="o">=</span> <span class="n">return_type</span><span class="p">;</span>
    <span class="n">ctx</span><span class="o">-&gt;</span><span class="n">_arg_types</span> <span class="o">=</span> <span class="n">arg_types</span><span class="p">;</span>
    <span class="k">return</span> <span class="n">ctx</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<h4 id="5-udf-设置阶段">5. UDF 设置阶段</h4>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Status</span> <span class="n">JavaFunctionCall</span><span class="o">::</span><span class="n">open</span><span class="p">(</span><span class="n">FunctionContext</span><span class="o">*</span> <span class="n">context</span><span class="p">,</span> <span class="n">FunctionContext</span><span class="o">::</span><span class="n">FunctionStateScope</span> <span class="n">scope</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">scope</span> <span class="o">==</span> <span class="n">FunctionContext</span><span class="o">::</span><span class="n">THREAD_LOCAL</span><span class="p">)</span> <span class="p">{</span>
        <span class="c1">// 初始化 JNI 环境</span>
        <span class="n">std</span><span class="o">::</span><span class="n">shared_ptr</span><span class="o">&lt;</span><span class="n">JniContext</span><span class="o">&gt;</span> <span class="n">jni_ctx</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">make_shared</span><span class="o">&lt;</span><span class="n">JniContext</span><span class="o">&gt;</span><span class="p">();</span>
        <span class="c1">// 加载 UDF 实现</span>
        <span class="n">TJavaUdfExecutorCtorParams</span> <span class="n">ctor_params</span><span class="p">;</span>
        <span class="n">ctor_params</span><span class="p">.</span><span class="n">__set_fn</span><span class="p">(</span><span class="n">fn_</span><span class="p">);</span>
        <span class="c1">// 设置 JNI 桥接</span>
        <span class="n">RETURN_IF_ERROR</span><span class="p">(</span><span class="n">SerializeThriftMsg</span><span class="p">(</span><span class="n">env</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">ctor_params</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">ctor_params_bytes</span><span class="p">));</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">Status</span><span class="o">::</span><span class="n">OK</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<h4 id="6-数据处理阶段">6. 数据处理阶段</h4>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Status</span> <span class="n">JavaFunctionCall</span><span class="o">::</span><span class="n">execute_impl</span><span class="p">(</span><span class="n">FunctionContext</span><span class="o">*</span> <span class="n">context</span><span class="p">,</span> <span class="n">Block</span><span class="o">&amp;</span> <span class="n">block</span><span class="p">,</span>
                                    <span class="k">const</span> <span class="n">ColumnNumbers</span><span class="o">&amp;</span> <span class="n">arguments</span><span class="p">,</span> <span class="kt">uint32_t</span> <span class="n">result</span><span class="p">,</span>
                                    <span class="kt">size_t</span> <span class="n">num_rows</span><span class="p">)</span> <span class="k">const</span> <span class="p">{</span>
    <span class="c1">// 转换输入数据为 Java 格式</span>
    <span class="n">RETURN_IF_ERROR</span><span class="p">(</span><span class="n">JniConnector</span><span class="o">::</span><span class="n">to_java_table</span><span class="p">(</span><span class="o">&amp;</span><span class="n">block</span><span class="p">,</span> <span class="n">num_rows</span><span class="p">,</span> <span class="n">arguments</span><span class="p">,</span> <span class="n">input_table</span><span class="p">));</span>
    
    <span class="c1">// 执行 UDF</span>
    <span class="kt">long</span> <span class="n">output_address</span> <span class="o">=</span> <span class="n">env</span><span class="o">-&gt;</span><span class="n">CallLongMethod</span><span class="p">(</span><span class="n">jni_ctx</span><span class="o">-&gt;</span><span class="n">executor</span><span class="p">,</span> 
                                            <span class="n">jni_ctx</span><span class="o">-&gt;</span><span class="n">executor_evaluate_id</span><span class="p">,</span>
                                            <span class="n">input_map</span><span class="p">,</span> <span class="n">output_map</span><span class="p">);</span>
    
    <span class="c1">// 处理结果</span>
    <span class="n">RETURN_IF_ERROR</span><span class="p">(</span><span class="n">JniUtil</span><span class="o">::</span><span class="n">GetJniExceptionMsg</span><span class="p">(</span><span class="n">env</span><span class="p">));</span>
    <span class="k">return</span> <span class="n">Status</span><span class="o">::</span><span class="n">OK</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<h4 id="7-清理阶段">7. 清理阶段</h4>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Status</span> <span class="nf">close</span><span class="p">(</span><span class="n">FunctionContext</span><span class="o">*</span> <span class="n">context</span><span class="p">,</span> <span class="n">FunctionContext</span><span class="o">::</span><span class="n">FunctionStateScope</span> <span class="n">scope</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">_jni_ctx</span><span class="p">)</span> <span class="p">{</span>
        <span class="c1">// 释放 JNI 资源</span>
        <span class="n">RETURN_IF_ERROR</span><span class="p">(</span><span class="n">_jni_ctx</span><span class="o">-&gt;</span><span class="n">close</span><span class="p">());</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">Status</span><span class="o">::</span><span class="n">OK</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<p>这个执行流程展示了 Doris 如何：</p>
<ol>
  <li>在分布式环境中高效处理 UDF 执行</li>
  <li>管理不同执行阶段的资源和内存</li>
  <li>安全地在 Doris 和 Java 类型之间转换数据</li>
  <li>在每个阶段正确处理错误和清理</li>
</ol>

<p>向量化执行引擎通过批处理数据来提升性能：</p>
<ul>
  <li>减少 JNI 调用开销</li>
  <li>提高 CPU 缓存利用率</li>
  <li>支持 SIMD 优化</li>
  <li>最小化内存分配/释放周期</li>
</ul>

<h3 id="源代码参考">源代码参考</h3>

<p>对于想深入了解实现细节的开发者，以下是关键源文件：</p>

<h4 id="核心-udf-框架">核心 UDF 框架</h4>
<ul>
  <li>函数上下文: <a href="https://github.com/apache/doris/blob/master/be/src/udf/udf.h"><code class="language-plaintext highlighter-rouge">be/src/udf/udf.h</code></a>, <a href="https://github.com/apache/doris/blob/master/be/src/udf/udf.cpp"><code class="language-plaintext highlighter-rouge">be/src/udf/udf.cpp</code></a>
    <ul>
      <li>定义核心 UDF 接口</li>
      <li>实现函数上下文管理</li>
      <li>处理内存和状态管理</li>
    </ul>
  </li>
</ul>

<h4 id="java-udf-实现">Java UDF 实现</h4>
<ul>
  <li>Java 函数调用: <a href="https://github.com/apache/doris/blob/master/be/src/vec/functions/function_java_udf.h"><code class="language-plaintext highlighter-rouge">be/src/vec/functions/function_java_udf.h</code></a>, <a href="https://github.com/apache/doris/blob/master/be/src/vec/functions/function_java_udf.cpp"><code class="language-plaintext highlighter-rouge">be/src/vec/functions/function_java_udf.cpp</code></a>
    <ul>
      <li>实现 Java UDF 生命周期</li>
      <li>处理 JNI 桥接</li>
      <li>管理数据转换</li>
    </ul>
  </li>
</ul>

<h4 id="聚合函数-udaf">聚合函数 (UDAF)</h4>
<ul>
  <li>Java UDAF: <a href="https://github.com/apache/doris/blob/master/be/src/vec/aggregate_functions/aggregate_function_java_udaf.h"><code class="language-plaintext highlighter-rouge">be/src/vec/aggregate_functions/aggregate_function_java_udaf.h</code></a>
    <ul>
      <li>实现聚合框架</li>
      <li>处理聚合状态管理</li>
      <li>定义 UDAF 生命周期</li>
    </ul>
  </li>
</ul>

<h4 id="表值函数-udtf">表值函数 (UDTF)</h4>
<ul>
  <li>UDF 表值函数: <a href="https://github.com/apache/doris/blob/master/be/src/vec/exprs/table_function/udf_table_function.h"><code class="language-plaintext highlighter-rouge">be/src/vec/exprs/table_function/udf_table_function.h</code></a>, <a href="https://github.com/apache/doris/blob/master/be/src/vec/exprs/table_function/udf_table_function.cpp"><code class="language-plaintext highlighter-rouge">be/src/vec/exprs/table_function/udf_table_function.cpp</code></a>
    <ul>
      <li>实现表值函数</li>
      <li>处理多行/多列输出</li>
      <li>管理向量化执行</li>
    </ul>
  </li>
</ul>

<h4 id="jni-工具">JNI 工具</h4>
<ul>
  <li>JNI 连接器: <a href="https://github.com/apache/doris/blob/master/be/src/vec/exec/jni_connector.h"><code class="language-plaintext highlighter-rouge">be/src/vec/exec/jni_connector.h</code></a>
    <ul>
      <li>提供 JNI 桥接工具</li>
      <li>处理 Java 和 C++ 之间的数据转换</li>
      <li>管理 JVM 生命周期</li>
    </ul>
  </li>
</ul>

<h3 id="问题分析udf-空指针处理">问题分析：UDF 空指针处理</h3>

<h4 id="问题描述">问题描述</h4>

<p>当 UDF 在谓词中未能正确处理空值时，可能导致 BE 组件崩溃，错误信息如下：</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>column_string.cpp:254 check failed filter.size()==offsets.size()(4064 vs 8128)
</code></pre></div></div>

<p>这是一个严重问题，原因如下：</p>
<ol>
  <li>导致整个 BE 进程崩溃，而不仅仅是查询失败</li>
  <li>发生在谓词评估阶段，影响查询过滤</li>
  <li>大小不匹配表明字符串列处理存在根本性问题</li>
</ol>

<h4 id="根本原因分析">根本原因分析</h4>

<p>让我们通过代码追踪问题原因：</p>

<ol>
  <li><strong>字符串列结构</strong> [<code class="language-plaintext highlighter-rouge">be/src/vec/columns/column_string.h</code>]:
    <div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">ColumnString</span> <span class="k">final</span> <span class="o">:</span> <span class="k">public</span> <span class="n">COWHelper</span><span class="o">&lt;</span><span class="n">IColumn</span><span class="p">,</span> <span class="n">ColumnString</span><span class="o">&gt;</span> <span class="p">{</span>
<span class="nl">private:</span>
 <span class="c1">/// 映射第 i 个位置到第 i+1 个位置的偏移量（第 i 个字符串的结束位置）</span>
 <span class="c1">/// 注意：第 0 个位置的偏移量显式存储在第一个位置</span>
 <span class="k">using</span> <span class="n">Offsets</span> <span class="o">=</span> <span class="n">ColumnOffsets</span><span class="o">::</span><span class="n">Container_t</span><span class="p">;</span>
 <span class="c1">/// 连续存储的字符串字节</span>
 <span class="k">using</span> <span class="n">Chars</span> <span class="o">=</span> <span class="n">PODArray</span><span class="o">&lt;</span><span class="n">UInt8</span><span class="o">&gt;</span><span class="p">;</span>
    
 <span class="n">Chars</span> <span class="n">chars</span><span class="p">;</span>           <span class="c1">/// 字符串字节</span>
 <span class="n">Offsets</span> <span class="n">offsets</span><span class="p">;</span>      <span class="c1">/// 每个元素后的偏移量</span>
 <span class="kt">size_t</span> <span class="n">total_bytes</span><span class="p">;</span>   <span class="c1">/// 使用的字节数</span>
<span class="p">};</span>
</code></pre></div>    </div>
  </li>
  <li><strong>谓词评估</strong> [<code class="language-plaintext highlighter-rouge">be/src/vec/functions/function_java_udf.cpp</code>]:
    <div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Status</span> <span class="n">JavaFunctionCall</span><span class="o">::</span><span class="n">execute_impl</span><span class="p">(</span><span class="n">FunctionContext</span><span class="o">*</span> <span class="n">context</span><span class="p">,</span> <span class="n">Block</span><span class="o">&amp;</span> <span class="n">block</span><span class="p">,</span>
                                 <span class="k">const</span> <span class="n">ColumnNumbers</span><span class="o">&amp;</span> <span class="n">arguments</span><span class="p">,</span> <span class="kt">uint32_t</span> <span class="n">result</span><span class="p">,</span>
                                 <span class="kt">size_t</span> <span class="n">num_rows</span><span class="p">)</span> <span class="k">const</span> <span class="p">{</span>
 <span class="c1">// 转换输入数据为 Java 格式</span>
 <span class="n">RETURN_IF_ERROR</span><span class="p">(</span><span class="n">JniConnector</span><span class="o">::</span><span class="n">to_java_table</span><span class="p">(</span><span class="o">&amp;</span><span class="n">block</span><span class="p">,</span> <span class="n">num_rows</span><span class="p">,</span> <span class="n">arguments</span><span class="p">,</span> <span class="n">input_table</span><span class="p">));</span>
    
 <span class="c1">// 当 UDF 用作谓词时，结果用作过滤器</span>
 <span class="k">if</span> <span class="p">(</span><span class="n">block</span><span class="p">.</span><span class="n">get_by_position</span><span class="p">(</span><span class="n">result</span><span class="p">).</span><span class="n">type</span><span class="o">-&gt;</span><span class="n">is_boolean</span><span class="p">())</span> <span class="p">{</span>
     <span class="c1">// 创建的过滤器必须匹配输入大小</span>
     <span class="k">auto</span><span class="o">&amp;</span> <span class="n">col</span> <span class="o">=</span> <span class="n">block</span><span class="p">.</span><span class="n">get_by_position</span><span class="p">(</span><span class="n">result</span><span class="p">).</span><span class="n">column</span><span class="p">;</span>
     <span class="c1">// ... 过滤器应用逻辑 ...</span>
 <span class="p">}</span>
<span class="p">}</span>
</code></pre></div>    </div>
  </li>
  <li><strong>字符串列过滤器应用</strong> [<code class="language-plaintext highlighter-rouge">be/src/vec/columns/column_string.cpp</code>]:
    <div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="n">ColumnString</span><span class="o">::</span><span class="n">filter</span><span class="p">(</span><span class="k">const</span> <span class="n">Filter</span><span class="o">&amp;</span> <span class="n">filt</span><span class="p">,</span> <span class="kt">ssize_t</span> <span class="n">result_size_hint</span><span class="p">)</span> <span class="p">{</span>
 <span class="c1">// 关键：确保过滤器和字符串偏移量大小匹配</span>
 <span class="k">if</span> <span class="p">(</span><span class="n">filt</span><span class="p">.</span><span class="n">size</span><span class="p">()</span> <span class="o">!=</span> <span class="n">offsets</span><span class="p">.</span><span class="n">size</span><span class="p">())</span>
     <span class="k">throw</span> <span class="n">Exception</span><span class="p">(</span><span class="s">"过滤器大小与列大小不匹配"</span><span class="p">);</span>
    
 <span class="c1">// ... 过滤器应用逻辑 ...</span>
<span class="p">}</span>
</code></pre></div>    </div>
  </li>
</ol>

<h4 id="导致崩溃的序列">导致崩溃的序列</h4>

<ol>
  <li><strong>初始状态</strong>:
    <pre><code class="language-mermaid">sequenceDiagram
 participant Query as 查询
 participant UDF
 participant StringColumn as 字符串列
 participant Filter as 过滤器

 Query-&gt;&gt;UDF: 使用空值执行
 Note over UDF: 未正确处理空值
 UDF-&gt;&gt;Filter: 创建不完整过滤器
 Filter-&gt;&gt;StringColumn: 应用过滤器
 Note over StringColumn: 检测到大小不匹配
 StringColumn--&gt;&gt;Query: 断言崩溃
</code></pre>
  </li>
  <li><strong>问题所在</strong>:
    <ul>
      <li>UDF 接收到空值但未正确处理</li>
      <li>用作谓词时，应该产生布尔过滤器</li>
      <li>过滤器大小必须匹配行数（偏移量大小）</li>
      <li>由于空值处理问题，过滤器大小不正确</li>
      <li><code class="language-plaintext highlighter-rouge">ColumnString::filter</code> 中的断言失败</li>
    </ul>
  </li>
</ol>

<h4 id="解决方案">解决方案</h4>

<ol>
  <li><strong>正确的空值处理</strong>:
```java
// ❌ 问题实现
public class UnsafeUDF extends ScalarFunction {
 public Boolean evaluate(String input) {
     return input.contains(“test”);  // 输入为 null 时抛出 NPE
 }
}</li>
</ol>

<p>// ✅ 安全实现
public class SafeUDF extends ScalarFunction {
    public Boolean evaluate(String input) {
        if (input == null) {
            return null;  // 或根据需求返回 false
        }
        return input.contains(“test”);
    }
}</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
2. **BE 端保护** [`be/src/vec/functions/function_java_udf.cpp`]:
```cpp
Status JavaFunctionCall::execute_impl(FunctionContext* context, Block&amp; block,
                                    const ColumnNumbers&amp; arguments, uint32_t result,
                                    size_t num_rows) const {
    // 处理前添加空值检查
    for (const auto&amp; arg : arguments) {
        const auto&amp; column = block.get_by_position(arg).column;
        if (column-&gt;is_nullable()) {
            // 适当处理空值
            auto&amp; nullable = assert_cast&lt;const ColumnNullable&amp;&gt;(*column);
            // ... 空值处理逻辑 ...
        }
    }
    
    // 继续正常执行
    RETURN_IF_ERROR(JniConnector::to_java_table(&amp;block, num_rows, arguments, input_table));
}
</code></pre></div></div>

<ol>
  <li><strong>大小验证</strong>:
    <div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// 过滤器应用前添加大小验证</span>
<span class="k">if</span> <span class="p">(</span><span class="n">filter</span><span class="o">-&gt;</span><span class="n">size</span><span class="p">()</span> <span class="o">!=</span> <span class="n">num_rows</span><span class="p">)</span> <span class="p">{</span>
 <span class="k">return</span> <span class="n">Status</span><span class="o">::</span><span class="n">InternalError</span><span class="p">(</span>
     <span class="n">fmt</span><span class="o">::</span><span class="n">format</span><span class="p">(</span><span class="s">"过滤器大小不匹配。期望: {}, 实际: {}"</span><span class="p">,</span> 
                <span class="n">num_rows</span><span class="p">,</span> <span class="n">filter</span><span class="o">-&gt;</span><span class="n">size</span><span class="p">()));</span>
<span class="p">}</span>
</code></pre></div>    </div>
  </li>
</ol>

<h4 id="预防策略">预防策略</h4>

<ol>
  <li><strong>UDF 开发</strong>:
    <ul>
      <li>始终显式处理空值输入</li>
      <li>适当使用可空返回类型</li>
      <li>专门测试空值情况</li>
    </ul>
  </li>
  <li><strong>系统层面</strong>:
    <ul>
      <li>在 UDF 框架中添加空值检查</li>
      <li>验证过滤器大小</li>
      <li>改进调试错误消息</li>
    </ul>
  </li>
  <li><strong>查询规划</strong>:
    <ul>
      <li>考虑将空值处理推送到 BE</li>
      <li>添加空值感知谓词优化</li>
      <li>实现空值安全比较运算符</li>
    </ul>
  </li>
</ol>

<h4 id="性能影响">性能影响</h4>

<p>正确的空值处理带来的开销很小：</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// 基准测试结果（假设）</span>
<span class="c1">// 不进行空值检查: 100ns/行</span>
<span class="c1">// 进行空值检查: 105ns/行</span>
<span class="c1">// 崩溃成本: 数分钟停机时间</span>
</code></pre></div></div>

<p>这点性能开销相比系统稳定性的提升是非常值得的。</p>]]></content><author><name>York Cao</name></author><category term="blog" /><category term="doris" /><summary type="html"><![CDATA[Doris UDF 工作原理]]></summary></entry><entry><title type="html">Enhanced Markdown Features Demo</title><link href="https://baymine.github.io/2024/06/20/markdown-features-demo/" rel="alternate" type="text/html" title="Enhanced Markdown Features Demo" /><published>2024-06-20T07:00:00+00:00</published><updated>2024-06-20T07:00:00+00:00</updated><id>https://baymine.github.io/2024/06/20/markdown-features-demo</id><content type="html" xml:base="https://baymine.github.io/2024/06/20/markdown-features-demo/"><![CDATA[<h1 id="enhanced-markdown-features-demo">Enhanced Markdown Features Demo</h1>

<p>This post demonstrates all the enhanced markdown features now available in your hacker-style blog.</p>

<h2 id="code-syntax-highlighting">Code Syntax Highlighting</h2>

<h3 id="python-code">Python Code</h3>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">fibonacci</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
    <span class="s">"""Generate Fibonacci sequence up to n terms."""</span>
    <span class="k">if</span> <span class="n">n</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">:</span>
        <span class="k">return</span> <span class="p">[]</span>
    <span class="k">elif</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
        <span class="k">return</span> <span class="p">[</span><span class="mi">0</span><span class="p">]</span>
    <span class="k">elif</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">2</span><span class="p">:</span>
        <span class="k">return</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">]</span>
    
    <span class="n">sequence</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">]</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
        <span class="n">sequence</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">sequence</span><span class="p">[</span><span class="n">i</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="n">sequence</span><span class="p">[</span><span class="n">i</span><span class="o">-</span><span class="mi">2</span><span class="p">])</span>
    
    <span class="k">return</span> <span class="n">sequence</span>

<span class="c1"># Example usage
</span><span class="err">$$</span><span class="n">fib_numbers</span> <span class="o">=</span> <span class="n">fibonacci</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span><span class="err">$$</span>
<span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"First 10 Fibonacci numbers: </span><span class="si">{</span><span class="n">fib_numbers</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
</code></pre></div></div>

<h3 id="c-code">C++ Code</h3>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;iostream&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;vector&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;algorithm&gt;</span><span class="cp">
</span>
<span class="k">class</span> <span class="nc">DataProcessor</span> <span class="p">{</span>
<span class="nl">private:</span>
    <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span> <span class="n">data</span><span class="p">;</span>
    
<span class="nl">public:</span>
    <span class="kt">void</span> <span class="n">addData</span><span class="p">(</span><span class="kt">int</span> <span class="n">value</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">data</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">value</span><span class="p">);</span>
    <span class="p">}</span>
    
    <span class="kt">double</span> <span class="n">calculateAverage</span><span class="p">()</span> <span class="k">const</span> <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">data</span><span class="p">.</span><span class="n">empty</span><span class="p">())</span> <span class="k">return</span> <span class="mf">0.0</span><span class="p">;</span>
        
        <span class="kt">int</span> <span class="n">sum</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">accumulate</span><span class="p">(</span><span class="n">data</span><span class="p">.</span><span class="n">begin</span><span class="p">(),</span> <span class="n">data</span><span class="p">.</span><span class="n">end</span><span class="p">(),</span> <span class="mi">0</span><span class="p">);</span>
        <span class="k">return</span> <span class="k">static_cast</span><span class="o">&lt;</span><span class="kt">double</span><span class="o">&gt;</span><span class="p">(</span><span class="n">sum</span><span class="p">)</span> <span class="o">/</span> <span class="n">data</span><span class="p">.</span><span class="n">size</span><span class="p">();</span>
    <span class="p">}</span>
    
    <span class="kt">void</span> <span class="n">sortData</span><span class="p">()</span> <span class="p">{</span>
        <span class="n">std</span><span class="o">::</span><span class="n">sort</span><span class="p">(</span><span class="n">data</span><span class="p">.</span><span class="n">begin</span><span class="p">(),</span> <span class="n">data</span><span class="p">.</span><span class="n">end</span><span class="p">());</span>
    <span class="p">}</span>
<span class="p">};</span>

<span class="kt">int</span> <span class="n">main</span><span class="p">()</span> <span class="p">{</span>
    <span class="n">DataProcessor</span> <span class="n">processor</span><span class="p">;</span>
    <span class="n">processor</span><span class="p">.</span><span class="n">addData</span><span class="p">(</span><span class="mi">42</span><span class="p">);</span>
    <span class="n">processor</span><span class="p">.</span><span class="n">addData</span><span class="p">(</span><span class="mi">17</span><span class="p">);</span>
    <span class="n">processor</span><span class="p">.</span><span class="n">addData</span><span class="p">(</span><span class="mi">89</span><span class="p">);</span>
    
    <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">"Average: "</span> <span class="o">&lt;&lt;</span> <span class="n">processor</span><span class="p">.</span><span class="n">calculateAverage</span><span class="p">()</span> <span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="sql-code">SQL Code</h3>
<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">-- Complex query with CTEs and window functions</span>
<span class="k">WITH</span> <span class="n">monthly_sales</span> <span class="k">AS</span> <span class="p">(</span>
    <span class="k">SELECT</span> 
        <span class="n">DATE_TRUNC</span><span class="p">(</span><span class="s1">'month'</span><span class="p">,</span> <span class="n">order_date</span><span class="p">)</span> <span class="k">as</span> <span class="k">month</span><span class="p">,</span>
        <span class="k">SUM</span><span class="p">(</span><span class="n">total_amount</span><span class="p">)</span> <span class="k">as</span> <span class="n">monthly_total</span><span class="p">,</span>
        <span class="k">COUNT</span><span class="p">(</span><span class="o">*</span><span class="p">)</span> <span class="k">as</span> <span class="n">order_count</span>
    <span class="k">FROM</span> <span class="n">orders</span> 
    <span class="k">WHERE</span> <span class="n">order_date</span> <span class="o">&gt;=</span> <span class="s1">'2024-01-01'</span>
    <span class="k">GROUP</span> <span class="k">BY</span> <span class="n">DATE_TRUNC</span><span class="p">(</span><span class="s1">'month'</span><span class="p">,</span> <span class="n">order_date</span><span class="p">)</span>
<span class="p">),</span>
<span class="n">sales_with_growth</span> <span class="k">AS</span> <span class="p">(</span>
    <span class="k">SELECT</span> 
        <span class="k">month</span><span class="p">,</span>
        <span class="n">monthly_total</span><span class="p">,</span>
        <span class="n">order_count</span><span class="p">,</span>
        <span class="n">LAG</span><span class="p">(</span><span class="n">monthly_total</span><span class="p">)</span> <span class="n">OVER</span> <span class="p">(</span><span class="k">ORDER</span> <span class="k">BY</span> <span class="k">month</span><span class="p">)</span> <span class="k">as</span> <span class="n">prev_month_total</span><span class="p">,</span>
        <span class="p">(</span><span class="n">monthly_total</span> <span class="o">-</span> <span class="n">LAG</span><span class="p">(</span><span class="n">monthly_total</span><span class="p">)</span> <span class="n">OVER</span> <span class="p">(</span><span class="k">ORDER</span> <span class="k">BY</span> <span class="k">month</span><span class="p">))</span> <span class="o">/</span> 
        <span class="n">LAG</span><span class="p">(</span><span class="n">monthly_total</span><span class="p">)</span> <span class="n">OVER</span> <span class="p">(</span><span class="k">ORDER</span> <span class="k">BY</span> <span class="k">month</span><span class="p">)</span> <span class="o">*</span> <span class="mi">100</span> <span class="k">as</span> <span class="n">growth_rate</span>
    <span class="k">FROM</span> <span class="n">monthly_sales</span>
<span class="p">)</span>
<span class="k">SELECT</span> 
    <span class="k">month</span><span class="p">,</span>
    <span class="n">monthly_total</span><span class="p">,</span>
    <span class="n">order_count</span><span class="p">,</span>
    <span class="n">ROUND</span><span class="p">(</span><span class="n">growth_rate</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span> <span class="k">as</span> <span class="n">growth_percentage</span>
<span class="k">FROM</span> <span class="n">sales_with_growth</span>
<span class="k">ORDER</span> <span class="k">BY</span> <span class="k">month</span><span class="p">;</span>
</code></pre></div></div>

<h3 id="bashshell-code">Bash/Shell Code</h3>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">#!/bin/bash</span>

<span class="c"># System monitoring script</span>
<span class="k">function </span>check_system_health<span class="o">()</span> <span class="o">{</span>
    <span class="nb">echo</span> <span class="s2">"=== System Health Check ==="</span>
    
    <span class="c"># Check disk usage</span>
    <span class="nb">echo</span> <span class="s2">"Disk Usage:"</span>
    <span class="nb">df</span> <span class="nt">-h</span> | <span class="nb">grep</span> <span class="nt">-E</span> <span class="s1">'^/dev/'</span> | <span class="nb">awk</span> <span class="s1">'{print $5 " " $1}'</span> | <span class="k">while </span><span class="nb">read </span>output<span class="p">;</span>
    <span class="k">do</span>
<span class="nv">$$usage</span><span class="o">=</span><span class="si">$(</span><span class="nb">echo</span> <span class="nv">$output</span> | <span class="nb">awk</span> <span class="s1">'{print $1}'</span> | <span class="nb">sed</span> <span class="s1">'s/%//g'</span><span class="si">)</span><span class="nv">$$</span>
<span class="nv">$$partition</span><span class="o">=</span><span class="si">$(</span><span class="nb">echo</span> <span class="nv">$output</span> | <span class="nb">awk</span> <span class="s1">'{print $2}'</span><span class="si">)</span><span class="nv">$$</span>
        
        <span class="k">if</span> <span class="o">[</span> <span class="nv">$usage</span> <span class="nt">-ge</span> 90 <span class="o">]</span><span class="p">;</span> <span class="k">then
            </span><span class="nb">echo</span> <span class="s2">"WARNING: </span><span class="nv">$partition</span><span class="s2"> is </span><span class="k">${</span><span class="nv">usage</span><span class="k">}</span><span class="s2">% full"</span>
        <span class="k">else
            </span><span class="nb">echo</span> <span class="s2">"OK: </span><span class="nv">$partition</span><span class="s2"> is </span><span class="k">${</span><span class="nv">usage</span><span class="k">}</span><span class="s2">% full"</span>
        <span class="k">fi
    done</span>
    
    <span class="c"># Check memory usage</span>
    <span class="nb">echo</span> <span class="nt">-e</span> <span class="s2">"</span><span class="se">\n</span><span class="s2">Memory Usage:"</span>
    free <span class="nt">-h</span> | <span class="nb">grep</span> <span class="s1">'^Mem:'</span> | <span class="nb">awk</span> <span class="s1">'{print "Used: " $3 "/" $2 " (" $3/$2*100 "%)"}'</span>
    
    <span class="c"># Check CPU load</span>
    <span class="nb">echo</span> <span class="nt">-e</span> <span class="s2">"</span><span class="se">\n</span><span class="s2">CPU Load:"</span>
    <span class="nb">uptime</span> | <span class="nb">awk</span> <span class="nt">-F</span><span class="s1">'load average:'</span> <span class="s1">'{print "Load Average:" $2}'</span>
<span class="o">}</span>

check_system_health
</code></pre></div></div>

<h2 id="mathematics-support">Mathematics Support</h2>

<h3 id="inline-math">Inline Math</h3>
<p>\(Here's an inline equation: $E = mc^2$ and another one: $\sum_{i=1}^{n} x_i = x_1 + x_2 + \cdots + x_n$.\)</p>

<h3 id="display-math">Display Math</h3>
<p>Complex mathematical expressions are fully supported:</p>

<p>\(\)\int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi}\(\)</p>

<p>\(\)\frac{\partial}{\partial t} \Psi(\mathbf{r}, t) = \frac{i\hbar}{2m} \nabla^2 \Psi(\mathbf{r}, t) + V(\mathbf{r}) \Psi(\mathbf{r}, t)\(\)</p>

<h3 id="matrix-equations">Matrix Equations</h3>
<p>\(\begin{pmatrix}
a &amp; b \\
c &amp; d\)\end{pmatrix}\(\begin{pmatrix}
x \\
y\)\end{pmatrix}\(=
\begin{pmatrix}
ax + by \\
cx + dy\)\end{pmatrix}\(\)</p>

<h3 id="statistical-formulas">Statistical Formulas</h3>
<p>The probability density function of a normal distribution:</p>

<p>\(\)f(x|\mu,\sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}} e^{-\frac{(x-\mu)^2}{2\sigma^2}}\(\)</p>

<h2 id="advanced-markdown-features">Advanced Markdown Features</h2>

<h3 id="tables">Tables</h3>
<p>| Algorithm | Time Complexity | Space Complexity | Use Case |
|———–|—————-|——————|———-|
| Quick Sort | O(n log n) avg | O(log n) | General sorting |
| Merge Sort | O(n log n) | O(n) | Stable sorting |
| Heap Sort | O(n log n) | O(1) | Memory constrained |
| Bubble Sort | O(n²) | O(1) | Educational |</p>

<h3 id="task-lists">Task Lists</h3>
<ul class="task-list">
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" checked="checked" />Implement syntax highlighting</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" checked="checked" />Add math support with KaTeX</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" checked="checked" />Create hacker-style post layout</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Add dark mode toggle</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Implement search functionality</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Add comment system</li>
</ul>

<h3 id="blockquotes">Blockquotes</h3>
<blockquote>
  <p>“The best way to predict the future is to implement it.”</p>

  <p>— Alan Kay</p>
</blockquote>

<blockquote>
  <p><strong>Note:</strong> This is a multi-line blockquote that demonstrates
how longer quotes are handled in the hacker theme.
The styling maintains readability while keeping the cyberpunk aesthetic.</p>
</blockquote>

<h3 id="links-and-references">Links and References</h3>
<p>Check out my <a href="https://github.com/Baymine">GitHub profile</a> for more projects.</p>

<p>You can also reference other posts: <a href="/2024/06/20/welcome-to-my-blog/">Welcome Post</a></p>

<h3 id="images">Images</h3>
<p><img src="https://via.placeholder.com/600x300/0a0a0a/00ff41?text=HACKER+TERMINAL" alt="Hacker Terminal" /></p>

<h3 id="horizontal-rules">Horizontal Rules</h3>
<hr />

<h2 id="code-with-line-numbers">Code with Line Numbers</h2>
<p>The syntax highlighting includes line numbers for better readability:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Advanced JavaScript example with async/await</span>
<span class="kd">class</span> <span class="nx">APIClient</span> <span class="p">{</span>
    <span class="kd">constructor</span><span class="p">(</span><span class="nx">baseURL</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">this</span><span class="p">.</span><span class="nx">baseURL</span> <span class="o">=</span> <span class="nx">baseURL</span><span class="p">;</span>
<span class="nx">$$this</span><span class="p">.</span><span class="nx">headers</span> <span class="o">=</span> <span class="p">{</span><span class="nx">$$</span>
            <span class="dl">'</span><span class="s1">Content-Type</span><span class="dl">'</span><span class="p">:</span> <span class="dl">'</span><span class="s1">application/json</span><span class="dl">'</span><span class="p">,</span>
            <span class="dl">'</span><span class="s1">Authorization</span><span class="dl">'</span><span class="p">:</span> <span class="s2">`Bearer </span><span class="p">${</span><span class="k">this</span><span class="p">.</span><span class="nx">getToken</span><span class="p">()}</span><span class="s2">`</span>
        <span class="p">};</span>
    <span class="p">}</span>
    
    <span class="k">async</span> <span class="kd">get</span><span class="p">(</span><span class="nx">endpoint</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">try</span> <span class="p">{</span>
<span class="nx">$$const</span> <span class="nx">response</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">fetch</span><span class="p">(</span><span class="s2">`</span><span class="p">${</span><span class="k">this</span><span class="p">.</span><span class="nx">baseURL</span><span class="p">}${</span><span class="nx">endpoint</span><span class="p">}</span><span class="s2">`</span><span class="p">,</span> <span class="p">{</span><span class="nx">$$</span>
                <span class="na">method</span><span class="p">:</span> <span class="dl">'</span><span class="s1">GET</span><span class="dl">'</span><span class="p">,</span>
                <span class="na">headers</span><span class="p">:</span> <span class="k">this</span><span class="p">.</span><span class="nx">headers</span>
            <span class="p">});</span>
            
            <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">response</span><span class="p">.</span><span class="nx">ok</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">throw</span> <span class="k">new</span> <span class="nb">Error</span><span class="p">(</span><span class="s2">`HTTP error! status: </span><span class="p">${</span><span class="nx">response</span><span class="p">.</span><span class="nx">status</span><span class="p">}</span><span class="s2">`</span><span class="p">);</span>
            <span class="p">}</span>
            
            <span class="k">return</span> <span class="k">await</span> <span class="nx">response</span><span class="p">.</span><span class="nx">json</span><span class="p">();</span>
        <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="nx">error</span><span class="p">)</span> <span class="p">{</span>
            <span class="nx">console</span><span class="p">.</span><span class="nx">error</span><span class="p">(</span><span class="dl">'</span><span class="s1">API request failed:</span><span class="dl">'</span><span class="p">,</span> <span class="nx">error</span><span class="p">);</span>
            <span class="k">throw</span> <span class="nx">error</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>
    
    <span class="nx">getToken</span><span class="p">()</span> <span class="p">{</span>
        <span class="k">return</span> <span class="nx">localStorage</span><span class="p">.</span><span class="nx">getItem</span><span class="p">(</span><span class="dl">'</span><span class="s1">authToken</span><span class="dl">'</span><span class="p">)</span> <span class="o">||</span> <span class="dl">''</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="c1">// Usage example</span>
<span class="kd">const</span> <span class="nx">client</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">APIClient</span><span class="p">(</span><span class="dl">'</span><span class="s1">https://api.example.com</span><span class="dl">'</span><span class="p">);</span>
<span class="nx">client</span><span class="p">.</span><span class="kd">get</span><span class="p">(</span><span class="dl">'</span><span class="s1">/users/profile</span><span class="dl">'</span><span class="p">)</span>
    <span class="p">.</span><span class="nx">then</span><span class="p">(</span><span class="nx">data</span> <span class="o">=&gt;</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">'</span><span class="s1">User profile:</span><span class="dl">'</span><span class="p">,</span> <span class="nx">data</span><span class="p">))</span>
    <span class="p">.</span><span class="k">catch</span><span class="p">(</span><span class="nx">error</span> <span class="o">=&gt;</span> <span class="nx">console</span><span class="p">.</span><span class="nx">error</span><span class="p">(</span><span class="dl">'</span><span class="s1">Failed to fetch profile:</span><span class="dl">'</span><span class="p">,</span> <span class="nx">error</span><span class="p">));</span>
</code></pre></div></div>

<h2 id="conclusion">Conclusion</h2>

<p>Your blog now supports:</p>
<ul>
  <li>✅ <strong>Syntax highlighting</strong> for 100+ programming languages</li>
  <li>✅ <strong>Mathematical equations</strong> with KaTeX rendering</li>
  <li>✅ <strong>Enhanced tables</strong> with proper styling</li>
  <li>✅ <strong>Task lists</strong> and checkboxes</li>
  <li>✅ <strong>Blockquotes</strong> with proper formatting</li>
  <li>✅ <strong>Code blocks</strong> with line numbers</li>
  <li>✅ <strong>Responsive design</strong> that works on all devices</li>
  <li>✅ <strong>Hacker aesthetic</strong> that matches your homepage</li>
</ul>

<p>All while maintaining the cyberpunk terminal theme throughout your blog! 🚀</p>]]></content><author><name>York Cao</name></author><category term="demo" /><category term="markdown" /><category term="markdown" /><category term="syntax" /><category term="math" /><category term="code" /><summary type="html"><![CDATA[Enhanced Markdown Features Demo]]></summary></entry><entry><title type="html">Welcome to My Blog!</title><link href="https://baymine.github.io/2024/06/20/welcome-to-my-blog/" rel="alternate" type="text/html" title="Welcome to My Blog!" /><published>2024-06-20T04:00:00+00:00</published><updated>2024-06-20T04:00:00+00:00</updated><id>https://baymine.github.io/2024/06/20/welcome-to-my-blog</id><content type="html" xml:base="https://baymine.github.io/2024/06/20/welcome-to-my-blog/"><![CDATA[<h1 id="welcome-to-my-blog">Welcome to My Blog!</h1>

<p>Hello and welcome to my personal blog! I’m excited to share this space with you where I’ll be writing about technology, programming, and various topics that interest me.</p>

<h2 id="what-you-can-expect">What You Can Expect</h2>

<p>This blog will cover a variety of topics including:</p>

<ul>
  <li><strong>Data Engineering</strong>: Insights from working with large-scale data systems</li>
  <li><strong>Programming</strong>: Tips, tricks, and deep dives into various programming languages</li>
  <li><strong>Technology Reviews</strong>: My thoughts on new tools and technologies</li>
  <li><strong>Learning Notes</strong>: Documentation of my learning journey in various subjects</li>
</ul>

<h2 id="recent-topics-ive-been-exploring">Recent Topics I’ve Been Exploring</h2>

<ul>
  <li><strong>ClickHouse Source Code</strong>: Deep diving into the architecture and implementation</li>
  <li><strong>Operating Systems</strong>: Working through MIT 6.S081 course materials</li>
  <li><strong>C++ Programming</strong>: Advanced concepts and memory management</li>
  <li><strong>Computer Networks</strong>: Protocol analysis and optimization techniques</li>
</ul>

<h2 id="about-the-blog-setup">About the Blog Setup</h2>

<p>This blog is now built using:</p>
<ul>
  <li><strong><a href="https://jekyllrb.com/">Jekyll</a></strong>: A simple, blog-aware static site generator</li>
  <li><strong><a href="https://github.com/jekyll/minima">Minima Theme</a></strong>: A beautiful and clean theme</li>
  <li><strong>GitHub Pages</strong>: For hosting and deployment</li>
</ul>

<h2 id="get-in-touch">Get in Touch</h2>

<p>I’d love to hear from you! Feel free to:</p>
<ul>
  <li>Leave comments on posts</li>
  <li>Reach out via <a href="https://github.com/Baymine">GitHub</a></li>
  <li>Suggest topics you’d like me to write about</li>
</ul>

<h2 id="whats-next">What’s Next?</h2>

<p>I’m planning to write about:</p>
<ul>
  <li>Setting up efficient development environments</li>
  <li>Database optimization techniques</li>
  <li>System design patterns</li>
  <li>Open source project contributions</li>
</ul>

<p>Stay tuned for more content, and thank you for visiting!</p>

<hr />

<p><em>Happy coding!</em><br />
<em>- York</em></p>]]></content><author><name>York Cao</name></author><category term="general" /><category term="introduction" /><category term="blog" /><category term="introduction" /><category term="jekyll" /><summary type="html"><![CDATA[Welcome to My Blog!]]></summary></entry><entry><title type="html">计算机教育缺失的一课</title><link href="https://baymine.github.io/2024/06/03/" rel="alternate" type="text/html" title="计算机教育缺失的一课" /><published>2024-06-03T02:56:51+00:00</published><updated>2024-06-03T02:56:51+00:00</updated><id>https://baymine.github.io/2024/06/</id><content type="html" xml:base="https://baymine.github.io/2024/06/03/"><![CDATA[<h1 id="shell-工具和脚本"><a href="#Shell-%E5%B7%A5%E5%85%B7%E5%92%8C%E8%84%9A%E6%9C%AC"></a>Shell 工具和脚本</h1>

<ul>
  <li>在bash中，单引号中不会替换变量，双引号会</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">echo '$HOME'</code> 输出 <code class="language-plaintext highlighter-rouge">$HOME</code></p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">echo "$HOME"</code> 输出 <code class="language-plaintext highlighter-rouge">/home/username</code></li>
</ul>

<p><code class="language-plaintext highlighter-rouge">!!</code> 会替换成上一条命令</p>

<h2 id="1-表示函数本身2-表示第一个参数3-表示第二个参数依次类推"><code class="language-plaintext highlighter-rouge">$1</code> 表示函数本身，<code class="language-plaintext highlighter-rouge">$2</code> 表示第一个参数，<code class="language-plaintext highlighter-rouge">$3</code> 表示第二个参数，依次类推</h2>
<p><code class="language-plaintext highlighter-rouge">$?</code> 表示上一条命令的返回值(错误代码)
0 表示成功; 1 表示失败</p>

<p><code class="language-plaintext highlighter-rouge">$#</code> 表示参数个数, <code class="language-plaintext highlighter-rouge">$*</code> 表示所有参数, <code class="language-plaintext highlighter-rouge">$@</code> 表示所有参数, `
$$
` 表示当前进程的进程号</p>

<p><code class="language-plaintext highlighter-rouge">/dev/null</code> 是一个特殊的文件，所有写入它的内容都会被丢弃(黑洞文件)
批量创建文件夹 <code class="language-plaintext highlighter-rouge">mkdir dir{1..10}</code>，创建文件也可以使用同样的方式。</p>
<ul>
  <li>大括号内部的实际上可以算是一个组合元素
<code class="language-plaintext highlighter-rouge">touch {foo,bar}.{py,cpp,c,java}</code></li>
</ul>

<p><code class="language-plaintext highlighter-rouge">#!/usr/bin/env python</code> 这实际上是在指定这个脚本使用的解释器，这样可以直接使用<code class="language-plaintext highlighter-rouge">./script.py</code>来运行脚本，而不需要<code class="language-plaintext highlighter-rouge">python script.py</code></p>

<h2 id="查找文件夹">查找文件（夹）</h2>
<p><code class="language-plaintext highlighter-rouge">find . -name src -type d</code> 查找当前目录下的所有名为<code class="language-plaintext highlighter-rouge">src</code>的文件夹</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">find . -name "*.tmp" -exec rm {} \;</code> 查找当前目录下的所有<code class="language-plaintext highlighter-rouge">.tmp</code>文件并删除</li>
  <li><code class="language-plaintext highlighter-rouge">grep -R foobar .</code></li>
</ul>

<p><code class="language-plaintext highlighter-rouge">ls -R</code> 递归列出所有文件</p>

<h1 id="vim"><a href="#Vim"></a>Vim</h1>
<h1 id="数据整理"><a href="#%E6%95%B0%E6%8D%AE%E6%95%B4%E7%90%86"></a>数据整理</h1>

<ul>
  <li><code class="language-plaintext highlighter-rouge">sed</code>: Stream Editor
支持使用正则表达式进行查询修改： <code class="language-plaintext highlighter-rouge">sed 's/old-text/new-text/g' filename</code></li>
</ul>

<p><code class="language-plaintext highlighter-rouge">sort</code>: 将内容进行排序 , <code class="language-plaintext highlighter-rouge">uniq -c</code>: 统计重复行的次数</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">sort filename | uniq -c</code></li>
</ul>]]></content><author><name>York Cao</name></author><category term="blog" /><summary type="html"><![CDATA[Shell 工具和脚本]]></summary></entry><entry><title type="html">Clickhouse源码阅读日记</title><link href="https://baymine.github.io/2024/05/29/clickhouse/" rel="alternate" type="text/html" title="Clickhouse源码阅读日记" /><published>2024-05-29T13:26:01+00:00</published><updated>2024-05-29T13:26:01+00:00</updated><id>https://baymine.github.io/2024/05/29/clickhouse</id><content type="html" xml:base="https://baymine.github.io/2024/05/29/clickhouse/"><![CDATA[<h1 id="源码"><a href="#%E6%BA%90%E7%A0%81"></a>源码</h1>
<h2 id="列columns"><a href="#%E5%88%97%EF%BC%88Columns%EF%BC%89"></a>列（Columns）</h2>
<h2 id="字段field"><a href="#%E5%AD%97%E6%AE%B5%EF%BC%88Field%EF%BC%89"></a>字段（Field）</h2>
<blockquote>

</blockquote>

<p>src\Core\Field.h</p>

\[字段实现是一个联合类， `std::aligned_union_t`，而一行数据在此文件当中定义为`using Row = std::vector&lt;Field&gt;;`\]

<blockquote>

</blockquote>

<p>Field 中并没有足够的关于一个表（table）的特定数据类型的信息。比如，UInt8、UInt16、UInt32 和 UInt64 在 Field 中均表示为 UInt64。</p>

<p>在代码当中，<code class="language-plaintext highlighter-rouge">createConcrete</code> 是一个模板函数，用于在给定的存储空间中创建一个具体的对象。小类型可能会被存储为更宽的类型，例如 char 可能会被存储为 UInt64。</p>

<h2 id="块block"><a href="#%E5%9D%97%EF%BC%88Block%EF%BC%89"></a>块（Block）</h2>
<blockquote>

</blockquote>

<p>If we have a <code class="language-plaintext highlighter-rouge">Block</code>, we have data (in the <code class="language-plaintext highlighter-rouge">IColumn</code> object), we have information about its type (in <code class="language-plaintext highlighter-rouge">IDataType</code>) that tells us how to deal with that column, and we have the column name.</p>

<p>这个类的成员变量当中有一个由<code class="language-plaintext highlighter-rouge">IColumn</code>指针组成的向量，还有一个由map组成的索引，用于存储列名到列索引的映射。同时还包含一个块信息的结构体。</p>

<h2 id="materializedview"><a href="#MaterializedView"></a>MaterializedView</h2>

<p><code class="language-plaintext highlighter-rouge">MaterializedView</code>是一种特殊的表，它根据预定义的SELECT查询语句存储数据。当插入新数据到源表时，这些数据也会被插入到<code class="language-plaintext highlighter-rouge">MaterializedView</code>中。</p>

<p><code class="language-plaintext highlighter-rouge">MaterializedView</code>的主要用途是预计算复杂的查询。例如，你可能有一个包含大量数据的表，你需要对这个表进行一些复杂的聚合查询。如果每次需要结果时都运行这些查询，可能会非常慢。相反，你可以创建一个<code class="language-plaintext highlighter-rouge">MaterializedView</code>，它根据你的查询预先计算结果。然后，你可以直接查询<code class="language-plaintext highlighter-rouge">MaterializedView</code>，这通常会比直接查询原始表快得多。</p>

<h1 id="编程范式"><a href="#%E7%BC%96%E7%A8%8B%E8%8C%83%E5%BC%8F"></a>编程范式</h1>
<h2 id="-nolint"><a href="#NOLINT"></a>// NOLINT</h2>

<p>在代码中添加 NOLINT 注释是一种指示，通常用于告诉静态代码分析工具或代码审查工具不要对特定行或块发出警告或错误报告。</p>

<p><code class="language-plaintext highlighter-rouge">例如在使用reinterpret_cast的时候</code></p>

<h2 id="类名称helper"><a href="#%E7%B1%BB%E5%90%8D%E7%A7%B0%EF%BC%9A-Helper"></a>类名称：***Helper</h2>

<p>通常是一个模板类的特化，可以是一个中间表示，其中实现了***（类名）的一些功能，作为统一的处理方式</p>

<p><code class="language-plaintext highlighter-rouge">例如：template &lt;typename T&gt; class ColumnVectorHelper;</code></p>

<h2 id="类名称dummy"><a href="#%E7%B1%BB%E5%90%8D%E7%A7%B0%EF%BC%9A-Dummy"></a>类名称：***Dummy</h2>

<p>在C++编程中，如果一个类被命名为含有”Dummy”的名称，比如IColumnDummy，这通常意味着该类是一个占位符类（Placeholder Class）或者是一个模拟类（Mock Class）。</p>

<p><code class="language-plaintext highlighter-rouge">例如：class IColumnDummy : public IColumn;</code></p>

<h2 id="在数组第一个元素前预留一个空间-1th"><a href="#%E5%9C%A8%E6%95%B0%E7%BB%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E5%85%83%E7%B4%A0%E5%89%8D%E9%A2%84%E7%95%99%E4%B8%80%E4%B8%AA%E7%A9%BA%E9%97%B4%EF%BC%88-1th%EF%BC%89"></a>在数组第一个元素前预留一个空间（-1th）</h2>

<p>这个设计在将偏移量数组转换为大小数组时提供了性能优势。在处理这种转换时，通常需要计算当前元素的大小，即下一个元素的偏移量减去当前元素的偏移量。有了额外的 0 值的 -1th 元素，计算第一个元素的大小时，可以直接用 0 减去第一个元素的偏移量，而不需要特殊处理。这样简化了代码，减少了条件分支，并可能提高计算速度。</p>

<p><code class="language-plaintext highlighter-rouge">在链表插入的过程中使用dummy_header也是类似的设计</code></p>

<blockquote>

</blockquote>

<p>1.在高性能计算或大数据处理中，避免条件分支可以显著提高循环的效率，因为现代处理器对分支预测有困难，尤其是在分支密集的情况下。
2.在处理向量数据或使用单指令多数据（SIMD）指令时，if 语句可能导致向量操作的分裂
3.分支惩罚</p>

<p><a href="https://clickhouse.com/docs/zh/development/architecture#lie-columns">对于 String 列和 Array 列，则由两个向量组成：其中一个向量连续存储所有的 String 或数组元素，另一个存储每一个 String 或 Array 的起始元素在第一个向量中的偏移。</a></p>

<p>在这种场景下，偏移数组可能需要转换成大小数组，这个时候可以利用到这种优化</p>

<h1 id="概念"><a href="#%E6%A6%82%E5%BF%B5"></a>概念</h1>
<h2 id="loop-vectorization循环向量化"><a href="#loop-vectorization-%E5%BE%AA%E7%8E%AF%E5%90%91%E9%87%8F%E5%8C%96"></a>loop vectorization(循环向量化)</h2>

<p>循环向量化是一种编译器优化技术，用于将循环转换为向量化指令，以便在单个指令中处理多个数据元素。这种技术可以提高程序的性能，因为它可以利用现代处理器的SIMD指令集，同时减少循环的迭代次数。</p>

\[`例如：for (int i = 0; i &lt; n; ++i) { c[i] = a[i] + b[i]; }`\]

<h1 id="语言语法"><a href="#%E8%AF%AD%E8%A8%80-%E8%AF%AD%E6%B3%95"></a>语言/语法</h1>
<h2 id="c11-using-引入构造函数"><a href="#C-11-using-%E5%BC%95%E5%85%A5%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0"></a>C++11 using 引入构造函数</h2>

<p>1
12</p>

<p>#define DEFINE_FIELD_VECTOR(X) <br />
struct X : public FieldVector <br />
{ <br />
    using FieldVector::FieldVector; <br />
}
‘’’
using FieldVector::FieldVector;：这是 C++11 引入的 using 声明，它引入了基类（FieldVector）的构造函数到派生类（X）的作用域中。
(第一个FieldVector是类名，第二个是构造函数的函数名称，这引入了所有的构造函数)</p>

<p>这意味着 X 类可以使用 FieldVector 的所有构造函数，而无需重复定义。
这有助于避免构造函数的代码重复，并保持代码简洁。
‘’’</p>]]></content><author><name>York Cao</name></author><category term="blog" /><summary type="html"><![CDATA[源码 列（Columns） 字段（Field）]]></summary></entry><entry><title type="html">GeePRC notes</title><link href="https://baymine.github.io/2023/01/05/geeprc-notes/" rel="alternate" type="text/html" title="GeePRC notes" /><published>2023-01-05T08:48:47+00:00</published><updated>2023-01-05T08:48:47+00:00</updated><id>https://baymine.github.io/2023/01/05/geeprc-notes</id><content type="html" xml:base="https://baymine.github.io/2023/01/05/geeprc-notes/"><![CDATA[<h2 id="项目大纲"><a href="#%E9%A1%B9%E7%9B%AE%E5%A4%A7%E7%BA%B2"></a>项目大纲</h2>

<ul>
  <li></li>
</ul>

<p>codec.go</p>

<p>报文Header</p>
<ul>
  <li>消息体编码解码的接口 Codec
读取报头</li>
  <li>读取主体</li>
  <li>写入报头的方法</li>
</ul>

<p>Codec的构造函数
可选用的编码方式</p>
<ul>
  <li>存储在一个map中
不同的编码方式调用不同的codec构造函数</li>
</ul>

<p>gob.go</p>

<ul>
  <li>gob结构体</li>
  <li>GobCodec实现接口codec</li>
</ul>

<p>server.go</p>

<ul>
  <li>Option
标识
Magic number</li>
</ul>

<p>编码方式
默认的Option</p>

<p>main.go</p>

<ul>
  <li>创建一个监听者
通过一个协程在执行</li>
  <li>协程中的得到的地址通过管道通知主线程</li>
</ul>

<p>确定编码方式
发送接收</p>
<ul>
  <li>创建报头</li>
  <li>写入
cc.Write()</li>
</ul>

<p>接收回应</p>
<ul>
  <li>cc.ReadHeader()</li>
</ul>

<h2 id="bug"><a href="#bug"></a>bug</h2>

<p>day5, go run main.go:
rpc server: register Foo.Sum
rpc server debug path: /debug/geerpc
call Foo.Sum error:rpc server: request handle timeout: expect within 10ns
exit status 1</p>

<h2 id="chanllenge"><a href="#Chanllenge"></a>Chanllenge</h2>
<h3 id="网络粘包"><a href="#%E7%BD%91%E7%BB%9C%E7%B2%98%E5%8C%85"></a>网络粘包</h3>

<p>执行 <code class="language-plaintext highlighter-rouge">go test -v</code> 会有一定概率出现测试卡死无响应的bug
<a href="https://github.com/geektutu/7days-golang/issues/26">issue</a></p>

<h2 id="great-designs"><a href="#Great-designs"></a>Great designs</h2>
<h3 id="使用通道实现超时判断"><a href="#%E4%BD%BF%E7%94%A8%E9%80%9A%E9%81%93%E5%AE%9E%E7%8E%B0%E8%B6%85%E6%97%B6%E5%88%A4%E6%96%AD"></a>使用通道实现超时判断</h3>

<p>在goroutine中，完成一步之后往管道内传入<code class="language-plaintext highlighter-rouge">struct {}{}</code>这样，在goroutine外部就可以接收到这些信息，这样外部就知道goroutine内部某个函数完成了，</p>

<p>1
12</p>

<p>callChannel := make(chan struct{})
go func(){
  err := call(args)
  callChannel &lt;- struct{}{}
}()</p>

<p>select {
  case &lt;-time.After(timeout):  // 处理超时
    timeout handling
  case &lt;-callChannel:
    function finished
}</p>

<h2 id="knowledges"><a href="#Knowledges"></a>Knowledges</h2>
<h3 id="如何结束一个goroutine"><a href="#%E5%A6%82%E4%BD%95%E7%BB%93%E6%9D%9F%E4%B8%80%E4%B8%AAgoroutine"></a>如何结束一个goroutine</h3>

<p>利用管道传入一个结束信息（这里是true），然后返回函数即可</p>

<p>1
16</p>

<p>quit := make(chan bool)
go func() {
    for {
        select {
        case &lt;- quit:
            return
        default:
            // Do other stuff
        }
    }
}()</p>

<p>// Do stuff</p>

<p>// Quit goroutine
quit &lt;- true</p>

<h3 id="encodinggob"><a href="#encoding-gob"></a>encoding/gob</h3>

<ul>
  <li>Package gob 管理 gobs 流 - 在编码器（发送器）和解码器（接收器）之间交换的二进制值</li>
  <li>
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>enc := gob.NewEncoder(&amp;network) // 将写入网络。
dec := gob.NewDecoder(&amp;network) // 将从网络上读取。
// Encoding（发送）一些值。
err := enc.Encode(P{3, 4, 5, "Pythagoras"})
// 接收
var q Q
err = dec.Decode(&amp;q)
</code></pre></div>    </div>
  </li>
</ul>

<h3 id="反射"><a href="#%E5%8F%8D%E5%B0%84"></a>反射</h3>
<h3 id="context-package"><a href="#Context-package"></a>Context package</h3>

<ul>
  <li>context 主要用来在 goroutine 之间传递上下文信息，包括：取消信号、超时时间、截止时间、k-v 等。</li>
  <li>一句话：context 用来解决 goroutine 之间 <code class="language-plaintext highlighter-rouge">退出通知</code>、<code class="language-plaintext highlighter-rouge">元数据传递</code>的功能。</li>
  <li><img src="https://pic3.zhimg.com/80/v2-6a27526f536505cea08a5813ccce05b2_720w.webp" alt="" /></li>
</ul>]]></content><author><name>York Cao</name></author><category term="blog" /><summary type="html"><![CDATA[项目大纲]]></summary></entry><entry><title type="html">C++ Memory Management</title><link href="https://baymine.github.io/2022/12/18/c-memory-management/" rel="alternate" type="text/html" title="C++ Memory Management" /><published>2022-12-18T07:04:19+00:00</published><updated>2022-12-18T07:04:19+00:00</updated><id>https://baymine.github.io/2022/12/18/c-memory-management</id><content type="html" xml:base="https://baymine.github.io/2022/12/18/c-memory-management/"><![CDATA[<h1 id="第一讲-primitives"><a href="#%E7%AC%AC%E4%B8%80%E8%AE%B2-primitives"></a>第一讲 primitives</h1>
<h3 id="1-overview"><a href="#1-overview"></a>1. overview</h3>

<ul>
  <li>
    <p>资料： <a href="http://gee.cs.oswego.edu/dl/">DL Malloc</a></p>
  </li>
  <li>
    <p>涉及的库</p>
  </li>
</ul>

<p><img src="https://Baymine.github.io/images/C-Memory-Management/1671347745514.png" alt="1671347745514" /></p>

<h3 id="23-内存分配的每一层面及基本用法"><a href="#2%E3%80%813-%E5%86%85%E5%AD%98%E5%88%86%E9%85%8D%E7%9A%84%E6%AF%8F%E4%B8%80%E5%B1%82%E9%9D%A2%E5%8F%8A%E5%9F%BA%E6%9C%AC%E7%94%A8%E6%B3%95"></a>2、3. 内存分配的每一层面及基本用法</h3>

<p><img src="https://Baymine.github.io/images/C-Memory-Management/1671348085106.png" alt="1671348085106" /></p>

<p>本课程只考虑CRT以上的层次。</p>

<p><strong>基本工具</strong></p>

<p><img src="https://Baymine.github.io/images/C-Memory-Management/1671348161500.png" alt="1671348161500" /></p>

<p><strong>基本用法</strong></p>

<p>1
13</p>

<p>void* p3 = ::operator new (512);   // 512 bytes
::operator delete(p3);</p>

<p>#ifdef <strong>BORLANDC</strong>  // 不同库不同
	// 申请5个int。 一般容器中使用
	int* p4 = allocator<int>().allocate(5);
	allocator<int>().deallocate(p4, 5);
#endif</int></int></p>

<p>#ifdef <strong>GNUC</strong>   // 较早版本中
	void* p4 = alloc::allocate(512);
	alloc::deallocate(p4, 512);
 #endif</p>

<h3 id="456基本构件new-delete-expression"><a href="#4%E3%80%815%E3%80%816%E3%80%81%E5%9F%BA%E6%9C%AC%E6%9E%84%E4%BB%B6%E2%80%94%E2%80%94new-delete-expression"></a>4、5、6、基本构件——new delete expression</h3>
<p>new 中实际上就是在调用malloc</p>

<p>1
9</p>

\[class_name* pc = new class_name(1, 2);\]

<p>// 编译器转换为
// 加上try catch
\(void* mem = operator new(sizeof(class_name));\)
\(pc = static_cast&lt;class_name*&gt;(mem);\)
pc-&gt;class_name::class_name(1, 2); // 只有编译其才能这样调用构造函数
// 但是可以直接调用析构函数</p>

<h3 id="7array-new"><a href="#7%E3%80%81Array-new"></a>7、Array new</h3>
<p>当new一个数组的时候，系统会使用4个字节存放数组的一些信息，即为下图中的 <code class="language-plaintext highlighter-rouge">cookie</code></p>

<p>1</p>

<p>Complex* pca = new Complex[3];</p>

<p><img src="https://Baymine.github.io/images/C-Memory-Management/1671438018665.png" alt="1671438018665" /></p>

<ul>
  <li>在进行array new的时候，单个元素不会独自进行内存对齐。</li>
  <li>构建的时候是从上往下，析构的时候是由下往上</li>
  <li><img src="https://Baymine.github.io/images/C-Memory-Management/1671439085184.png" alt="1671439085184" /></li>
</ul>

<p><code class="language-plaintext highlighter-rouge">61h</code>就是cokie，需要进行内存对齐（VC6)中是16位对齐</p>
<ul>
  <li>对于申请的int类型的数组，可以直接使用delete，因为这些数据类型没有析构函数，</li>
</ul>

<p><img src="https://Baymine.github.io/images/C-Memory-Management/1671440046493.png" alt="1671440046493" /></p>
<ul>
  <li>因为数组个数被写入，所以内存的整体布局会发生变化，所以不能直接用 <code class="language-plaintext highlighter-rouge">delete</code>来回收</li>
  <li><code class="language-plaintext highlighter-rouge">61h</code>的大小计算
\(类大小*类个数=((3*4) * 3) = 36\ 上下debugger header = 32 + 4\ 两个61h=4*2=8\)</li>
  <li>最后向16的倍数内存对齐最后的 <code class="language-plaintext highlighter-rouge">pad</code></li>
</ul>

<h3 id="8palcement-new"><a href="#8-palcement-new"></a>8.palcement new</h3>

<p>允许将对象构造与已分配的内存中</p>

<p><img src="https://Baymine.github.io/images/C-Memory-Management/1671441329456.png" alt="1671441329456" /></p>

<h3 id="9random"><a href="#9-random"></a>9.random</h3>

<ul>
  <li>placement new 的重载</li>
  <li>嵌入式指针使用案例（内存池）
通过一次性申请一定量的内存，减少每个内存中的cookie的数量，同时减少malloc的调用</li>
  <li>整个内存是通过一个链表管理的，释放内存就是将空闲的内存插入到链表头部</li>
  <li>但是申请的内存没有真正释放，所以可能会存在使用峰值的问题</li>
</ul>

<p><img src="https://Baymine.github.io/images/C-Memory-Management/1671541094430.png" alt="1671541094430" /></p>

<ul>
  <li>可以自定义handler来让更多的空间可用，或者调用abort() 或 exit();</li>
</ul>

<p>1</p>

<p>set_new_handler(handlerFunctionPoint);</p>

<ul>
  <li>default, delete 关键字</li>
</ul>]]></content><author><name>York Cao</name></author><category term="blog" /><summary type="html"><![CDATA[第一讲 primitives 1. overview]]></summary></entry><entry><title type="html">MIT6.S081</title><link href="https://baymine.github.io/2022/12/16/mit6s081/" rel="alternate" type="text/html" title="MIT6.S081" /><published>2022-12-16T03:53:01+00:00</published><updated>2022-12-16T03:53:01+00:00</updated><id>https://baymine.github.io/2022/12/16/mit6s081</id><content type="html" xml:base="https://baymine.github.io/2022/12/16/mit6s081/"><![CDATA[<h1 id="reading"><a href="#Reading"></a>Reading</h1>
<h3 id="chapter-1-operating-system-interfaces"><a href="#Chapter-1-Operating-system-interfaces"></a>Chapter 1: Operating system interfaces</h3>

<ul>
  <li>the shell is a user program, and not part of the kernel</li>
  <li>Although the child has the same memory contents as the parent initially, the parent and child are executing with different memory and different registers: changing a variable in one does not affect the other.</li>
  <li></li>
</ul>

<p><code class="language-plaintext highlighter-rouge">exec</code> replaces the calling process’s memory but preserves its file table</p>

<p><code class="language-plaintext highlighter-rouge">exec</code> replaces the memory and registers of the current process with a new program</p>

<p>I/O and File descriptors</p>

<ul>
  <li>The shell ensures that it always has three file descriptors open
std input, std output, std error</li>
  <li>先close(0); 然后open, 让文件描述符与读相连接</li>
</ul>

<p>read(fd, buf, n)
write(fd, buf, n)</p>

<p><code class="language-plaintext highlighter-rouge">dup</code> system call duplicates an existing file descriptor, returning a new one that refers to the same underlying I/O object.
File descriptors are a powerful abstraction, because they hide the details of what they are connected to</p>

<p>1.3 Pipes</p>

<ul>
  <li>A pipe is a small kernel buffer exposed to processes as a pair of file descriptors, one for reading and one for writing.</li>
  <li>
    <table>
      <tbody>
        <tr>
          <td>命令行pipe实例： grep fork sh.c</td>
          <td>wc -l 程序会分别为两个程序创建一个子进程，并递归地运行命令（可能会出现多管道的现象， a</td>
          <td>b</td>
          <td>c）</td>
        </tr>
      </tbody>
    </table>
  </li>
  <li>与重定向的优势
会自动清理（重定向需要小心清理临时文件）</li>
  <li>能传入任意长的数据流（重定向需要足够的disk空间存储所有的数据）</li>
  <li>能够并行执行（重定向只能串行）</li>
</ul>

<p>1.4 File system</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">chdir</code>: change current directory</li>
  <li><code class="language-plaintext highlighter-rouge">mkdir</code> creates a new directory, <code class="language-plaintext highlighter-rouge">open</code> with the <code class="language-plaintext highlighter-rouge">O_CREATE</code> flag creates a new data file, and <code class="language-plaintext highlighter-rouge">mknod</code> creates a new device file</li>
  <li>The <code class="language-plaintext highlighter-rouge">link</code> system call creates another file system name referring to the same inode as an existing file.</li>
  <li>The <code class="language-plaintext highlighter-rouge">fstat</code> system call retrieves information from the inode that a file descriptor refers to. It fills in a <code class="language-plaintext highlighter-rouge">struct stat</code>, defined in <code class="language-plaintext highlighter-rouge">stat.h</code>
Each inode is identified by a unique <code class="language-plaintext highlighter-rouge">inode number</code>.</li>
  <li>The file’s inode and the disk space holding its content are only freed when the file’s link count is zero and no file descriptors refer to it(using <code class="language-plaintext highlighter-rouge">unlink</code>)</li>
</ul>

<p>sum-up： 文件目录变换，文件的结构和信息，文件的创建和关闭，Unix中运行文件相关命令的方法</p>

<h3 id="chapter-2-operating-system-organization"><a href="#Chapter-2-Operating-system-organization"></a>Chapter 2: Operating system organization</h3>

<ul>
  <li>Thus an operating system must fulfill three requirements: multiplexing, isolation, and interaction.</li>
  <li></li>
</ul>

<p>2.1 Abstracting physical resources</p>

<p>通过函数结构访问disk的优势（让OS管理内存）</p>

<p>2.2 User mode, supervisor mode, and system calls</p>

<ul>
  <li>Machine mode
have full privilege; a CPU starts in machine mode. Machine mode is mostly intended for configuring a computer.</li>
</ul>

<p>Supervisor mode(Kernel space)</p>
<ul>
  <li>the CPU is allowed to execute privileged instructions
If running privileged instructions in user mode, CPU wouldn’t execute it, but switch to the supervisor mode to terminate it</li>
</ul>

<p>the kernel control the entry point for transitions to supervisor mode</p>

<p>User mode(User space)
实现程序之间隔离的方法</p>

<p>2.3 Kernel organization</p>

<ul>
  <li></li>
</ul>

<p>monolithic kernel</p>

<h2 id="the-entire-operating-system-resides-in-the-kernel-so-that-the-implementations-of-all-system-calls-run-in-supervisor-mode">The <strong>entire operating system resides in the kernel</strong>, so that the implementations of all system calls run in supervisor mode</h2>
<p><code class="language-plaintext highlighter-rouge">Pros</code>: Easy to cooperate, doesn’t have to decide which part of the operating system doesn’t need full hardware privileg</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">Cons</code>: 1. the interfaces between different parts of the operating system are often complex 2. a mistake is fatal, because an error in supervisor mode will often cause the kernel to fail</li>
</ul>

<p>microkernel</p>

<ul>
  <li>minimize the amount of operating system code that runs in supervisor mode</li>
  <li><img src="https://Baymine.github.io/images/MIT6-S081/microkernel.png" alt="img" /></li>
  <li>the kernel provides an <code class="language-plaintext highlighter-rouge">inter-process communication mechanism</code> to send messages from one user-mode process to another</li>
  <li>OS services running as processes are called servers.
it sends a message to the file server and waits for a response.</li>
</ul>

<p>sum-up： 两种不同的内核设计方式</p>

<p>2.5 Process overview</p>

<ul>
  <li>The unit of isolation is a process.</li>
  <li>The mechanisms used by the kernel to implement processes include the user/supervisor mode flag, address spaces, and time-slicing of threads</li>
  <li></li>
</ul>

<p>Xv6 maintains a separate page table for each process that defines that process’s address space</p>

<p><img src="https://Baymine.github.io/images/MIT6-S081/virtual%20address%20space.png" alt="img" /></p>

<p>the trampoline page contains the code to transition in and out of the kernel</p>
<ul>
  <li>mapping the trapframe is necessary to save/restore the state of the user process</li>
</ul>

<p>The xv6 kernel maintains many pieces of state for each process, which it gathers into a <code class="language-plaintext highlighter-rouge">struct proc</code></p>

<ul>
  <li>most important pieces of kernel state are its page table, its kernel stack, and its run state.</li>
</ul>

<p>Context switch between user space and kernel space</p>

<ul>
  <li>To switch transparently between processes, the kernel suspends the currently running thread and resumes another process’s thread.</li>
  <li>Each process has two stacks: a user stack and a kernel stack (<code class="language-plaintext highlighter-rouge">p-&gt;kstack</code>)
the kernel can execute even if a process has wrecked its user stack.</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">ecall</code>: change to kernel space; <code class="language-plaintext highlighter-rouge">sret</code>: to user space</p>

<p>Sum-up</p>
<ul>
  <li>an address space to give a process the illusion of its own memory, and, a thread, to give the process the illusion of its own CPU</li>
  <li>如何利用进程实现隔离性的以及进程的工作方式</li>
</ul>

<p>2.7 Security Model</p>

<ul>
  <li>Safeguards
Assertions, type checking, stack guard pages, etc.</li>
</ul>

<h3 id="chapter-3-page-tables"><a href="#Chapter-3-Page-tables"></a>Chapter 3: Page tables</h3>

<ul>
  <li>provides each process with its own private address space and memory</li>
  <li>Xv6 performs a few tricks: mapping the same memory (a trampoline page) in several address spaces, and guarding kernel and user stacks with an unmapped page.</li>
  <li></li>
</ul>

<p>3.1 Paging hardware</p>

<p>The structure of page table</p>

<p><img src="https://Baymine.github.io/images/MIT6-S081/pageTable.png" alt="img" /></p>

<p>Address translation</p>

<ul>
  <li>A page table is stored in physical memory as a three-level tree. (first nine bits is used for indexing PPN of each <code class="language-plaintext highlighter-rouge">page directory</code>. and etc.)</li>
  <li>
    <p>If page is not found, raise <code class="language-plaintext highlighter-rouge">page-fault exception</code></p>
  </li>
  <li>In the common case in which large ranges of virtual addresses have no mappings, the three-level structure can omit entire page directories.(Allocate pages when they are needed)</li>
  <li>flag bits that tell the paging hardware how the associated virtual address is allowed to be used</li>
</ul>

<p><strong>每个PTE都包含标志位，说明虚拟地址的使用权限。</strong></p>

<h2 id="pte_v表示-pte-是否存在于页表中如果未设置那么一个对该页的引用会引发错误也就是不允许被使用-validity-"><code class="language-plaintext highlighter-rouge">PTE_V</code>表示 PTE 是否存在于页表中：如果未设置，那么一个对该页的引用会引发错误(也就是：不允许被使用（ <strong>validity</strong> ）)。</h2>
<p><code class="language-plaintext highlighter-rouge">PTE_W</code>控制着能否对页执行写操作；</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">PTE_R</code> 控制是否允许使用指令读取页。</li>
  <li><code class="language-plaintext highlighter-rouge">PTE_X</code>控制CPU是否可以将页面内容解释为指令并执行它们。</li>
  <li><code class="language-plaintext highlighter-rouge">PTE_U</code>控制着用户程序能否使用该页；如果不能，则只有内核能够使用该页。</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">satp</code>: the physical address of the root pagetable page</p>
<ul>
  <li>each CPU has its own <code class="language-plaintext highlighter-rouge">satp</code>(different CPUs can run different processes)</li>
</ul>

<p><img src="https://Baymine.github.io/images/MIT6-S081/address%20translation.png" alt="img" /></p>

<p>Translation Look-aside Buffer (TLB)</p>

<ul>
  <li>Motivation: To avoid the cost of loading PTEs from physical memory
a potential downside of three levels is that the CPU must load three PTEs from memory to perform the translation of the virtual address in the load/store instruction to a physical address.</li>
</ul>

<p>when xv6 changes a page table, it must tell the CPU to invalidate corresponding cached TLB entries.</p>

<p>3.2 Kernel address space</p>

<ul>
  <li>Xv6 maintains one page table per process, describing each process’s user address space, plus a single page table that describes the kernel’s address space</li>
  <li>The kernel gets at RAM and memory-mapped device registers using “direct mapping;
Direct mapping simplifies kernel code that reads or writes physical memory.</li>
</ul>

<p>The guard page’s PTE is invalid (i.e.,PTE_V is not set), so that if the kernel overflows a kernel stack, it will likely cause an exception
<img src="https://Baymine.github.io/images/MIT6-S081/kernel%20address%20space.png" alt="img" /></p>

<p>3.4 Physical memory allocation</p>

<ul>
  <li>The kernel must allocate and free physical memory at run-time for page tables, user memory, kernel stacks, and pipe buffers.</li>
  <li>Allocation consists of removing a page from the linked list; freeing consists of adding the freed page to the list.</li>
</ul>

<p>3.6 Process address space</p>

<ul>
  <li><img src="https://Baymine.github.io/images/MIT6-S081/user%20addr%20space.png" alt="img" /></li>
  <li>A process’s user memory starts at virtual address zero and can grow up to <code class="language-plaintext highlighter-rouge">MAXVA</code>(The max bits the address can take)</li>
  <li>Xv6 maps the data, stack, and heap with the permissions <code class="language-plaintext highlighter-rouge">PTE_R</code>, <code class="language-plaintext highlighter-rouge">PTE_W</code>, and <code class="language-plaintext highlighter-rouge">PTE_U</code>.
Avoid the program modifies the unexpected regions.(the hardware will refuse to execute the store and raises a page fault)</li>
</ul>

<h5 id="lecture-note"><a href="#Lecture-Note"></a>Lecture Note</h5>

<ul>
  <li>Address space
pagetable
implemented in hardware by the processor or by unit called MMU</li>
  <li>CPU—VA—&gt;MMU—-PA—-&gt;Memory</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">satp</code>: In CPU, this register is used to specify where the map is(VA-&gt;PA). Each one process has unique address for the map(This is writen by the kernel for isolation)</p>
<ul>
  <li>MMU: 读取内存并转换，不保存映射</li>
</ul>

<p>The max bits of the virtual address is determined by the number of the registers</p>

<p>paging hardware(RISC-V)
xv6 virtual memory code and layout of the kernel address spaces and user address spaces
多级页表中存储PPN是44位的，末尾加上12个0，得到56位物理地址，这就是下一级页表的物理地址</p>
<ul>
  <li>多次访问耗费时间，所以使用TLB（快表）[VA, PA] mapping</li>
</ul>

<p>MMU —-hardware</p>

<h3 id="chapter-4-traps-and-system-calls"><a href="#Chapter-4-Traps-and-system-calls"></a>Chapter 4 Traps and system calls</h3>

<ul>
  <li></li>
</ul>

<p>CPU Interrupt</p>

<p>Cases</p>

<p>system call</p>
<ul>
  <li>exception</li>
  <li>device interrupt
While commonality among the three trap types suggests that a kernel could handle all traps with a single code path, it turns out to be convenient to have separate code for three distinct cases: traps from user space, traps from kernel space, and timer interrupts.</li>
</ul>

<p>The usual sequence</p>

<ul>
  <li>a trap forces a transfer of control into the kernel</li>
  <li>the kernel saves registers and other state</li>
  <li>the kernel restores the saved state and returns from the trap</li>
  <li>original code resumes where it left off</li>
</ul>

<p>For what</p>

<ul>
  <li>isolation demands that only the kernel be allowed to use devices</li>
  <li>the kernel is a convenient mechanism with which to share devices among multiple processes</li>
</ul>

<p>4.1 RISC-V trap machinery</p>

<ul>
  <li>Each RISC-V CPU has a set of control registers that the kernel writes to tell the CPU how to handle traps, and that the kernel can read to find out about a trap that has occurred.</li>
  <li>sum-up: CPU用专用的寄存器完成上下文转换。但为了trap的效率CPU并不会将所有任务都完成，剩余的工作需要由内核软件完成</li>
</ul>

<p>4.2 Traps from user space</p>

<ul>
  <li>Occur if the user program makes a system call (<code class="language-plaintext highlighter-rouge">ecall</code> instruction), or does something illegal, or if a device interrupts</li>
  <li>RISC-V hardware does not switch page tables when it forces a trap
Things need to do
trap handling code needs to switch to the kernel page table</li>
  <li>the kernel page table must also have a mapping for the handler pointed to by stvec</li>
</ul>

<h2 id="trampoline-page">Trampoline page</h2>
<blockquote>

</blockquote>

<p>Trampoline page <strong>stores code to switch between user and kernel space</strong>. The code is mapped at the same virtual address (TRAMPOLINE) in user and kernel space so that it continues to work when it switches page tables.</p>

<p><code class="language-plaintext highlighter-rouge">TRAPFRAME</code></p>
<ul>
  <li>address of <code class="language-plaintext highlighter-rouge">TRAPFRAME</code> is stored in <code class="language-plaintext highlighter-rouge">sscratch</code> register. Saves all the user registers there, including the user’s a0, read back from sscratch.</li>
  <li><code class="language-plaintext highlighter-rouge">TRAPFRAME</code> also contain the kernel information and the address of <code class="language-plaintext highlighter-rouge">usertrap</code> function.</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">usertrap</code>: The job of <code class="language-plaintext highlighter-rouge">usertrap</code> is to determine the cause of the trap, process it, and return</p>

<p>Pointer as argument on system call</p>
<ul>
  <li>Problems
Invalid pointer</li>
  <li>kernel page table mappings are not the same as the user page table mappings so the kernel cannot use ordinary instructions to load or store from user-supplied addresses.</li>
</ul>

<p>Find PA by using user space page table and map it to the VA in the kernel space.</p>

<p>sum-up: 在用户空间中调用trap。</p>

<p>4.5 Traps from kernel space</p>

<p>4.6 Page-fault exceptions</p>

<ul>
  <li></li>
</ul>

<p>Actions</p>

<p>In user space: kill the faulting process</p>
<ul>
  <li>In kernel space: kernel panics</li>
</ul>

<blockquote>

</blockquote>

<p><strong>内核错误 (Kernel panic</strong> )是指操作系统在监测到内部的致命错误，并无法安全处理此错误时采取的动作。</p>

<p>three kinds of page fault</p>

<ul>
  <li>load page faults (when a load instruction cannot translate its virtual address)</li>
  <li>store page faults (when a store instruction cannot translate its virtual address)</li>
  <li>instruction page faults (when the address in the program counter doesn’t translate)</li>
</ul>

<p>The applications of page-fault exception</p>

<ul>
  <li></li>
</ul>

<p>copy-on-write fork</p>

<p>Procedure
the parent and child to initially share all physical pages, but for each to map them read-only</p>
<ul>
  <li>Write to that memory will raise a page-fault exception</li>
  <li>The kernel’s trap handler responds by allocating a new page of physical memory and
copying into it the physical page that the faulted address maps to.</li>
</ul>

<p>Lazy allocation</p>

<ul>
  <li>
    <p>Procedure
application asks for more memory by calling <code class="language-plaintext highlighter-rouge">sbrk</code></p>
  </li>
  <li>The kernel notes the increase in size, but does not allocate memory or create PTEs</li>
  <li>When page-fault occurs in those address, the kernel allocates a page of physical memory and maps it into the page table</li>
</ul>

<p>Since applications often ask for more memory than they need
Problem</p>
<ul>
  <li>The extra overhead introduced by kernel/user transition
reduce this cost by allocating a batch of consecutive pages per page fault instead of one page</li>
  <li>specializing the kernel entry/exit code for such page-faults.</li>
</ul>

<p>demand paging(需求分页)</p>

<ul>
  <li></li>
</ul>

<p>Problem</p>

<p>Since applications can be large and reading from disk is expensive, this startup cost may be noticeable to users</p>

<p>Solution</p>

<ul>
  <li>a modern kernel creates the page table for the user address space, but marks the PTEs for the pages invalid</li>
  <li>On a page fault, the kernel reads the content of the page from disk and maps it into the user address space</li>
</ul>

<p>paging to disk</p>

<ul>
  <li></li>
</ul>

<p>Problem</p>

<p>The programs running on a computer may need more memory than the computer has RAM</p>

<p>Solution</p>

<ul>
  <li>to store only a fraction of user pages in RAM, and to store the rest on disk in a paging area.</li>
  <li>The memory stored in the paging area is set as invalid.</li>
  <li>Access paging area will incur a page fault. The kernel trap handler will allocate a page of physical RAM, read the page from disk into the RAM, and modify the relevant PTE to point to the RAM</li>
</ul>

<h3 id="chapter5-interrupts-and-device-drivers"><a href="#Chapter5-Interrupts-and-device-drivers"></a>Chapter5 Interrupts and device drivers</h3>

<ul>
  <li>A driver is the code in an operating system that
manages a particular device: it configures the device hardware tells the device to perform operations</li>
  <li>handles the resulting interrupts</li>
  <li>interacts withprocesses that may be waiting for I/O from the device.</li>
</ul>

<p>device drivers execute code in two contexts</p>
<ul>
  <li>top half that runs in a process’s kernel thread
ask the hardware to start an operation</li>
  <li>wait for the operation complete</li>
  <li>raise an interrupt when the code is completed</li>
</ul>

<p>a bottom half that executes at interrupt time.</p>
<ul>
  <li>what operation has completed, wakes up a waiting process if appropriate</li>
  <li>tells the hardware to start work on any waiting next operation</li>
</ul>

<p>A general pattern to note is the decoupling of device activity from process activity via buffering
and interrupts. (This idea is sometimes called <code class="language-plaintext highlighter-rouge">I/O concurrency</code>.)</p>
<ul>
  <li>This decoupling can increase performance by allowing processes to execute concurrently with device I/O</li>
</ul>

<p>驱动程序完全禁用中断，并定期检查设备是否需要注意。这种技术被称为轮询（polling）</p>
<ul>
  <li>如果设备执行操作非常快，轮询是有意义的，但是如果设备大部分空闲，轮询会浪费CPU时间。一些驱动程序根据当前设备负载在轮询和中断之间动态切换。</li>
</ul>

<p>程序I/O很简单，但速度太慢，无法在高数据速率下使用。需要高速移动大量数据的设备通常使用直接内存访问（DMA）</p>
<ul>
  <li>DMA设备硬件直接将传入数据写入内存，并从内存中读取传出数据。</li>
  <li>一些操作系统能够直接在用户空间缓冲区和设备硬件之间移动数据，通常带有DMA。</li>
</ul>

<h3 id="lock"><a href="#lock"></a>lock</h3>

<ul>
  <li>锁的缺点是它们会扼杀性能，因为它们会串行化并发操作</li>
  <li></li>
</ul>

<p>竞态条件是指多个进程读写某些共享数据（至少有一个访问是写入）的情况</p>

<h2 id="在内存池中两个进程并行地释放内存那么可能会导致释放的内存被放到同一个地址中从而变成了覆盖">在内存池中，两个进程并行地释放内存，那么可能会导致释放的内存被放到同一个地址中，从而变成了覆盖</h2>
<p><code class="language-plaintext highlighter-rouge">acquire</code>和 <code class="language-plaintext highlighter-rouge">release</code>之间的指令序列通常被称为临界区域（critical section）。（加锁的区域）</p>
<ul>
  <li>代码在执行的时候，依托一些 <code class="language-plaintext highlighter-rouge">不变量</code>(相当于一些条件)，但是其他进程对这个变量的操作暂时改变了这种不变量，所以导致代码运行错误。（上面就是链表头部指针有一个时间段中不是指向链表头部的，这时候其他进程的操作就可能导致竞态）</li>
  <li>以将锁视为串行化（serializing）并发的临界区域，以便同时只有一个进程在运行这部分代码，从而维护不变量（假设临界区域设定了正确的隔离性）</li>
</ul>

<p>冲突</p>

<ul>
  <li>如果多个进程同时想要相同的锁或者锁经历了争用，则称之为发生冲突（conflict）</li>
</ul>

<p>要使用多少锁，以及每个锁应该保护哪些数据和不变量</p>

<ul>
  <li>任何时候可以被一个CPU写入，同时又可以被另一个CPU读写的变量，都应该使用锁来防止两个操作重叠</li>
  <li>锁保护不变量（invariants）：如果一个不变量涉及多个内存位置，通常所有这些位置都需要由一个锁来保护，以确保不变量不被改变。</li>
  <li>大内核锁（big kernel lock）
如果并行性不重要，那么可以安排只拥有一个线程，而不用担心锁。一个简单的内核可以在多处理器上做到这一点，方法是拥有一个锁，这个锁必须在进入内核时获得，并在退出内核时释放</li>
</ul>

<p>死锁和锁排序</p>

<ul>
  <li>如果在内核中执行的代码路径必须同时持有数个锁，那么所有代码路径以相同的顺序获取这些锁是很重要的（否则有死锁的风险）</li>
  <li>全局锁获取顺序的需求意味着锁实际上是每个函数规范的一部分：调用者必须以一种使锁按照约定顺序被获取的方式调用函数。</li>
</ul>

<p>锁和中断处理函数</p>

<ul>
  <li>一个进程中持有一个变量，在执行过程中出现了中断，而中断处理函数可能又会需要访问这个变量，这时候处理函数就会等待这个变量被释放，这时候就产生了死锁
如果一个自旋锁被中断处理程序所使用，那么CPU必须保证在启用中断的情况下永远不能持有该锁。</li>
</ul>

<p>Re-entrant locks</p>

<ul>
  <li>It might appear that some deadlocks and lock-ordering challenges could be avoided by using re-entrant locks, which are also called recursive locks.
if the lock is held by a process and if that process attempts to acquire the lock again, then the kernel could just allow this</li>
</ul>

<p>指令和内存访问顺序</p>

<ul>
  <li>规则确实允许重新排序后改变并发代码的结果，并且很容易导致多处理器上的不正确行为。CPU的排序规则称为内存模型（memory model）。</li>
  <li><code class="language-plaintext highlighter-rouge">__sync_synchronize()</code>是一个内存障碍：它告诉编译器和CPU不要跨障碍重新排序 <code class="language-plaintext highlighter-rouge">load</code>或 <code class="language-plaintext highlighter-rouge">store</code>指令。</li>
</ul>

<p>睡眠锁</p>

<ul>
  <li>因为等待会浪费CPU时间，所以自旋锁最适合短的临界区域；睡眠锁对于冗长的操作效果很好。</li>
</ul>

<h3 id="调度"><a href="#%E8%B0%83%E5%BA%A6"></a>调度</h3>

<ul>
  <li></li>
</ul>

<p>任何操作系统都可能运行比CPU数量更多的进程，所以需要一个进程间分时共享CPU的方案</p>

<p>通过将进程多路复用到硬件CPU上，使每个进程产生一种错觉，即它有自己的虚拟CPU</p>

<p>多路复用</p>

<ul>
  <li>情景
进程等待设备或管道I/O完成，或等待子进程退出，或在 <code class="language-plaintext highlighter-rouge">sleep</code>系统调用中等待时，xv6使用睡眠（sleep）和唤醒（wakeup）机制切换</li>
  <li>xv6周期性地强制切换以处理长时间计算而不睡眠的进程。</li>
</ul>

<p>协程</p>

<ul>
  <li>在两个线程之间进行这种样式化切换的过程有时被称为协程（coroutines）
协程运行在线程之上，当一个协程执行完成后，可以选择主动让出，让另一个协程运行在当前线程之上。 <strong>协程并没有增加线程数量，只是在线程的基础之上通过分时复用的方式运行多个协程</strong> ，而且协程的切换在用户态完成，切换的代价比线程从用户态到内核态的代价小很多。</li>
  <li><img src="https://pic3.zhimg.com/80/v2-f4fb2dea86d909ed60498b7021d0fe66_720w.webp" alt="img" /></li>
  <li>每个线程中运行多个协程</li>
  <li><strong>协程只有和异步IO结合起来才能发挥出最大的威力。</strong>
假设协程运行在线程之上，并且协程调用了一个阻塞IO操作，这时候会发生什么？实际上操作系统并不知道协程的存在，它只知道线程，<strong>因此在协程调用阻塞IO操作的时候，操作系统会让线程进入阻塞状态，当前的协程和其它绑定在该线程之上的协程都会陷入阻塞而得不到调度，这往往是不能接受的。</strong></li>
</ul>

<p>sleep 和 wakeup</p>
<ul>
  <li>Xv6使用了一种称为 <code class="language-plaintext highlighter-rouge">sleep</code>和 <code class="language-plaintext highlighter-rouge">wakeup</code>的方法，它允许一个进程在等待事件时休眠，而另一个进程在事件发生后将其唤醒。睡眠和唤醒通常被称为序列协调（sequence coordination）或条件同步机制（conditional synchronization mechanisms）。</li>
</ul>

<h2 id="sleepchan在任意值-chan上睡眠称为等待通道wait-channel-释放cpu用于其他任务"><code class="language-plaintext highlighter-rouge">Sleep(chan)</code>在任意值 <code class="language-plaintext highlighter-rouge">chan</code>上睡眠，称为等待通道（wait channel）。 释放CPU用于其他任务</h2>
<p><code class="language-plaintext highlighter-rouge">Wakeup(chan)</code>唤醒所有在 <code class="language-plaintext highlighter-rouge">chan</code>上睡眠的进程（如果有），使其 <code class="language-plaintext highlighter-rouge">sleep</code>调用返回。</p>
<ul>
  <li>为了防止死锁，使用 <code class="language-plaintext highlighter-rouge">条件锁</code>，让进程在睡眠之后释放锁</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">条件锁</code>就是所谓的条件变量，某一个线程因为某个条件为满足时可以使用条件变量使该程序处于阻塞状态。一旦条件满足以“信号量”的方式唤醒一个因为该条件而被阻塞的线程。</p>

<h3 id="文件"><a href="#%E6%96%87%E4%BB%B6"></a>文件</h3>

<ul>
  <li>文件系统的目的是组织和存储数据</li>
  <li>解决的问题
文件系统需要磁盘上的数据结构来表示目录和文件名称树，记录保存每个文件内容的块的标识，以及记录磁盘的哪些区域是空闲的。</li>
  <li>文件系统必须支持崩溃恢复（crash recovery）。</li>
  <li>文件系统代码必须协调以保持不变量（不同的进程可能在相同的文件系统上运行）</li>
  <li>文件系统必须保持常用块的内存缓存（访问磁盘慢）</li>
</ul>

<p>文件描述符（File descriptor）</p>

<p>路径名（Pathname）</p>

<p>目录（Directory）</p>

<p>索引结点（Inode）</p>

<p>日志（Logging）</p>

<p>缓冲区高速缓存（Buffer cache）</p>

<p>磁盘（Disk)</p>

<p><img src="./https://Baymine.github.io/images/MIT6-S081/Structure%20of%20file%20system.png" alt="" /></p>

<ul>
  <li>日志
日志驻留在超级块中指定的未知。</li>
  <li>事务中途奔溃将导致日志头块中的计数为0，提交后奔溃将导致非零计数</li>
</ul>

<h1 id="notes"><a href="#Notes"></a>Notes</h1>
<h2 id="lecture-3-os-design"><a href="#Lecture-3-OS-design"></a>Lecture 3: OS design</h2>

<ul>
  <li></li>
</ul>

<p>Lecture Topic:</p>

<p>OS design
system calls</p>
<ul>
  <li>micro/monolithic kernel</li>
</ul>

<p>First system call in xv6</p>

<p>OS picture</p>

<ul>
  <li>apps: sh, echo, …</li>
  <li>system call interface (open, close,…)
OS</li>
</ul>

<p>Goal of OS</p>

<ul>
  <li>run multiple applications</li>
  <li>isolate them</li>
  <li>multiplex them</li>
  <li>share</li>
</ul>

<p>Strawman design: No OS</p>

<ul>
  <li>Application directly interacts with hardware
CPU cores &amp; registers</li>
  <li>DRAM chips</li>
  <li>Disk blocks</li>
  <li>…</li>
</ul>

<p>OS library perhaps abstracts some of it</p>

<p>Strawman design not conducive to multiplexing</p>

<ul>
  <li>each app periodically must give up hardware</li>
  <li>BUT, weak isolation
app forgets to give up, no other app runs</li>
  <li>apps has end-less loop, no other app runs</li>
  <li>you cannot even kill the badly app from another app</li>
</ul>

<p>but used by real-time OSes</p>
<ul>
  <li>“cooperative scheduling”</li>
</ul>

<p>Strawman design not conducive to memory isolation</p>

<ul>
  <li>all apps share physical memory</li>
  <li>one app can overwrites another apps memory</li>
  <li>one app can overwrite OS library</li>
</ul>

<p>Unix interface conducive to OS goals</p>

<ul>
  <li>abstracts the hardware in way that achieves goals</li>
  <li>processes (instead of cores): fork
OS transparently allocates cores to processes
Saves and restore registers</li>
</ul>

<p>Enforces that processes give them up</p>
<ul>
  <li>Periodically re-allocates cores</li>
</ul>

<p>memory (instead of physical memory): exec</p>
<ul>
  <li>Each process has its “own” memory</li>
  <li>OS can decide where to place app in memory</li>
  <li>OS can enforce isolation between memory of different apps</li>
  <li>OS allows storing image in file system</li>
</ul>

<p>files (instead of disk blocks)</p>
<ul>
  <li>OS can provide convenient names</li>
  <li>OS can allow sharing of files between processes/users</li>
</ul>

<p>pipes (instead of shared physical mem)</p>
<ul>
  <li>OS can stop sender/receiver</li>
</ul>

<p>OS must be defensive</p>

<ul>
  <li>an application shouldn’t be able to crash OS</li>
  <li>an application shouldn’t be able to break out of its isolation</li>
  <li>=&gt; need strong isolation between apps and OS</li>
  <li>approach: hardware support</li>
</ul>

<p>user/kernel mode
virtual memory</p>

<p>Processors provide user/kernel mode</p>

<ul>
  <li>kernel mode: can execute “privileged” instructions
e.g., setting kernel/user bit</li>
  <li>e.g., reprogramming timer chip</li>
</ul>

<p>user mode: cannot execute privileged instructions
Run OS in kernel mode, applications in user mode
[RISC-V has also an M mode, which we mostly ignore]</p>

<p>Processors provide virtual memory</p>

<ul>
  <li>Hardware provides page tables that translate virtual address to physical</li>
  <li>Define what physical memory an application can access</li>
  <li>OS sets up page tables so that each application can access only its memory</li>
</ul>

<p>Apps must be able to communicate with kernel</p>

<ul>
  <li>Write to storage device, which is shared =&gt; must be protected =&gt; in kernel</li>
  <li>Exit app</li>
  <li>…</li>
</ul>

<p>Solution: add instruction to change mode in controlled way</p>

<ul>
  <li>
    <p>ecall <code class="language-plaintext highlighter-rouge">&lt;n&gt;</code></p>
  </li>
  <li>
    <p>enters kernel mode at a pre-agreed entry point</p>
  </li>
</ul>

<p>Modify OS picture</p>

<ul>
  <li>user / kernel (redline)</li>
  <li>app -&gt; printf() -&gt; write() -&gt; SYSTEM CALL -&gt; sys_write() -&gt; …
user-level libraries are app’s private business</li>
  <li>kernel internal functions are not callable by user</li>
  <li>other way of drawing picture:</li>
  <li>syscall 1  -&gt; system call stub -&gt; kernel entry -&gt; syscall -&gt; fs</li>
  <li>syscall 2                                                 -&gt; proc</li>
  <li>system call stub executes special instruction to enter kernel
hardware switches to kernel mode
but only at an entry point specified by the kernel</li>
  <li>syscall need some way to get at arguments of syscall</li>
  <li>[syscalls the topic of this week’s lab]</li>
</ul>

<p>Kernel is the Trusted Computing Base (TCB)</p>

<ul>
  <li>Kernel must be “correct”
Bugs in kernel could allow user apps to circumvent kernel/user
Happens often in practice, because kernels are complex
See CVEs</li>
</ul>

<p>Kernel must treat user apps as suspect
User app may trick kernel to do the wrong thing
Kernel must check arguments carefully
Setup user/kernel correctly
Etc.
Kernel in charge of separating applications too
One app may try to read/write another app’s memory
=&gt; Requires a security mindset
Any bug in kernel may be a security exploit</p>

<p>Aside: can one have process isolation WITHOUT h/w-supported
kernel/user mode and virtual memory?</p>

<ul>
  <li>yes! use a strongly-typed programming language</li>
</ul>

<p>For example, see Singularity O/S
the compiler is then the trust computing base (TCB)
but h/w user/kernel mode is the most popular plan
Monolothic kernel
OS runs in kernel space
Xv6 does this.  Linux etc. too.
kernel interface == system call interface
one big program with file system, drivers, &amp;c
good: easy for subsystems to cooperate
one cache shared by file system and virtual memory
bad: interactions are complex
leads to bugs
no isolation within</p>

<p>Microkernel design</p>

<ul>
  <li>many OS services run as ordinary user programs
file system in a file server</li>
</ul>

<p>kernel implements minimal mechanism to run services in user space</p>
<ul>
  <li>processes with memory</li>
  <li>inter-process communication (IPC)</li>
</ul>

<p>kernel interface != system call interface</p>

<p>good: more isolation
bad: may be hard to get good performance
both monolithic and microkernel designs widely used</p>

<p>Xv6 case study</p>

<ul>
  <li>Monolithic kernel
Unix system calls == kernel interface</li>
</ul>

<p>Source code reflects OS organization (by convention)</p>
<ul>
  <li>user/    apps in user mode</li>
  <li>kernel/  code in kernel mode</li>
</ul>

<p>Kernel has several parts</p>
<ul>
  <li>kernel/defs.h
proc</li>
  <li>fs
..</li>
</ul>

<p>Goal: read source code and understand it (without consulting book)</p>

<p>The RISC-V computer</p>

<ul>
  <li>A very simple board (e.g., no display)</li>
</ul>

<p>RISC-V processor with 4 cores
RAM (128 MB)
support for interrupts (PLIC, CLINT)
support for UART
allows xv6 to talk to console
allows xv6 to read from keyboard
support for e1000 network card (through PCIe)
Qemu emulates several RISC-V computers
we use the “virt” one
<a href="https://github.com/riscv/riscv-qemu/wiki">https://github.com/riscv/riscv-qemu/wiki</a></p>

<p>close to the SiFive board (<a href="https://www.sifive.com/boards">https://www.sifive.com/boards</a>)
but with virtio for disk</p>

<p>Boot xv6 (under gdb)</p>

<ul>
  <li>$ make CPUS=1 qemu-gdb
runs xv6 under gdb (with 1 core)</li>
</ul>

<p>Qemu starts xv6 in kernel/entry.S (see kernel/kernel.ld)</p>
<ul>
  <li>set breakpoint at _entry
look at instruction</li>
  <li>info reg</li>
</ul>

<p>set breakpoint at main</p>
<ul>
  <li>Walk through main
single step into userinit
Walk through userinit
show kalloc
show proc.h
show allocproc()
show initcode.S/initcode.asm
break forkret()
walk to userret
break syscall
print num
syscalls[num]
exec “/init”
points to be made:
page table in userinit
ecall: U -&gt; K
a7: syscall #
exec: defensive</li>
</ul>

<p>kernel</p>

<p>\text{proc.c} \stackrel{\text{gcc}}{\rightarrow} \text{proc.s} \stackrel{\text{assembler}}{\rightarrow} \text{proc.o} \rightarrow\text{link different .o file together}</p>

<h2 id="6s081-2020-lecture-4-virtual-memory"><a href="#6-S081-2020-Lecture-4-Virtual-Memory"></a>6.S081 2020 Lecture 4: Virtual Memory</h2>

<p>========================================</p>

<ul>
  <li>plan:
address spaces
paging hardware
xv6 VM code</li>
</ul>

<h3 id="virtual-memory-overview"><a href="#Virtual-memory-overview"></a>Virtual memory overview</h3>

<ul>
  <li>today’s problem:
[user/kernel diagram]
[memory view: diagram with user processes and kernel in memory]
suppose the shell has a bug:
sometimes it writes to a random memory address
how can we keep it from wrecking the kernel?
and from wrecking other processes?</li>
  <li>we want isolated address spaces
each process has its own memory
it can read and write its own memory
it cannot read or write anything else
challenge:
how to multiplex several memories over one physical memory?
while maintaining isolation between memories</li>
  <li>xv6 uses RISC-V’s paging hardware to implement AS’s
ask questions! this material is important
topic of next lab (and shows up in several other labs)</li>
  <li></li>
</ul>

<p>paging provides a level of indirection for addressing
CPU -&gt; MMU -&gt; RAM
VA     PA</p>

\[\text{CPU}\stackrel{\text{VA}}{\rightarrow}MMU\stackrel{\text{PA}}{\rightarrow}\text{RAM}\]

<p>s/w can only ld/st to virtual addresses, not physical
kernel tells MMU how to map each virtual address to a physical address
MMU essentially has a table, indexed by va, yielding pa
called a “page table”
one page table per address space
MMU can restrict what virtual addresses user code can use
By programming the MMU, the kernel has complete control over va-&gt;pa mapping
Allows for many interesting OS features/tricks</p>

<ul>
  <li>RISC-V maps 4-KB “pages”
and aligned — start on 4 KB boundaries
4 KB = 12 bits
the RISC-V used in xv6 has 64-bit for addresses
thus page table index is top 64-12 = 52 bits of VA
except that the top 25 of the top 52 are unused
no RISC-V has that much memory now
can grow in future
so, index is 27 bits.</li>
  <li>MMU translation
see Figure 3.1 of book
use index bits of VA to find a page table entry (PTE)
construct physical address using PPN from PTE + offset of VA</li>
  <li>what is in PTE?
each PTE is 64 bits, but only 54 are used
top 44 bits of PTE are top bits of physical address
“physical page number”
low 10 bits of PTE flags
Present, Writeable, &amp;c
note: size virtual addresses != size physical addresses</li>
  <li>where is the page table stored?
in RAM — MMU loads (and stores) PTEs
o/s can read/write PTEs
read/write memory location corresponding to PTEs</li>
  <li>would it be reasonable for page table to just be an array of PTEs? how big is it?
2^27 is roughly 134 million
64 bits per entry
134*8 MB for a full page table
wasting roughly 1GB per page table
one page table per address space
one address space per application
would waste lots of memory for small programs!
you only need mappings for a few hundred pages
so the rest of the million entries would be there but not needed</li>
  <li>RISC-V 64 uses a “three-level page table” to save space
see figure 3.2 from book
page directory page (PD)
PD has 512 PTEs
PTEs point to another PD or is a leaf
so 512<em>512</em>512 PTEs in total
PD entries can be invalid
those PTE pages need not exist
so a page table for a small address space can be small</li>
  <li>how does the mmu know where the page table is located in RAM?
satp holds phys address of top PD
pages can be anywhere in RAM — need not be contiguous
rewrite satp when switching to another address space/application</li>
  <li>how does RISC-V paging hardware translate a va?
need to find the right PTE
satp register points to PA of top/L2 PD
top 9 bits index L2 PD to get PA of L1 PD
next 9 bits index L1 PD to get PA of L0 PD
next 9 bits index L0 PD to get PA of PTE
PPN from PTE + low-12 from VA</li>
  <li>flags in PTE
V, R, W, X, U
xv6 uses all of them</li>
  <li>what if V bit not set? or store and W bit not set?
“page fault”
forces transfer to kernel
trap.c in xv6 source
kernel can just produce error, kill process
in xv6: “usertrap(): unexpected scause … pid=… sepc=… stval=…”
or kernel can install a PTE, resume the process
e.g. after loading the page of memory from disk</li>
  <li>indirection allows paging h/w to solve many problems
e.g. phys memory doesn’t have to be contiguous
avoids fragmentation
e.g. lazy allocation (a lab)
e.g. copy-on-write fork (another lab)
many more techniques
topic of next lecture</li>
  <li></li>
</ul>

<p>Q: why use virtual memory in kernel?
it is clearly good to have page tables for user processes
but why have a page table for the kernel?
could the kernel run with using only physical addresses?
top-level answer: yes
most standard kernels do use virtual addresses
why do standard kernels do so?
some reasons are lame, some are better, none are fundamental</p>

<p>the hardware makes it difficult to turn it off
e.g. on entering a system call, one would have to disable VM</p>
<ul>
  <li>the kernel itself can benefit from virtual addresses
mark text pages X, but data not (helps tracking down bugs)
unmap a page below kernel stack (helps tracking down bugs)
map a page both in user and kernel (helps user/kernel transition)</li>
</ul>

<h3 id="virtual-memory-in-xv6"><a href="#Virtual-memory-in-xv6"></a>Virtual memory in xv6</h3>

<ul>
  <li>kernel page table
See figure 3.3 of book
simple maping mostly
map virtual to physical one-on-one
note double-mapping of trampoline
note permissions
why map devices?</li>
  <li>each process has its own address space
and its own page table
see figure 3.4 of book
note: trampoline and trapframe aren’t writable by user process
kernel switches page tables (i.e. sets satp) when switching processes</li>
  <li>Q: why this address space arrangement?
user virtual addresses start at zero
of course user va 0 maps to different pa for each process
16,777,216 GB for user heap to grow contiguously
but needn’t have contiguous phys mem — no fragmentation problem
both kernel and user map trampoline and trapframe page
eases transition user -&gt; kernel and back
kernel doesn’t map user applications
not easy for kernel to r/w user memory
need translate user virtual address to kernel virtual address
good for isolation (see spectre attacks)
easy for kernel to r/w physical memory
pa x mapped at va x</li>
  <li>Q: does the kernel have to map all of phys mem into its virtual address space?</li>
</ul>

<h3 id="code-walk-through"><a href="#Code-walk-through"></a>Code walk through</h3>

<ul>
  <li>setup of kernel address space
kvmmap()
Q: what is address 0x10000000 (256M)
Q: how much address space does 1 L2 entry cover? (1G)
Q: how much address space does 1 L1 entry cover? (2MB)
Q: how much address space does 1 L0 entry cover? (4096)
print kernel page table
Q: what is size of address space? (512G)
Q: how much memory is used to represent it after 1rst kvmmap()? (3 pages)
Q: how many entries is CLINT? (16 pages)
Q: how many entries is PLIC? (1024 pages, two level 1 PDs)
Q: how many pages is kernel text (8 pages)
Q: how many pages is kernel total (128M = 64 * 2MB)
Q: Is trampoline mapped twice? (yes, last entry and direct-mapped, entry [2, 3, 7])
kvminithart();
Q: after executing w_satp() why will the next instruction be sfence_vma()?</li>
  <li>mappages() in vm.c
arguments are top PD, va, size, pa, perm
adds mappings from a range of va’s to corresponding pa’s
rounds b/c some uses pass in non-page-aligned addresses
for each page-aligned address in the range
call walkpgdir to find address of PTE
need the PTE’s address (not just content) b/c we want to modify
put the desired pa into the PTE
mark PTE as valid w/ PTE_P</li>
  <li>walk() in vm.c
mimics how the paging h/w finds the PTE for an address
PX extracts the 9 bits at Level level
&amp;pagetable[PX(level, va)] is the address of the relevant PTE
if PTE_V
the relevant page-table page already exists
PTE2PA extracts the PPN from the PDE
if not PTE_V
alloc a page-table page
fill in pte with PPN (using PA2PTE)
now the PTE we want is in the page-table page</li>
  <li>procinit() in proc.c
alloc a page for each kernel stack with a guard page</li>
  <li>setup user address space
allocproc(): allocates empty top-level page table
fork(): uvmcopy()
exec(): replace proc’s page table with a new one
uvmalloc
loadseg
print user page table for sh
Q: what is entry 2?</li>
  <li>a process calls sbrk(n) to ask for n more bytes of heap memory
user/umalloc.c calls sbrk() to get memory for the allocator
each process has a size
kernel adds new memory at process’s end, increases size
sbrk() allocates physical memory (RAM)
maps it into the process’s page table
returns the starting address of the new memory</li>
  <li>growproc() in proc.c
proc-&gt;sz is the process’s current size
uvmalloc() does most of the work
when switching to user space satp will be loaded with updated page table</li>
  <li>uvmalloc() in vm.c
why PGROUNDUP?
arguments to mappages()…</li>
</ul>]]></content><author><name>York Cao</name></author><category term="blog" /><summary type="html"><![CDATA[Reading Chapter 1: Operating system interfaces]]></summary></entry></feed>