repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
ai-pr-reviewer
github_2023
typescript
5
coderabbitai
github-actions[bot]
@@ -117,17 +117,104 @@ export const codeReview = async ( if (files_to_review.length > 0) { const commenter: Commenter = new Commenter() - const [, review_begin_ids] = await bot.chat( - prompts.render_review_beginning(inputs), - {} - ) - let next_review_ids = review_begin_ids - + // Summary Stage const [, summarize_begin_ids] = await bot.chat( prompts.render_summarize_beginning(inputs), {} ) let next_summarize_ids = summarize_begin_ids + for (const [filename, file_content, file_diff] of files_to_review) { + inputs.filename = filename + inputs.file_content = file_content + inputs.file_diff = file_diff + if (file_diff.length > 0) { + // summarize diff + const [summarize_resp, summarize_diff_ids] = await bot.chat( + prompts.render_summarize_file_diff(inputs), + next_summarize_ids + ) + if (!summarize_resp) { + core.info('summarize: nothing obtained from chatgpt') + } else { + next_summarize_ids = summarize_diff_ids + } + } + } + // final summary + const [summarize_final_response, summarize_final_response_ids] = + await bot.chat(prompts.render_summarize(inputs), next_summarize_ids) + if (!summarize_final_response) { + core.info('summarize: nothing obtained from chatgpt') + } else { + inputs.summary = summarize_final_response + + next_summarize_ids = summarize_final_response_ids + const tag = + '<!-- This is an auto-generated comment: summarize by chatgpt -->' + await commenter.comment(`${summarize_final_response}`, tag, 'replace') + } + + // final release notes + const [release_notes_response, release_notes_ids] = await bot.chat( + prompts.render_summarize_release_notes(inputs), + next_summarize_ids + ) + if (!release_notes_response) { + core.info('release notes: nothing obtained from chatgpt') + } else { + next_summarize_ids = release_notes_ids + // add this response to the description field of the PR as release notes by looking + // for the tag (marker) + try { + const description = inputs.description + + // find the tag in the description and replace the content between the tag and the tag_end + // if not found, add the tag and the content to the end of the description + const tag_index = description.indexOf(description_tag) + const tag_end_index = description.indexOf(description_tag_end) + if (tag_index === -1 || tag_end_index === -1) { + let new_description = description + new_description += description_tag + new_description += '\n### Summary by ChatGPT\n' + new_description += release_notes_response + new_description += '\n' + new_description += description_tag_end + await octokit.pulls.update({ + owner: repo.owner, + repo: repo.repo, + pull_number: context.payload.pull_request.number, + body: new_description + }) + } else { + let new_description = description.substring(0, tag_index) + new_description += description_tag + new_description += '\n### Summary by ChatGPT\n' + new_description += release_notes_response + new_description += '\n' + new_description += description_tag_end + new_description += description.substring( + tag_end_index + description_tag_end.length + ) + await octokit.pulls.update({ + owner: repo.owner, + repo: repo.repo, + pull_number: context.payload.pull_request.number, + body: new_description + }) + } + } catch (e: any) { + core.warning( + `Failed to get PR: ${e}, skipping adding release notes to description.` + ) + } + } + + // Review Stage + const [, review_begin_ids] = await bot.chat( + prompts.render_review_beginning(inputs), + {} + ) + let next_review_ids = review_begin_ids for (const [ filename,
:robot: ChatGPT This patch adds a new feature to the code review process, which generates release notes and adds them to the PR description. The implementation looks good and well-structured. However, it would be better to add some error handling for the case when the tag is not found in the PR description. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
5
coderabbitai
github-actions[bot]
@@ -175,17 +262,6 @@ export const codeReview = async ( } else { next_review_ids = review_diff_ids } - - // summarize diff - const [summarize_resp, summarize_diff_ids] = await bot.chat( - prompts.render_summarize_file_diff(inputs), - next_summarize_ids - ) - if (!summarize_resp) { - core.info('summarize: nothing obtained from chatgpt') - } else { - next_summarize_ids = summarize_diff_ids - } } else { core.info( `skip sending diff of file: ${inputs.filename} due to token count: ${file_diff_tokens}`
:robot: ChatGPT This patch removes the code that summarizes the diff of each file. It seems like a reasonable decision to remove this feature, as it may not be necessary for every file and could potentially slow down the review process. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
5
coderabbitai
github-actions[bot]
@@ -232,76 +308,10 @@ export const codeReview = async ( } } } - // final summary - const [summarize_final_response, summarize_final_response_ids] = - await bot.chat(prompts.render_summarize(inputs), next_summarize_ids) - if (!summarize_final_response) { - core.info('summarize: nothing obtained from chatgpt') - } else { - next_summarize_ids = summarize_final_response_ids - const tag = - '<!-- This is an auto-generated comment: summarize by chatgpt -->' - await commenter.comment(`${summarize_final_response}`, tag, 'replace') - } - - // final release notes - const [release_notes_response, release_notes_ids] = await bot.chat( - prompts.render_summarize_release_notes(inputs), - next_summarize_ids - ) - if (!release_notes_response) { - core.info('release notes: nothing obtained from chatgpt') - } else { - next_summarize_ids = release_notes_ids - // add this response to the description field of the PR as release notes by looking - // for the tag (marker) - try { - const description = inputs.description - - // find the tag in the description and replace the content between the tag and the tag_end - // if not found, add the tag and the content to the end of the description - const tag_index = description.indexOf(description_tag) - const tag_end_index = description.indexOf(description_tag_end) - if (tag_index === -1 || tag_end_index === -1) { - let new_description = description - new_description += description_tag - new_description += '\n### Summary by ChatGPT\n' - new_description += release_notes_response - new_description += '\n' - new_description += description_tag_end - await octokit.pulls.update({ - owner: repo.owner, - repo: repo.repo, - pull_number: context.payload.pull_request.number, - body: new_description - }) - } else { - let new_description = description.substring(0, tag_index) - new_description += description_tag - new_description += '\n### Summary by ChatGPT\n' - new_description += release_notes_response - new_description += '\n' - new_description += description_tag_end - new_description += description.substring( - tag_end_index + description_tag_end.length - ) - await octokit.pulls.update({ - owner: repo.owner, - repo: repo.repo, - pull_number: context.payload.pull_request.number, - body: new_description - }) - } - } catch (e: any) { - core.warning( - `Failed to get PR: ${e}, skipping adding release notes to description.` - ) - } - } } } -// Write a function that takes diff for a single file as a string +// Write a function that takes diff for a single file as a string // and splits the diff into separate patches const split_patch = (patch: string | null | undefined): string[] => {
:robot: ChatGPT This patch removes the code that generates the final summary and release notes. It seems like a reasonable decision to remove this feature, as it may not be necessary for every review and could potentially slow down the review process. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
others
5
coderabbitai
github-actions[bot]
@@ -1,5 +1,7 @@ # ChatGPT based PR reviewer and summarizer +![AI](./docs/images/ai.png) + ## Overview This [ChatGPT](https://platform.openai.com/docs/guides/chat) based GitHub Action provides a summary, release notes and review of pull requests. The prompts have been tuned for concise response. To prevent excessive notifications, this action can be configured to skip adding review comments when the changes look good for the most part.
:robot: ChatGPT LGTM! The developer has added an AI image to the README, which is a nice touch. <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
others
5
coderabbitai
github-actions[bot]
@@ -173,7 +175,6 @@ Set `debug: true` in the workflow file to enable debug mode, which will show the ### Special Thanks -This GitHub Action is based on +This GitHub Action is based on [ChatGPT Action](https://github.com/unsafecoerce/chatgpt-pr-reviewer) by [Tao He](https://github.com/sighingnow).
:robot: ChatGPT LGTM! The removal of the extra line improves readability. <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
5
coderabbitai
github-actions[bot]
@@ -147,7 +153,7 @@ export class Options { review_comment_lgtm = false, path_filters: string[] | null = null, system_message = '', - temperature = '0.2' + temperature = '0.0' ) { this.debug = debug this.chatgpt_reverse_proxy = chatgpt_reverse_proxy
:robot: ChatGPT This patch modifies the `Options` class constructor to set the default temperature value to 0.0 instead of 0.2. It seems reasonable and does not introduce any new issues. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
5
coderabbitai
github-actions[bot]
@@ -212,7 +288,8 @@ export const codeReview = async ( continue } next_review_ids = patch_ids - if (!options.review_comment_lgtm && response.includes('LGTM')) { + // if the response contains LGTM (case insensitive), then skip commenting + if (!options.review_comment_lgtm && response.match(/lgtm/i)) { continue } try {
:robot: ChatGPT The patch improves the `codeReview` function by making it case-insensitive when checking for the "LGTM" response. This is a good improvement as it makes the code more robust and flexible. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
5
coderabbitai
github-actions[bot]
@@ -232,76 +309,10 @@ export const codeReview = async ( } } } - // final summary - const [summarize_final_response, summarize_final_response_ids] = - await bot.chat(prompts.render_summarize(inputs), next_summarize_ids) - if (!summarize_final_response) { - core.info('summarize: nothing obtained from chatgpt') - } else { - next_summarize_ids = summarize_final_response_ids - const tag = - '<!-- This is an auto-generated comment: summarize by chatgpt -->' - await commenter.comment(`${summarize_final_response}`, tag, 'replace') - } - - // final release notes - const [release_notes_response, release_notes_ids] = await bot.chat( - prompts.render_summarize_release_notes(inputs), - next_summarize_ids - ) - if (!release_notes_response) { - core.info('release notes: nothing obtained from chatgpt') - } else { - next_summarize_ids = release_notes_ids - // add this response to the description field of the PR as release notes by looking - // for the tag (marker) - try { - const description = inputs.description - - // find the tag in the description and replace the content between the tag and the tag_end - // if not found, add the tag and the content to the end of the description - const tag_index = description.indexOf(description_tag) - const tag_end_index = description.indexOf(description_tag_end) - if (tag_index === -1 || tag_end_index === -1) { - let new_description = description - new_description += description_tag - new_description += '\n### Summary by ChatGPT\n' - new_description += release_notes_response - new_description += '\n' - new_description += description_tag_end - await octokit.pulls.update({ - owner: repo.owner, - repo: repo.repo, - pull_number: context.payload.pull_request.number, - body: new_description - }) - } else { - let new_description = description.substring(0, tag_index) - new_description += description_tag - new_description += '\n### Summary by ChatGPT\n' - new_description += release_notes_response - new_description += '\n' - new_description += description_tag_end - new_description += description.substring( - tag_end_index + description_tag_end.length - ) - await octokit.pulls.update({ - owner: repo.owner, - repo: repo.repo, - pull_number: context.payload.pull_request.number, - body: new_description - }) - } - } catch (e: any) { - core.warning( - `Failed to get PR: ${e}, skipping adding release notes to description.` - ) - } - } } } -// Write a function that takes diff for a single file as a string +// Write a function that takes diff for a single file as a string // and splits the diff into separate patches const split_patch = (patch: string | null | undefined): string[] => {
:robot: ChatGPT The patch removes the `summarize_final_response` and `release_notes_response` functionality from the `codeReview` function. This is a good improvement as it reduces code duplication and makes the function more focused on its main purpose. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
others
5
coderabbitai
github-actions[bot]
@@ -26,4 +26,4 @@ jobs: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} with: debug: true - review_comment_lgtm: true + review_comment_lgtm: false
:robot: ChatGPT LGTM! This patch sets the `review_comment_lgtm` flag to false, which will prevent the bot from automatically commenting "LGTM" on pull requests. This seems like a reasonable change. <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
5
coderabbitai
github-actions[bot]
@@ -212,7 +288,8 @@ export const codeReview = async ( continue } next_review_ids = patch_ids - if (!options.review_comment_lgtm && response.includes('LGTM')) { + // if the response contains LGTM (case insensitive), then skip commenting + if (!options.review_comment_lgtm && response.match(/lgtm/i) !== null) { continue } try {
:robot: ChatGPT The code looks good. However, the regular expression used to match "LGTM" is case-insensitive, which may result in false positives if there are other words that contain "lgtm". Consider using a more specific regular expression or checking for an exact match of "LGTM". <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
others
6
coderabbitai
github-actions[bot]
@@ -26,4 +26,4 @@ jobs: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} with: debug: true - review_comment_lgtm: true + review_comment_lgtm: false
:robot: ChatGPT This patch changes the `review_comment_lgtm` flag from `true` to `false`. This means that the LGTM (Looks Good To Me) comment will not be automatically added to the pull request when the review is approved. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
others
6
coderabbitai
github-actions[bot]
@@ -1,5 +1,7 @@ # ChatGPT based PR reviewer and summarizer +![AI](./docs/images/ai.png) + ## Overview This [ChatGPT](https://platform.openai.com/docs/guides/chat) based GitHub Action provides a summary, release notes and review of pull requests. The prompts have been tuned for concise response. To prevent excessive notifications, this action can be configured to skip adding review comments when the changes look good for the most part.
:robot: ChatGPT This patch adds an AI image to the README.md file. No bug risk or improvement suggestion found. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
others
6
coderabbitai
github-actions[bot]
@@ -173,7 +175,6 @@ Set `debug: true` in the workflow file to enable debug mode, which will show the ### Special Thanks -This GitHub Action is based on +This GitHub Action is based on [ChatGPT Action](https://github.com/unsafecoerce/chatgpt-pr-reviewer) by [Tao He](https://github.com/sighingnow).
:robot: ChatGPT This patch removes an unnecessary line break. No bug risk or improvement suggestion found. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
6
coderabbitai
github-actions[bot]
@@ -75,6 +75,7 @@ export class Inputs { system_message: string title: string description: string + summary: string filename: string file_content: string file_diff: string
:robot: ChatGPT This patch modifies the `Inputs` class to add a new field called `summary`. This change looks good and acceptable. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
6
coderabbitai
github-actions[bot]
@@ -85,6 +86,7 @@ export class Inputs { system_message = '', title = '', description = '', + summary = '', filename = '', file_content = '', file_diff = '',
:robot: ChatGPT This patch modifies the constructor of the `Inputs` class to include the new `summary` field. This change looks good and acceptable. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
6
coderabbitai
github-actions[bot]
@@ -94,6 +96,7 @@ export class Inputs { this.system_message = system_message this.title = title this.description = description + this.summary = summary this.filename = filename this.file_content = file_content this.file_diff = file_diff
:robot: ChatGPT This patch modifies the constructor of the `Inputs` class to set the value of the new `summary` field. This change looks good and acceptable. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
6
coderabbitai
github-actions[bot]
@@ -114,6 +117,9 @@ export class Inputs { if (this.description) { content = content.replace('$description', this.description) } + if (this.summary) { + content = content.replace('$summary', this.summary) + } if (this.filename) { content = content.replace('$filename', this.filename) }
:robot: ChatGPT This patch modifies the `render` method of the `Inputs` class to handle the new `summary` field. This change looks good and acceptable. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
6
coderabbitai
github-actions[bot]
@@ -147,7 +153,7 @@ export class Options { review_comment_lgtm = false, path_filters: string[] | null = null, system_message = '', - temperature = '0.2' + temperature = '0.0' ) { this.debug = debug this.chatgpt_reverse_proxy = chatgpt_reverse_proxy
:robot: ChatGPT This patch modifies the `Options` class to set the default value of the `temperature` field to 0.0 instead of 0.2. This change looks good and acceptable. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
6
coderabbitai
github-actions[bot]
@@ -117,17 +117,104 @@ export const codeReview = async ( if (files_to_review.length > 0) { const commenter: Commenter = new Commenter() - const [, review_begin_ids] = await bot.chat( - prompts.render_review_beginning(inputs), - {} - ) - let next_review_ids = review_begin_ids - + // Summary Stage const [, summarize_begin_ids] = await bot.chat( prompts.render_summarize_beginning(inputs), {} ) let next_summarize_ids = summarize_begin_ids + for (const [filename, file_content, file_diff] of files_to_review) { + inputs.filename = filename + inputs.file_content = file_content + inputs.file_diff = file_diff + if (file_diff.length > 0) { + // summarize diff + const [summarize_resp, summarize_diff_ids] = await bot.chat( + prompts.render_summarize_file_diff(inputs), + next_summarize_ids + ) + if (!summarize_resp) { + core.info('summarize: nothing obtained from chatgpt') + } else { + next_summarize_ids = summarize_diff_ids + } + } + } + // final summary + const [summarize_final_response, summarize_final_response_ids] = + await bot.chat(prompts.render_summarize(inputs), next_summarize_ids) + if (!summarize_final_response) { + core.info('summarize: nothing obtained from chatgpt') + } else { + inputs.summary = summarize_final_response + + next_summarize_ids = summarize_final_response_ids + const tag = + '<!-- This is an auto-generated comment: summarize by chatgpt -->' + await commenter.comment(`${summarize_final_response}`, tag, 'replace') + } + + // final release notes + const [release_notes_response, release_notes_ids] = await bot.chat( + prompts.render_summarize_release_notes(inputs), + next_summarize_ids + ) + if (!release_notes_response) { + core.info('release notes: nothing obtained from chatgpt') + } else { + next_summarize_ids = release_notes_ids + // add this response to the description field of the PR as release notes by looking + // for the tag (marker) + try { + const description = inputs.description + + // find the tag in the description and replace the content between the tag and the tag_end + // if not found, add the tag and the content to the end of the description + const tag_index = description.indexOf(description_tag) + const tag_end_index = description.indexOf(description_tag_end) + if (tag_index === -1 || tag_end_index === -1) { + let new_description = description + new_description += description_tag + new_description += '\n### Summary by ChatGPT\n' + new_description += release_notes_response + new_description += '\n' + new_description += description_tag_end + await octokit.pulls.update({ + owner: repo.owner, + repo: repo.repo, + pull_number: context.payload.pull_request.number, + body: new_description + }) + } else { + let new_description = description.substring(0, tag_index) + new_description += description_tag + new_description += '\n### Summary by ChatGPT\n' + new_description += release_notes_response + new_description += '\n' + new_description += description_tag_end + new_description += description.substring( + tag_end_index + description_tag_end.length + ) + await octokit.pulls.update({ + owner: repo.owner, + repo: repo.repo, + pull_number: context.payload.pull_request.number, + body: new_description + }) + } + } catch (e: any) { + core.warning( + `Failed to get PR: ${e}, skipping adding release notes to description.` + ) + } + } + + // Review Stage + const [, review_begin_ids] = await bot.chat( + prompts.render_review_beginning(inputs), + {} + ) + let next_review_ids = review_begin_ids for (const [ filename,
:robot: ChatGPT This patch adds a new feature to summarize the diff and generate release notes using ChatGPT. The code looks good, but it would be better to add some error handling for the case when `inputs.description` is undefined. Also, it would be helpful to add some comments to explain the purpose of each section of the code. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
6
coderabbitai
github-actions[bot]
@@ -175,17 +262,6 @@ export const codeReview = async ( } else { next_review_ids = review_diff_ids } - - // summarize diff - const [summarize_resp, summarize_diff_ids] = await bot.chat( - prompts.render_summarize_file_diff(inputs), - next_summarize_ids - ) - if (!summarize_resp) { - core.info('summarize: nothing obtained from chatgpt') - } else { - next_summarize_ids = summarize_diff_ids - } } else { core.info( `skip sending diff of file: ${inputs.filename} due to token count: ${file_diff_tokens}`
:robot: ChatGPT This patch removes the code that summarizes the diff for each file. It seems like this is intentional and part of a larger change to move the diff summarization to a separate stage. The code looks good. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
6
coderabbitai
github-actions[bot]
@@ -232,76 +308,10 @@ export const codeReview = async ( } } } - // final summary - const [summarize_final_response, summarize_final_response_ids] = - await bot.chat(prompts.render_summarize(inputs), next_summarize_ids) - if (!summarize_final_response) { - core.info('summarize: nothing obtained from chatgpt') - } else { - next_summarize_ids = summarize_final_response_ids - const tag = - '<!-- This is an auto-generated comment: summarize by chatgpt -->' - await commenter.comment(`${summarize_final_response}`, tag, 'replace') - } - - // final release notes - const [release_notes_response, release_notes_ids] = await bot.chat( - prompts.render_summarize_release_notes(inputs), - next_summarize_ids - ) - if (!release_notes_response) { - core.info('release notes: nothing obtained from chatgpt') - } else { - next_summarize_ids = release_notes_ids - // add this response to the description field of the PR as release notes by looking - // for the tag (marker) - try { - const description = inputs.description - - // find the tag in the description and replace the content between the tag and the tag_end - // if not found, add the tag and the content to the end of the description - const tag_index = description.indexOf(description_tag) - const tag_end_index = description.indexOf(description_tag_end) - if (tag_index === -1 || tag_end_index === -1) { - let new_description = description - new_description += description_tag - new_description += '\n### Summary by ChatGPT\n' - new_description += release_notes_response - new_description += '\n' - new_description += description_tag_end - await octokit.pulls.update({ - owner: repo.owner, - repo: repo.repo, - pull_number: context.payload.pull_request.number, - body: new_description - }) - } else { - let new_description = description.substring(0, tag_index) - new_description += description_tag - new_description += '\n### Summary by ChatGPT\n' - new_description += release_notes_response - new_description += '\n' - new_description += description_tag_end - new_description += description.substring( - tag_end_index + description_tag_end.length - ) - await octokit.pulls.update({ - owner: repo.owner, - repo: repo.repo, - pull_number: context.payload.pull_request.number, - body: new_description - }) - } - } catch (e: any) { - core.warning( - `Failed to get PR: ${e}, skipping adding release notes to description.` - ) - } - } } } -// Write a function that takes diff for a single file as a string +// Write a function that takes diff for a single file as a string // and splits the diff into separate patches const split_patch = (patch: string | null | undefined): string[] => {
:robot: ChatGPT This patch removes the final summary and release notes generation code from the `codeReview` function. It seems like this is intentional and part of a larger change to move the diff summarization to a separate stage. The code looks good. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
javascript
4
coderabbitai
github-actions[bot]
@@ -26762,7 +26762,7 @@ var ChatGPTUnofficialProxyAPI = class { constructor(opts) { const { accessToken, - apiReverseProxyUrl = "https://chat.duti.tech/api/conversation", + apiReverseProxyUrl = "https://bypass.duti.tech/api/conversation", model = "text-davinci-002-render-sha", debug = false, headers,
:robot: ChatGPT LGTM! The change seems reasonable and does not introduce any new issues. <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
javascript
4
coderabbitai
github-actions[bot]
@@ -28663,15 +28663,17 @@ class Inputs { system_message; title; description; + summary; filename; file_content; file_diff; patch; diff; - constructor(system_message = '', title = '', description = '', filename = '', file_content = '', file_diff = '', patch = '', diff = '') { + constructor(system_message = '', title = '', description = '', summary = '', filename = '', file_content = '', file_diff = '', patch = '', diff = '') { this.system_message = system_message; this.title = title; this.description = description; + this.summary = summary; this.filename = filename; this.file_content = file_content; this.file_diff = file_diff;
:robot: ChatGPT LGTM! The addition of the `summary` field to the `Inputs` class seems reasonable and does not introduce any new issues. <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
javascript
4
coderabbitai
github-actions[bot]
@@ -28691,6 +28693,9 @@ class Inputs { if (this.description) { content = content.replace('$description', this.description); } + if (this.summary) { + content = content.replace('$summary', this.summary); + } if (this.filename) { content = content.replace('$filename', this.filename); }
:robot: ChatGPT LGTM! The addition of the `summary` field to the `Inputs` class and its replacement in the `content` string seems reasonable and does not introduce any new issues. <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
javascript
4
coderabbitai
github-actions[bot]
@@ -29093,10 +29098,87 @@ const codeReview = async (bot, options, prompts) => { } if (files_to_review.length > 0) { const commenter = new Commenter(); - const [, review_begin_ids] = await bot.chat(prompts.render_review_beginning(inputs), {}); - let next_review_ids = review_begin_ids; + // Summary Stage const [, summarize_begin_ids] = await bot.chat(prompts.render_summarize_beginning(inputs), {}); let next_summarize_ids = summarize_begin_ids; + for (const [filename, file_content, file_diff] of files_to_review) { + inputs.filename = filename; + inputs.file_content = file_content; + inputs.file_diff = file_diff; + if (file_diff.length > 0) { + // summarize diff + const [summarize_resp, summarize_diff_ids] = await bot.chat(prompts.render_summarize_file_diff(inputs), next_summarize_ids); + if (!summarize_resp) { + core.info('summarize: nothing obtained from chatgpt'); + } + else { + next_summarize_ids = summarize_diff_ids; + } + } + // final summary + const [summarize_final_response, summarize_final_response_ids] = await bot.chat(prompts.render_summarize(inputs), next_summarize_ids); + if (!summarize_final_response) { + core.info('summarize: nothing obtained from chatgpt'); + } + else { + inputs.summary = summarize_final_response; + next_summarize_ids = summarize_final_response_ids; + const tag = '<!-- This is an auto-generated comment: summarize by chatgpt -->'; + await commenter.comment(`${summarize_final_response}`, tag, 'replace'); + } + // final release notes + const [release_notes_response, release_notes_ids] = await bot.chat(prompts.render_summarize_release_notes(inputs), next_summarize_ids); + if (!release_notes_response) { + core.info('release notes: nothing obtained from chatgpt'); + } + else { + next_summarize_ids = release_notes_ids; + // add this response to the description field of the PR as release notes by looking + // for the tag (marker) + try { + const description = inputs.description; + // find the tag in the description and replace the content between the tag and the tag_end + // if not found, add the tag and the content to the end of the description + const tag_index = description.indexOf(description_tag); + const tag_end_index = description.indexOf(description_tag_end); + if (tag_index === -1 || tag_end_index === -1) { + let new_description = description; + new_description += description_tag; + new_description += '\n### Summary by ChatGPT\n'; + new_description += release_notes_response; + new_description += '\n'; + new_description += description_tag_end; + await review_octokit.pulls.update({ + owner: review_repo.owner, + repo: review_repo.repo, + pull_number: review_context.payload.pull_request.number, + body: new_description + }); + } + else { + let new_description = description.substring(0, tag_index); + new_description += description_tag; + new_description += '\n### Summary by ChatGPT\n'; + new_description += release_notes_response; + new_description += '\n'; + new_description += description_tag_end; + new_description += description.substring(tag_end_index + description_tag_end.length); + await review_octokit.pulls.update({ + owner: review_repo.owner, + repo: review_repo.repo, + pull_number: review_context.payload.pull_request.number, + body: new_description + }); + } + } + catch (e) { + core.warning(`Failed to get PR: ${e}, skipping adding release notes to description.`); + } + } + } + // Review Stage + const [, review_begin_ids] = await bot.chat(prompts.render_review_beginning(inputs), {}); + let next_review_ids = review_begin_ids; for (const [filename, file_content, file_diff, patches] of files_to_review) { inputs.filename = filename; inputs.file_content = file_content;
:robot: ChatGPT LGTM! The addition of the summary stage to `codeReview` function that summarizes each file's diff and generates release notes for the PR seems reasonable and does not introduce any new issues. <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
javascript
4
coderabbitai
github-actions[bot]
@@ -29130,14 +29212,6 @@ const codeReview = async (bot, options, prompts) => { else { next_review_ids = review_diff_ids; } - // summarize diff - const [summarize_resp, summarize_diff_ids] = await bot.chat(prompts.render_summarize_file_diff(inputs), next_summarize_ids); - if (!summarize_resp) { - core.info('summarize: nothing obtained from chatgpt'); - } - else { - next_summarize_ids = summarize_diff_ids; - } } else { core.info(`skip sending diff of file: ${inputs.filename} due to token count: ${file_diff_tokens}`);
:robot: ChatGPT Improvement Suggestion: It seems that the `summarize diff` stage is removed from the `codeReview` function. It might be useful to keep this stage to provide more detailed information about the changes made in each file. <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
javascript
4
coderabbitai
github-actions[bot]
@@ -29170,68 +29244,9 @@ const codeReview = async (bot, options, prompts) => { } } } - // final summary - const [summarize_final_response, summarize_final_response_ids] = await bot.chat(prompts.render_summarize(inputs), next_summarize_ids); - if (!summarize_final_response) { - core.info('summarize: nothing obtained from chatgpt'); - } - else { - next_summarize_ids = summarize_final_response_ids; - const tag = '<!-- This is an auto-generated comment: summarize by chatgpt -->'; - await commenter.comment(`${summarize_final_response}`, tag, 'replace'); - } - // final release notes - const [release_notes_response, release_notes_ids] = await bot.chat(prompts.render_summarize_release_notes(inputs), next_summarize_ids); - if (!release_notes_response) { - core.info('release notes: nothing obtained from chatgpt'); - } - else { - next_summarize_ids = release_notes_ids; - // add this response to the description field of the PR as release notes by looking - // for the tag (marker) - try { - const description = inputs.description; - // find the tag in the description and replace the content between the tag and the tag_end - // if not found, add the tag and the content to the end of the description - const tag_index = description.indexOf(description_tag); - const tag_end_index = description.indexOf(description_tag_end); - if (tag_index === -1 || tag_end_index === -1) { - let new_description = description; - new_description += description_tag; - new_description += '\n### Summary by ChatGPT\n'; - new_description += release_notes_response; - new_description += '\n'; - new_description += description_tag_end; - await review_octokit.pulls.update({ - owner: review_repo.owner, - repo: review_repo.repo, - pull_number: review_context.payload.pull_request.number, - body: new_description - }); - } - else { - let new_description = description.substring(0, tag_index); - new_description += description_tag; - new_description += '\n### Summary by ChatGPT\n'; - new_description += release_notes_response; - new_description += '\n'; - new_description += description_tag_end; - new_description += description.substring(tag_end_index + description_tag_end.length); - await review_octokit.pulls.update({ - owner: review_repo.owner, - repo: review_repo.repo, - pull_number: review_context.payload.pull_request.number, - body: new_description - }); - } - } - catch (e) { - core.warning(`Failed to get PR: ${e}, skipping adding release notes to description.`); - } - } } }; -// Write a function that takes diff for a single file as a string +// Write a function that takes diff for a single file as a string // and splits the diff into separate patches const split_patch = (patch) => { if (!patch) {
:robot: ChatGPT Improvement Suggestion: It seems that the final summary and release notes stages are removed from the `codeReview` function. It might be useful to keep these stages to provide a summary of all changes made in the PR and generate release notes for the PR. <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
others
4
coderabbitai
github-actions[bot]
@@ -26,4 +26,3 @@ jobs: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} with: debug: true
:robot: ChatGPT Patch review for `.github/workflows/chatgpt-review.yml`: The patch removes the `review_comment_lgtm` flag from the `with` section of the `chatgpt-review.yml` workflow file. This flag was previously used to automatically add an LGTM comment to pull requests that passed the review process. This change seems reasonable, as it is not necessary to have this flag in the workflow file anymore since a new stage has been added to summarize the changes made in the code review process and add them as release notes to the PR description. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
4
coderabbitai
github-actions[bot]
@@ -75,6 +75,7 @@ export class Inputs { system_message: string title: string description: string + summary: string filename: string file_content: string file_diff: string
:robot: ChatGPT This patch adds a new `summary` field to the `Inputs` class. The changes seem reasonable and necessary for the new stage that was added in this pull request. The addition of the `summary` field will allow the summary of changes made during the code review process to be included in the release notes of the PR description. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
4
coderabbitai
github-actions[bot]
@@ -85,6 +86,7 @@ export class Inputs { system_message = '', title = '', description = '', + summary = '', filename = '', file_content = '', file_diff = '',
:robot: ChatGPT This patch updates the constructor of the `Inputs` class to include the new `summary` field. The changes seem appropriate and necessary for the new stage that was added in this pull request. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
4
coderabbitai
github-actions[bot]
@@ -94,6 +96,7 @@ export class Inputs { this.system_message = system_message this.title = title this.description = description + this.summary = summary this.filename = filename this.file_content = file_content this.file_diff = file_diff
:robot: ChatGPT This patch updates the constructor of the `Inputs` class to set the new `summary` field. The changes seem appropriate and necessary for the new stage that was added in this pull request. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
4
coderabbitai
github-actions[bot]
@@ -114,6 +117,9 @@ export class Inputs { if (this.description) { content = content.replace('$description', this.description) } + if (this.summary) { + content = content.replace('$summary', this.summary) + } if (this.filename) { content = content.replace('$filename', this.filename) }
:robot: ChatGPT This patch updates the `render` function of the `Inputs` class to include the new `summary` field. The changes seem appropriate and necessary for the new stage that was added in this pull request. LGTM! <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
4
coderabbitai
github-actions[bot]
@@ -117,17 +117,104 @@ export const codeReview = async ( if (files_to_review.length > 0) { const commenter: Commenter = new Commenter() - const [, review_begin_ids] = await bot.chat( - prompts.render_review_beginning(inputs), - {} - ) - let next_review_ids = review_begin_ids - + // Summary Stage const [, summarize_begin_ids] = await bot.chat( prompts.render_summarize_beginning(inputs), {} ) let next_summarize_ids = summarize_begin_ids + for (const [filename, file_content, file_diff] of files_to_review) { + inputs.filename = filename + inputs.file_content = file_content + inputs.file_diff = file_diff + if (file_diff.length > 0) { + // summarize diff + const [summarize_resp, summarize_diff_ids] = await bot.chat( + prompts.render_summarize_file_diff(inputs), + next_summarize_ids + ) + if (!summarize_resp) { + core.info('summarize: nothing obtained from chatgpt') + } else { + next_summarize_ids = summarize_diff_ids + } + } + } + // final summary + const [summarize_final_response, summarize_final_response_ids] = + await bot.chat(prompts.render_summarize(inputs), next_summarize_ids) + if (!summarize_final_response) { + core.info('summarize: nothing obtained from chatgpt') + } else { + inputs.summary = summarize_final_response + + next_summarize_ids = summarize_final_response_ids + const tag = + '<!-- This is an auto-generated comment: summarize by chatgpt -->' + await commenter.comment(`${summarize_final_response}`, tag, 'replace') + } + + // final release notes + const [release_notes_response, release_notes_ids] = await bot.chat( + prompts.render_summarize_release_notes(inputs), + next_summarize_ids + ) + if (!release_notes_response) { + core.info('release notes: nothing obtained from chatgpt') + } else { + next_summarize_ids = release_notes_ids + // add this response to the description field of the PR as release notes by looking + // for the tag (marker) + try { + const description = inputs.description + + // find the tag in the description and replace the content between the tag and the tag_end + // if not found, add the tag and the content to the end of the description + const tag_index = description.indexOf(description_tag) + const tag_end_index = description.indexOf(description_tag_end) + if (tag_index === -1 || tag_end_index === -1) { + let new_description = description + new_description += description_tag + new_description += '\n### Summary by ChatGPT\n' + new_description += release_notes_response + new_description += '\n' + new_description += description_tag_end + await octokit.pulls.update({ + owner: repo.owner, + repo: repo.repo, + pull_number: context.payload.pull_request.number, + body: new_description + }) + } else { + let new_description = description.substring(0, tag_index) + new_description += description_tag + new_description += '\n### Summary by ChatGPT\n' + new_description += release_notes_response + new_description += '\n' + new_description += description_tag_end + new_description += description.substring( + tag_end_index + description_tag_end.length + ) + await octokit.pulls.update({ + owner: repo.owner, + repo: repo.repo, + pull_number: context.payload.pull_request.number, + body: new_description + }) + } + } catch (e: any) { + core.warning( + `Failed to get PR: ${e}, skipping adding release notes to description.` + ) + } + } + + // Review Stage + const [, review_begin_ids] = await bot.chat( + prompts.render_review_beginning(inputs), + {} + ) + let next_review_ids = review_begin_ids for (const [ filename,
:robot: ChatGPT The patch looks good. However, I suggest breaking down the `codeReview` function into smaller, more focused functions for easier testing and maintenance. Also, use destructuring assignment to simplify object access. Finally, add error handling for all async functions, especially those that interact with external APIs like GitHub and chatgpt. <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
4
coderabbitai
github-actions[bot]
@@ -175,17 +262,6 @@ export const codeReview = async ( } else { next_review_ids = review_diff_ids } - - // summarize diff - const [summarize_resp, summarize_diff_ids] = await bot.chat( - prompts.render_summarize_file_diff(inputs), - next_summarize_ids - ) - if (!summarize_resp) { - core.info('summarize: nothing obtained from chatgpt') - } else { - next_summarize_ids = summarize_diff_ids - } } else { core.info( `skip sending diff of file: ${inputs.filename} due to token count: ${file_diff_tokens}`
:robot: ChatGPT The patch looks good. However, I suggest adding a comment explaining why the `summarize_diff` step was removed. <!-- This is an auto-generated comment by ChatGPT -->
ai-pr-reviewer
github_2023
typescript
4
coderabbitai
github-actions[bot]
@@ -232,76 +308,10 @@ export const codeReview = async ( } } } - // final summary - const [summarize_final_response, summarize_final_response_ids] = - await bot.chat(prompts.render_summarize(inputs), next_summarize_ids) - if (!summarize_final_response) { - core.info('summarize: nothing obtained from chatgpt') - } else { - next_summarize_ids = summarize_final_response_ids - const tag = - '<!-- This is an auto-generated comment: summarize by chatgpt -->' - await commenter.comment(`${summarize_final_response}`, tag, 'replace') - } - - // final release notes - const [release_notes_response, release_notes_ids] = await bot.chat( - prompts.render_summarize_release_notes(inputs), - next_summarize_ids - ) - if (!release_notes_response) { - core.info('release notes: nothing obtained from chatgpt') - } else { - next_summarize_ids = release_notes_ids - // add this response to the description field of the PR as release notes by looking - // for the tag (marker) - try { - const description = inputs.description - - // find the tag in the description and replace the content between the tag and the tag_end - // if not found, add the tag and the content to the end of the description - const tag_index = description.indexOf(description_tag) - const tag_end_index = description.indexOf(description_tag_end) - if (tag_index === -1 || tag_end_index === -1) { - let new_description = description - new_description += description_tag - new_description += '\n### Summary by ChatGPT\n' - new_description += release_notes_response - new_description += '\n' - new_description += description_tag_end - await octokit.pulls.update({ - owner: repo.owner, - repo: repo.repo, - pull_number: context.payload.pull_request.number, - body: new_description - }) - } else { - let new_description = description.substring(0, tag_index) - new_description += description_tag - new_description += '\n### Summary by ChatGPT\n' - new_description += release_notes_response - new_description += '\n' - new_description += description_tag_end - new_description += description.substring( - tag_end_index + description_tag_end.length - ) - await octokit.pulls.update({ - owner: repo.owner, - repo: repo.repo, - pull_number: context.payload.pull_request.number, - body: new_description - }) - } - } catch (e: any) { - core.warning( - `Failed to get PR: ${e}, skipping adding release notes to description.` - ) - } - } } } -// Write a function that takes diff for a single file as a string +// Write a function that takes diff for a single file as a string // and splits the diff into separate patches const split_patch = (patch: string | null | undefined): string[] => {
:robot: ChatGPT The patch looks good. However, I suggest adding a comment explaining why the `summarize_final_response` and `release_notes_response` steps were removed. <!-- This is an auto-generated comment by ChatGPT -->
yakGPT
github_2023
typescript
63
yakGPT
yakGPT
@@ -16,34 +17,45 @@ export const startRecording = async (router: NextRouter) => { clearTimeout(get().recorderTimeout); const { apiKeyAzure, apiKeyAzureRegion } = get(); - let lastTextUpdate = ""; + let textUpdates: string[] = []; - const updateText = (text: string, persist: boolean) => { - // Remove previous text update - const textInputValue = get().textInputValue; - const cutText = textInputValue.substring( - 0, - textInputValue.length - lastTextUpdate.length - ); + const persistText = (text: string) => { + const effectiveInputValue = `${get().textInputValue} `; set((state) => ({ - textInputValue: `${cutText}${text}${persist ? " " : ""}`, + textInputValue: effectiveInputValue, }));
Ha, great catch, appears I completely overcomplicated this!
honox
github_2023
typescript
252
honojs
yusukebe
@@ -33,7 +33,7 @@ export const Script = (options: Options): any => { <script type='module' async={!!options.async} - src={`/${scriptInManifest.file}`} + src={`${import.meta.env.BASE_URL}${scriptInManifest.file}`}
Should we support without a trailing slash pattern? ```ts defineConfig({ base: '/subdir' // does not have a trailing slash }) ```
honox
github_2023
typescript
253
honojs
yusukebe
@@ -217,18 +217,18 @@ export function islandComponents(options?: IslandComponentsOptions): Plugin { root = config.root if (!reactApiImportSource) { - const tsConfigPath = path.resolve(process.cwd(), 'tsconfig.json') - const denoJsonPath = path.resolve(process.cwd(), 'deno.json') - let tsConfigRaw: string - try { - tsConfigRaw = await fs.readFile(denoJsonPath, 'utf8') - } catch (error1) { + const tsConfigFiles = ['deno.json', 'deno.jsonc', 'tsconfig.json'] + let tsConfigRaw: string | undefined + for (const tsConfigFile of tsConfigFiles) { try { + const tsConfigPath = path.resolve(process.cwd(), tsConfigFile) tsConfigRaw = await fs.readFile(tsConfigPath, 'utf8') - } catch (error2) { - console.warn('Cannot find neither tsconfig.json nor deno.json', error1, error2) - return - } + break + } catch {} + } + if (!tsConfigRaw) { + console.warn('Cannot find tsconfig.json or deno.json(c)')
I think this `console.warn()` is okay!
honox
github_2023
typescript
181
honojs
yusukebe
@@ -0,0 +1,38 @@ +import type { FC } from 'hono/jsx' +import type { Manifest } from 'vite' + +type Options = { manifest?: Manifest; prod: boolean } & JSX.IntrinsicElements['link']
Should `prod` be `prod?`?
honox
github_2023
typescript
176
honojs
usualoma
@@ -29,20 +29,22 @@ export type ClientOptions = { */ triggerHydration?: TriggerHydration ISLAND_FILES?: Record<string, () => Promise<unknown>> + /** + * @deprecated + */ island_root?: string } export const createClient = async (options?: ClientOptions) => { const FILES = options?.ISLAND_FILES ?? { - ...import.meta.glob('/app/islands/**/[a-zA-Z0-9[-]+.(tsx|ts)'), - ...import.meta.glob('/app/routes/**/_[a-zA-Z0-9[-]+.island.(tsx|ts)'), + ...import.meta.glob('/app/islands/**/[a-zA-Z0-9-]+.(tsx|ts)'), + ...import.meta.glob('/app/**/_[a-zA-Z0-9-]+.island.(tsx|ts)'), + ...import.meta.glob('/app/**/$[a-zA-Z0-9-]+.(tsx|ts)'),
It has nothing to do with this PR change, In `matchIslandComponentId()`, only `.tsx` matches (`.ts does not), so I think only `.tsx` should be used here as well. https://github.com/honojs/honox/pull/176/files#diff-4b7b8acce4bb320abe3a28d1bb85d7ad346253af647225df7e62d19891192a27R25
honox
github_2023
typescript
171
honojs
usualoma
@@ -52,6 +52,18 @@ function isComponentName(name: string) { return /^[A-Z][A-Z0-9]*[a-z][A-Za-z0-9]*$/.test(name) } +/** + * Matches when id is the filename of Island component + * + * @param id - The id to match + * @returns The result object if id is matched or null + */ +export function matchIslandComponentId(id: string) { + return id.match( + /(\/islands\/.+?\.tsx$)|(\/routes\/.*\_[a-zA-Z0-9[-]+\.island\.tsx$)|(\/routes.*\/\$[a-zA-Z0-9[-]+\.tsx$)/
Is it intended that there is no `/` under `routes` ? If not, I think it should be added. ```suggestion /(\/islands\/.+?\.tsx$)|(\/routes\/.*\_[a-zA-Z0-9[-]+\.island\.tsx$)|(\/routes\/.*\/\$[a-zA-Z0-9[-]+\.tsx$)/ ``` We might also want to take this opportunity to review our existing regular expressions as well. I think I can summarize as follows ```ts return id.match( /\/islands\/.+?\.tsx$|\/routes\/(?:.*\/)?(?:\_[a-zA-Z0-9-]+\.island\.tsx$|\$[a-zA-Z0-9-]+\.tsx$)/ ) ``` ![CleanShot 2024-05-09 at 05 48 45@2x](https://github.com/honojs/honox/assets/30598/cd38b69f-2ed5-452c-9d2a-0bc474d24cb0)
honox
github_2023
typescript
168
honojs
yusukebe
@@ -62,6 +63,11 @@ export const createApp = <E extends Env>(options: BaseServerOptions<E>): Hono<E> const app = options.app ?? new Hono() const trailingSlash = options.trailingSlash ?? false + // Share context by AsyncLocalStorage + app.use(async function ShareContext(c, next) {
This is cool! Only a few code can adapt `AsyncLocalStorage` to a Hono app.
honox
github_2023
typescript
163
honojs
yusukebe
@@ -29,27 +29,34 @@ import { memberExpression, importDeclaration, importSpecifier, + exportNamedDeclaration, + exportSpecifier, } from '@babel/types' import { parse as parseJsonc } from 'jsonc-parser' // eslint-disable-next-line node/no-extraneous-import import type { Plugin } from 'vite' -function addSSRCheck(funcName: string, componentName: string) { +function isComponentName(name: string) { + return /^[A-Z]/.test(name) && /[a-z]/.test(name)
I think the component name is `/^[A-Z][A-Za-z0-9]+/`. What do you think?
honox
github_2023
typescript
151
honojs
yusukebe
@@ -197,25 +197,46 @@ export type IslandComponentsOptions = { isIsland: IsIsland } +function getIslandComponentName( + root: string, + id: string, + options?: IslandComponentsOptions +): string | null { + const defaultIsIsland: IsIsland = (id) => { + const islandDirectoryPath = path.join(root, 'app') + return path.resolve(id).startsWith(islandDirectoryPath) + } + const matchIslandPath = options?.isIsland ?? defaultIsIsland + if (!matchIslandPath(id)) { + return null + } + const match = id.match(/(\/islands\/.+?\.tsx$)|(\/routes\/.*\_[a-zA-Z0-9[-]+\.island\.tsx$)/) + if (!match) { + return null + } + return match[0] +} + export function islandComponents(options?: IslandComponentsOptions): Plugin { let root = '' return { name: 'transform-island-components', + enforce: 'pre', configResolved: (config) => { root = config.root }, - async load(id) { - const defaultIsIsland: IsIsland = (id) => { - const islandDirectoryPath = path.join(root, 'app') - return path.resolve(id).startsWith(islandDirectoryPath) + async resolveId(source, importer) { + const resolution = await this.resolve(source, importer) + if (resolution && importer && getIslandComponentName(root, importer, options)) { + return `${resolution.id}?no-island`
I think `?not-island` or `?inside-island` is better than `?no-island`. How about you?
honox
github_2023
typescript
81
honojs
yusukebe
@@ -30,10 +30,80 @@ export default WrappedBadge;` `const AsyncComponentOriginal = async function () { return <h1>Hello</h1>; }; -const WrappedAsyncComponent = async function (props) { +const WrappedAsyncComponent = function (props) { return import.meta.env.SSR ? <honox-island component-name="AsyncComponent.tsx" data-serialized-props={JSON.stringify(Object.fromEntries(Object.entries(props).filter(([key]) => key !== "children")))}><AsyncComponentOriginal {...props}></AsyncComponentOriginal>{props.children ? <template data-hono-template="">{props.children}</template> : null}</honox-island> : <AsyncComponentOriginal {...props}></AsyncComponentOriginal>; }; export default WrappedAsyncComponent;` ) }) + + it('unnamed', () => { + const code = `export default async function() { + return <h1>Hello</h1> + }` + const result = transformJsxTags(code, 'UnnamedComponent.tsx') + expect(result).toBe( + `const __HonoIsladComponent__Original = async function () { + return <h1>Hello</h1>; +}; +const Wrapped__HonoIsladComponent__ = function (props) { + return import.meta.env.SSR ? <honox-island component-name="UnnamedComponent.tsx" data-serialized-props={JSON.stringify(Object.fromEntries(Object.entries(props).filter(([key]) => key !== "children")))}><__HonoIsladComponent__Original {...props}></__HonoIsladComponent__Original>{props.children ? <template data-hono-template="">{props.children}</template> : null}</honox-island> : <__HonoIsladComponent__Original {...props}></__HonoIsladComponent__Original>; +}; +export default Wrapped__HonoIsladComponent__;` + ) + }) + + it('arrow - block', () => { + const code = `export default () => { + return <h1>Hello</h1> + }` + const result = transformJsxTags(code, 'UnnamedComponent.tsx') + expect(result).toBe( + `const __HonoIsladComponent__Original = () => { + return <h1>Hello</h1>; +}; +const Wrapped__HonoIsladComponent__ = function (props) { + return import.meta.env.SSR ? <honox-island component-name="UnnamedComponent.tsx" data-serialized-props={JSON.stringify(Object.fromEntries(Object.entries(props).filter(([key]) => key !== "children")))}><__HonoIsladComponent__Original {...props}></__HonoIsladComponent__Original>{props.children ? <template data-hono-template="">{props.children}</template> : null}</honox-island> : <__HonoIsladComponent__Original {...props}></__HonoIsladComponent__Original>; +}; +export default Wrapped__HonoIsladComponent__;` + ) + }) + + it('arrow - expression', () => { + const code = 'export default () => <h1>Hello</h1>' + const result = transformJsxTags(code, 'UnnamedComponent.tsx') + expect(result).toBe( + `const __HonoIsladComponent__Original = () => <h1>Hello</h1>; +const Wrapped__HonoIsladComponent__ = function (props) { + return import.meta.env.SSR ? <honox-island component-name="UnnamedComponent.tsx" data-serialized-props={JSON.stringify(Object.fromEntries(Object.entries(props).filter(([key]) => key !== "children")))}><__HonoIsladComponent__Original {...props}></__HonoIsladComponent__Original>{props.children ? <template data-hono-template="">{props.children}</template> : null}</honox-island> : <__HonoIsladComponent__Original {...props}></__HonoIsladComponent__Original>; +}; +export default Wrapped__HonoIsladComponent__;` + ) + }) + + it('export via variable', () => { + const code = 'export default ExportViaVariable' + const result = transformJsxTags(code, 'ExportViaVariable.tsx') + expect(result).toBe( + `const WrappedExportViaVariable = function (props) { + return import.meta.env.SSR ? <honox-island component-name="ExportViaVariable.tsx" data-serialized-props={JSON.stringify(Object.fromEntries(Object.entries(props).filter(([key]) => key !== "children")))}><ExportViaVariable {...props}></ExportViaVariable>{props.children ? <template data-hono-template="">{props.children}</template> : null}</honox-island> : <ExportViaVariable {...props}></ExportViaVariable>; +}; +export default WrappedExportViaVariable;` + ) + }) + + it('export via specifier', () => { + const code = `const utilityFn = () => {}
It's good to test the utility function too!
honox
github_2023
others
67
honojs
yusukebe
@@ -466,6 +466,25 @@ export const POST = createRoute(zValidator('form', schema), async (c) => { }) ``` +Alternatively, you can use a `_middleware.(ts|tsx)` file in a directory to have that middleware applied to the current route, as well as all child routes. Middleware is ran in the order that it is listed within the array. + +An equivilant example to the previous Hono-style middleware configuration is as follows: + +```tsx +// /app/_middleware.tsx
I know it's a small detail, but wouldn't `/app/_middleware.ts` be better here?
cheriot-rtos
github_2023
cpp
468
CHERIoT-Platform
rmn30
@@ -863,22 +863,53 @@ __cheriot_minimum_stack(0x90) ssize_t return cap->quota; } -__cheriot_minimum_stack(0xd0) int heap_quarantine_empty() +__cheriot_minimum_stack(0xd0) int heap_quarantine_flush(Timeout *timeout) { STACK_CHECK(0xd0);
Aside: now that we have `__cheriot_minimum_stack__` can we introduce a variant of this macro that doesn't need repeat the stack size?
cheriot-rtos
github_2023
cpp
468
CHERIoT-Platform
rmn30
@@ -291,17 +291,36 @@ ssize_t __cheri_compartment("allocator") heap_quota_remaining(AllocatorCapability heapCapability); /** - * Block until the quarantine is empty. + * Try to empty the quarantine and defragment the heap. * - * This should be used only in testing, to place the system in a quiesced - * state. It can block indefinitely if another thread is allocating and - * freeing memory while this runs. + * This will start revocation sweep and then try to empty the quarantine. In
```suggestion * This will start a revocation sweep and then try to empty the quarantine. In ```
cheriot-rtos
github_2023
cpp
468
CHERIoT-Platform
rmn30
@@ -291,17 +291,36 @@ ssize_t __cheri_compartment("allocator") heap_quota_remaining(AllocatorCapability heapCapability); /** - * Block until the quarantine is empty. + * Try to empty the quarantine and defragment the heap. * - * This should be used only in testing, to place the system in a quiesced - * state. It can block indefinitely if another thread is allocating and - * freeing memory while this runs. + * This will start revocation sweep and then try to empty the quarantine. In + * normal operation, the allocator will remove a small number of allocations + * from quarantine on each allocation. Allocations are not coalesced until + * they are moved from quarantine, so this can cause fragmentation. If you + * have just freed a lot of memory (for example, after resetting a compartment + * and calling `heap_free_all`), especially if you have freed a lot of small + * allocations, then calling this function will reduce fragmentation. * * Returns 0 on success, a compartment invocation failure indication - * (-ENOTENOUGHSTACK, -ENOTENOUGHTRUSTEDSTACK) if it cannot be invoked, or - * possibly -ECOMPARTMENTFAIL if the allocator compartment is damaged. + * (`-ENOTENOUGHSTACK`, `-ENOTENOUGHTRUSTEDSTACK`) if it cannot be invoked, or + * possibly `-ECOMPARTMENTFAIL` if the allocator compartment is damaged. + * + * Returns `-ETIMEDOUT` if the timeout expires or `-EINVAL` if the timeout is + * not valid. + */ +__attribute__((overloadable)) int __cheri_compartment("allocator") + heap_quarantine_flush(Timeout *timeout); + +/** + * Compatibility implementation of `heap_quarantine_empty`. This should be + * used only in debugging and testing because it is not guaranteed to terminate + * if another thread is allocating memory. */ -int __cheri_compartment("allocator") heap_quarantine_empty(void); +static int heap_quarantine_empty(void)
Could mark this deprecated and add a new version called `heap_quarantine_flush_block_forever`? Hopefully that's a sufficiently scary name to discourage inappropriate use and also consistent with naming convention?
cheriot-rtos
github_2023
cpp
468
CHERIoT-Platform
nwf
@@ -863,22 +863,54 @@ __cheriot_minimum_stack(0x90) ssize_t return cap->quota; } -__cheriot_minimum_stack(0xd0) int heap_quarantine_empty() +__cheriot_minimum_stack(0xd0) int heap_quarantine_flush(Timeout *timeout) { STACK_CHECK(0xd0); - LockGuard g{lock}; - while (gm->heapQuarantineSize > 0) + + if (!check_timeout_pointer(timeout)) + { + return -EINVAL; + } + + if (LockGuard g{lock, timeout}) { - if (!gm->quarantine_dequeue()) + while (gm->heapQuarantineSize > 0) { - revoker.system_bg_revoker_kick(); + auto epoch = revoker.system_epoch_get(); + if (!gm->quarantine_dequeue())
This probably wants to be repeated, like `while (gm->quarantine_dequeue()) { ; }`, possibly with a notion of time elapsing, because there may be lots of (that is, more than 4) objects for us to remove from quarantine before we need to kick and wait for any revocation passes to take place. We should re-check `gm->heapQuarantineSize > 0` afterwards in case the entire quarantine was on the finished or (already-revoked) pending rings.
cheriot-rtos
github_2023
cpp
468
CHERIoT-Platform
rmn30
@@ -863,22 +863,54 @@ __cheriot_minimum_stack(0x90) ssize_t return cap->quota; } -__cheriot_minimum_stack(0xd0) int heap_quarantine_empty() +__cheriot_minimum_stack(0xd0) int heap_quarantine_flush(Timeout *timeout) { STACK_CHECK(0xd0); - LockGuard g{lock}; - while (gm->heapQuarantineSize > 0) + + if (!check_timeout_pointer(timeout)) + { + return -EINVAL; + } + + if (LockGuard g{lock, timeout}) { - if (!gm->quarantine_dequeue()) + while (gm->heapQuarantineSize > 0) { - revoker.system_bg_revoker_kick(); + auto epoch = revoker.system_epoch_get(); + if (!gm->quarantine_dequeue()) + { + revoker.system_bg_revoker_kick(); + } + if constexpr (Revocation::Revoker::IsAsynchronous) + { + wait_for_background_revoker(timeout, epoch, g); + } + else + { + (void)epoch; + // Drop and reacquire the lock while yielding.
This sequence could be extracted as a method on `LockGuard` so that this would become `if (!g.unlock_temporarily(timeout, 1)) return -ETIMEDOUT;`. Do we have other instances of this pattern?
cheriot-rtos
github_2023
cpp
468
CHERIoT-Platform
rmn30
@@ -305,27 +333,8 @@ namespace revoker.system_bg_revoker_kick(); - if constexpr (Revocation::Revoker::IsAsynchronous) - { - wait_for_background_revoker( - timeout, needsRevocation->waitingEpoch, g); - } - else - { - // Drop and reacquire the lock while yielding. - // Sleep for a single tick. - g.unlock(); - Timeout smallSleep{1}; - if (thread_sleep(&smallSleep) < 0) - { - /* Unable to sleep; bail out */ - return nullptr; - } - if (!reacquire_lock(timeout, g, smallSleep.elapsed)) - { - return nullptr; - } - } + wait_for_background_revoker(
Should this check the return value?
cheriot-rtos
github_2023
cpp
468
CHERIoT-Platform
nwf
@@ -291,17 +291,36 @@ ssize_t __cheri_compartment("allocator") heap_quota_remaining(AllocatorCapability heapCapability); /** - * Block until the quarantine is empty. + * Try to empty the quarantine and defragment the heap. * - * This should be used only in testing, to place the system in a quiesced - * state. It can block indefinitely if another thread is allocating and - * freeing memory while this runs. + * This will start a revocation sweep and then try to empty the quarantine. In + * normal operation, the allocator will remove a small number of allocations + * from quarantine on each allocation. Allocations are not coalesced until + * they are moved from quarantine, so this can cause fragmentation. If you + * have just freed a lot of memory (for example, after resetting a compartment + * and calling `heap_free_all`), especially if you have freed a lot of small + * allocations, then calling this function will reduce fragmentation.
I don't think it's a certainty? ```suggestion * allocations, then calling this function will likely reduce fragmentation. ```
cheriot-rtos
github_2023
cpp
468
CHERIoT-Platform
nwf
@@ -291,17 +291,42 @@ ssize_t __cheri_compartment("allocator") heap_quota_remaining(AllocatorCapability heapCapability); /** - * Block until the quarantine is empty. + * Try to empty the quarantine and defragment the heap. * - * This should be used only in testing, to place the system in a quiesced - * state. It can block indefinitely if another thread is allocating and - * freeing memory while this runs. + * This will start a revocation sweep and then try to empty the quarantine. In + * normal operation, the allocator will remove a small number of allocations + * from quarantine on each allocation. Allocations are not coalesced until + * they are moved from quarantine, so this can cause fragmentation. If you + * have just freed a lot of memory (for example, after resetting a compartment + * and calling `heap_free_all`), especially if you have freed a lot of small + * allocations, then calling this function will likely reduce fragmentation. + * + * Calling this function will ensure that all objects freed before the call are + * out of quarantine (unless a timeout occurs). Objects freed concurrently (by + * another thread) may remain in quarantine, so this does not guarantee that + * the quarantine is empty, only that everything freed by this thread is + * removed from quarantine. * * Returns 0 on success, a compartment invocation failure indication - * (-ENOTENOUGHSTACK, -ENOTENOUGHTRUSTEDSTACK) if it cannot be invoked, or - * possibly -ECOMPARTMENTFAIL if the allocator compartment is damaged. + * (`-ENOTENOUGHSTACK`, `-ENOTENOUGHTRUSTEDSTACK`) if it cannot be invoked, or + * possibly `-ECOMPARTMENTFAIL` if the allocator compartment is damaged. + * + * Returns `-ETIMEDOUT` if the timeout expires or `-EINVAL` if the timeout is + * not valid. */ -int __cheri_compartment("allocator") heap_quarantine_empty(void); +__attribute__((overloadable)) int __cheri_compartment("allocator") + heap_quarantine_flush(Timeout *timeout); + +/** + * Compatibility implementation of `heap_quarantine_empty`. This should be + * used only in debugging and testing because it is not guaranteed to terminate + * if another thread is allocating memory.
Since `heap_quarantine_flush` is now one-pass, this should also be guaranteed to terminate, now... or should it loop around `_flush`?
cheriot-rtos
github_2023
cpp
468
CHERIoT-Platform
nwf
@@ -216,20 +217,44 @@ namespace uint32_t epoch, LockGuard<decltype(lock)> &g, T &r = revoker) - requires(!Revocation::SupportsInterruptNotification<T>) + requires(!Revocation::SupportsInterruptNotification<T> && + Revocation::Revoker::IsAsynchronous) { // Yield while until a revocation pass has finished. while (!revoker.has_revocation_finished_for_epoch(epoch)) { // Release the lock before sleeping g.unlock(); Timeout smallSleep{1}; - if (thread_sleep(&smallSleep) < 0) + if ((thread_sleep(&smallSleep) < 0) || + !reacquire_lock(timeout, g, smallSleep.elapsed)) { return false; } - if (!reacquire_lock(timeout, g, smallSleep.elapsed)) + } + return true; + } + + template<typename T = Revocation::Revoker> + bool wait_for_background_revoker(Timeout *timeout,
At a glance, this implementation looks to be the same as the above?
cheriot-rtos
github_2023
cpp
476
CHERIoT-Platform
davidchisnall
@@ -104,7 +104,7 @@ namespace ds::pointer __always_inline Pointer<T> &operator=(Pointer const &p) { - ref = p.ref; + ref = (T *){p.ref};
Doesn't this trigger a clang-tidy warning about C-style casts?
cheriot-rtos
github_2023
others
250
CHERIoT-Platform
rmn30
@@ -223,6 +224,29 @@ For Ubuntu, you can do: # apt install xmake ``` +### Installing u2futils + +If you are working with Sonata, you will need to convert the ELF files that the linker produces to [USB Flashing Format (UF2)](https://github.com/microsoft/uf2) format.
```suggestion If you are working with Sonata, you will need to convert the ELF files that the linker produces to [USB Flashing Format (UF2)](https://github.com/microsoft/uf2). ```
cheriot-rtos
github_2023
others
250
CHERIoT-Platform
rmn30
@@ -352,3 +376,99 @@ issions are: Test runner: Global(0x0) ... ``` + +Running on Sonata +----------------- + +The Sonata board from lowRISC is an FPGA prototyping platform designed specifically to work with the CHERIoT Ibex. +If you have installed a [release of their system firmware](https://github.com/lowRISC/sonata-system/releases) that is at least v0.2, everything should be ready to work out of the box. + +### Building, Copying, and Running the Firmware + +The steps to build firmware are the same as for any other CHERIoT hardware, this time specifying `sonata` as the board. +Let's build the test suite again: + +``` +$ cd tests +$ xmake config --sdk=/cheriot-tools/ --board=sonata +$ xmake +``` + +Note that /cheriot-tools is the location in the dev container. +This value may vary if you did not use the dev container and must be the directory containing a bin directory with your LLVM build in it. + +### Running the firmware + +You can usually run firmware on Sonata simply with `xmake run`: + +``` +$ xmake run +[100%]: build ok, spent 4.52s +Converted to uf2, output size: 258048, start address: 0x101000 +Wrote 258048 bytes to test-suite.uf2 +Firmware copied to /Volumes//SONATA/ +``` + +If the last line instead says something like the following, one extra step is needed: + +``` +Please copy {some path}/cheriot-rtos/tests/build/cheriot/cheriot/release/firmware.uf2 to the SONATA drive to load. +``` + +If your SONATA board is connected, you should have a filesystem mounted called `SONATA` as a USB mass storage device. +You can copy the file mentioned in this line to the `SONATA` drive to run it. +The script that `xmake run` invokes looks in common mount locations for macOS and some Linux distributions to try to find the SONATA device. + +If you are running in the dev container, you are in an isolated environment with no access to this filesystem. +On most systems, you can add this as an explicit mount by adding the following to the [`devcontainer.json`](https://github.com/microsoft/cheriot-rtos/blob/main/.devcontainer/devcontainer.json) file: + +```json + "mounts": [ + "source={/your/SONATA/mount/point},target=/mnt/SONATA,type=bind" + ] +``` + +Replacing `{/your/SONATA/mount/point}` with the mount point of your `SONATA` filesystem. +Your editor should prompt to rebuild the container at this point. + +If you invoked the dev container directly, rather than via an editor such as VS Code, then you will need to instead add the following to your `docker run` command: + +``` +--mount source={/your/SONATA/mount/point},target=/mnt/SONATA,type=bind +``` + +Again, replacing `{/your/SONATA/mount/point}` with the real mount point. + +If you are on Windows, this will not work because Docker on Windows runs containers in a WSL2 VM and needs to have host filesystems mounted explicitly (Docker on macOS does this automatically). +In theory, the following steps should work (run in the WSL2 terminal in the Docker WSL2 VM): + +``` +sudo mkdir /mnt/d +sudo mount -t drvfs D: /mnt/d/ +``` + +Assuming that `SONATA` is mounted as `D:` on Windows. +The above commands should then work. +Unfortunately, they do not. +The cause of this is not currently known but will hopefully be fixed in a newer version of the Sonata RPi2040 firmware. + +### Seeing UART output + +If you ran the above `xmake run` commands, you will have noted that there is no output from the test suite. +When you use a simulator, the UART output goes directly to the simulator's standard output. +In contrast, when you run on an FPGA the output will go to a USB serial device. + +You will need to connect a terminal emulator to the corresponding serial port. +The Sonata system exposes *four* serial devices, typically numbered 0-3. +The UART is device 2. +On Linux, this is usually `/dev/ttyUSB2` (if no other USB serial devices are connected). +On macOS, the device name includes the serial number of the device and so will be something like `/dev/tty.usbserial-LN28292` (the last digit is the serial port number). +On Windows, it will be a COM port, but unfortunately Windows is not always consistent about the order in which the ports appear. + +If you install a serial terminal (for example, `minicom` on *NIX or PuTTY on Windows), you can point it at the relevant serial port. + +The serial setup is the same as for the Arty A7 [above](#installing-and-running-the-firmware), aside from the different device name. + +Once a serial terminal is connected, running `xmake run` should show the output from the test suite. + +If you are unsure which of Sonata's serial ports is the correct one, you can connect your serial console to all four and see which produces output from the test suite.
I don't think it's a good idea to connect to all of them at the same time. I think one might be the debugger and actually halts CPU or something. ```suggestion If you are unsure which of Sonata's serial ports is the correct one, you can connect your serial console to each of them in turn and see which produces output from the test suite. ```
cheriot-rtos
github_2023
others
235
CHERIoT-Platform
HU90m
@@ -0,0 +1,36 @@ +#!/bin/sh + +FIRMWARE_ELF=$1 + +SCRIPT_DIRECTORY="$(dirname "$(realpath "$0")")" +. ${SCRIPT_DIRECTORY}/includes/helper_find_llvm_install.sh + +OBJCOPY=$(find_llvm_tool_required llvm-objcopy) + +command -v uf2conv > /dev/null +if [ ! $? ] ; then + echo "uf2conv not found. On macOS / Linux systems with Python3 installed, you can install it with:" + echo "python3 -m pip install --pre -U git+https://github.com/makerdiary/uf2utils.git@main" +fi + +# Convert the ELF file to a binary file +${OBJCOPY} -O binary ${FIRMWARE_ELF} ${FIRMWARE_ELF}.bin +# Convert the binary to a UF2 (Microsoft USB Flashing Format) file +uf2conv ${FIRMWARE_ELF}.bin -b0x00101000 -co ${FIRMWARE_ELF}.uf2 + +# Try to copy the firmware to the SONATA drive, if we can find one. +try_copy() +{ + if [ -f $1/SONATA/OPTIONS.TXT ] ; then + cp ${FIRMWARE_ELF}.uf2 $1/SONATA/firmware.uf2 + echo "Firmware copied to $1/SONATA/" + exit + fi +} + +# Try some common mount points +try_copy /Volumes/ +try_copy /run/media/
```suggestion try_copy /run/media/$USER/ ```
cheriot-rtos
github_2023
others
235
CHERIoT-Platform
HU90m
@@ -0,0 +1,36 @@ +#!/bin/sh
```suggestion #!/usr/bin/env sh set -ue ``` Mainly care about `set -ue`, `env` is just a preference.
cheriot-rtos
github_2023
cpp
201
CHERIoT-Platform
rmn30
@@ -335,7 +336,13 @@ debug_log_message_write(const char *context, DebugPrinter printer; printer.write("\x1b[35m"); printer.write(context); +#if 0
Make make this a compile time option? ```suggestion #if defined(DEBUG_SHOW_THREAD_ID) ```
cheriot-rtos
github_2023
cpp
201
CHERIoT-Platform
rmn30
@@ -114,6 +116,11 @@ namespace return schedTStack; } + static bool any_ready() + { + return priorityMap != 0; + } + /** * When yielding inside the scheduler compartment, we almost always want
While you're here could you change this comment to fix #56 ?
cheriot-rtos
github_2023
cpp
201
CHERIoT-Platform
rmn30
@@ -28,34 +28,72 @@ namespace class Timer final : private TimerCore { + inline static uint64_t lastTickTime = 0; + inline static uint32_t accumulatedTickError = 0; + public: static void interrupt_setup() { static_assert(TIMERCYCLES_PER_TICK <= UINT32_MAX, "Cycles per tick can't be represented in 32 bits. " "Double check your platform config"); init(); - setnext(TIMERCYCLES_PER_TICK); } - static void do_interrupt() + using TimerCore::time; + + static void update() { - ++Thread::ticksSinceBoot; + auto *thread = Thread::current_get(); + bool waitingListIsEmpty = ((Thread::waitingList == nullptr) || + (Thread::waitingList->expiryTime == -1)); + bool threadHasNoPeers = + (thread == nullptr) || (!thread->has_priority_peers()); + if (waitingListIsEmpty && threadHasNoPeers) + { + clear(); + } + else + { + uint64_t nextTimer = waitingListIsEmpty + ? time() + TIMERCYCLES_PER_TICK + : Thread::waitingList->expiryTime; + setnext(nextTimer); + } + } - expiretimers(); - setnext(TIMERCYCLES_PER_TICK); + static uint64_t update_tick() + { + uint64_t now = time(); + uint32_t elapsed = now - lastTickTime; + int32_t error = elapsed % TIMERCYCLES_PER_TICK;
This is worthy of some comment. I think it is calculating error by assuming elapsed should be a multiples of TIMERCYCLES_PER_TICK and, if less than a tick has elapsed, it rounds up by one?
cheriot-rtos
github_2023
cpp
201
CHERIoT-Platform
nwf-msr
@@ -26,36 +26,81 @@ namespace IsTimer<TimerCore>, "Platform's timer implementation does not meet the required interface"); + /** + * Timer interface. Provides generic timer functionality to the scheduler, + * wrapping the platform's timer device. + */ class Timer final : private TimerCore { + inline static uint64_t lastTickTime = 0; + inline static uint64_t zeroTickTime = 0; + inline static uint32_t accumulatedTickError = 0; + public: + /** + * Perform any setup necessary for the timer device. + */ static void interrupt_setup() { static_assert(TIMERCYCLES_PER_TICK <= UINT32_MAX, "Cycles per tick can't be represented in 32 bits. " "Double check your platform config"); init(); - setnext(TIMERCYCLES_PER_TICK); + zeroTickTime = time(); } - static void do_interrupt() - { - ++Thread::ticksSinceBoot; + /** + * Expose the timer device's method for returning the current time. + */ + using TimerCore::time; - expiretimers(); - setnext(TIMERCYCLES_PER_TICK); + /** + * Update the timer to fire the next timeout for the thread at the + * front of the queue, or disable the timer if there are no threads + * blocked with a timeout.
Expand comment to match code and maybe write something to make those of us stuck in the 1980s feel better about clearing the timer? Something like... "... no threads blocked with a timeout and no priority-peers of the current thread such that we'd need to timeslice the CPU. The timer can be re-enabled if this single thread blocks with a timeout or if either this thread or an interrupt wakes another currently blocked in indefinite sleep."
cheriot-rtos
github_2023
others
201
CHERIoT-Platform
nwf-msr
@@ -970,7 +970,13 @@ __Z13thread_id_getv: // Load the trusted stack pointer into a register that we will clobber in // the next instruction when we load the thread ID. cspecialr ca0, mtdc + //cgettag a1, ca0 + // If this is a null pointer, don't try to dereference it and report that + // we are thread 0. This permits the debug code to work even from things + // that are not real threads. + //beqz a1, .Lend
Do you want this to be commented out?
cheriot-rtos
github_2023
cpp
201
CHERIoT-Platform
nwf-msr
@@ -55,7 +55,7 @@ static inline BaseType_t xTaskCheckForTimeOut(TimeOut_t *pxTimeOut, static inline void vTaskDelay(const TickType_t xTicksToDelay) { struct Timeout timeout = {0, xTicksToDelay}; - thread_sleep(&timeout); + thread_sleep(&timeout, 0);
I don't think that's the semantics of `vTaskDelay`. https://www.freertos.org/a00127.html makes it sound like it's supposed to guarantee that time elapses.
cheriot-rtos
github_2023
cpp
201
CHERIoT-Platform
nwf-msr
@@ -72,6 +117,39 @@ namespace break; } } + if (!Thread::any_ready()) + { + for (Thread *iter = Thread::waitingList; iter;)
I think I'd prefer two `waitingList`-s, one for time elapsing and one for yielding, so that we wouldn't have to do this kind of two-pass rummaging and discrimination. I suppose with our thread counts it doesn't hugely matter, but still.
cheriot-rtos
github_2023
cpp
201
CHERIoT-Platform
nwf-msr
@@ -72,6 +117,39 @@ namespace break; } } + if (!Thread::any_ready()) + { + for (Thread *iter = Thread::waitingList; iter;) + { + if (iter->is_yielding()) + { + Debug::log("Woke thread {} {} cycles early", + iter->id_get(), + int64_t(iter->expiryTime) - now); + Thread *iterNext = iter->timerNext; + iter->ready(Thread::WakeReason::Timer); + iter = iterNext; + if (Thread::waitingList == nullptr || + iter == Thread::waitingList) + { + break; + } + } + else + { + break;
I don't think that's right; I think you want to keep scanning the queue for the first yielding thread, not bail if the head of the queue isn't yielding.
cheriot-rtos
github_2023
others
201
CHERIoT-Platform
nwf-msr
@@ -38,6 +38,21 @@ class StandardClint : private utils::NoCopyNoMove 2 * sizeof(uint32_t)); } + static uint64_t time() + { + /// the low 32 bits
Eh?
cheriot-rtos
github_2023
cpp
201
CHERIoT-Platform
nwf-msr
@@ -23,6 +23,17 @@ typedef struct [[cheri::interrupt_state(disabled)]] SystickReturn __cheri_compartment("sched") thread_systemtick_get(void); +enum ThreadSleepFlags : uint32_t +{ + /** + * Sleep for up to the specified timeout, but wake early if there are no + * other runnable threads. This allows a high-priority thread to yield for
```suggestion * other threads runnable or blocked with earlier timeouts. * This allows a high-priority thread to yield for ``` I'm trying to capture the difference between "wake as soon as the system idles within the next N ticks" (which would be the "traverse the waiting queue until we found a yielding thread" behavior) and "wake as soon as the system looks like it might be idle N ticks from now" (the "only test the head of the waiting queue for yielding" behavior now implemented).
cheriot-rtos
github_2023
cpp
201
CHERIoT-Platform
nwf-msr
@@ -419,14 +435,17 @@ SystickReturn __cheri_compartment("sched") thread_systemtick_get() } __cheriot_minimum_stack(0x80) int __cheri_compartment("sched") - thread_sleep(Timeout *timeout) + thread_sleep(Timeout *timeout, uint32_t flags) { STACK_CHECK(0x80); if (!check_timeout_pointer(timeout)) { return -EINVAL; } - Thread::current_get()->suspend(timeout, nullptr, true); + ////Debug::log("Thread {} sleeping for {} ticks", + /// Thread::current_get()->id_get(), timeout->remaining);
Nit: could you `ifdef 0` this or cut down the number of slashes so that it doesn't look like a doxygen-style comment?
cheriot-rtos
github_2023
cpp
201
CHERIoT-Platform
nwf-msr
@@ -616,7 +647,12 @@ namespace uint8_t priority; /// The original priority level for this thread. This never changes. const uint8_t OriginalPriority; - ThreadState state; + ThreadState state : 2; + /** + * If the thread is yielding, it may be scheduled before its timeout + * expires, as long as no other threads are runnable.
I might leave off the "as long as..." part here and just point at the docs for `ThreadSleepNoEarlyWake` or the comment down in the actual wake code.
cheriot-rtos
github_2023
cpp
201
CHERIoT-Platform
nwf-msr
@@ -26,36 +26,96 @@ namespace IsTimer<TimerCore>, "Platform's timer implementation does not meet the required interface"); + /** + * Timer interface. Provides generic timer functionality to the scheduler, + * wrapping the platform's timer device. + */ class Timer final : private TimerCore { + inline static uint64_t lastTickTime = 0; + inline static uint64_t zeroTickTime = 0; + inline static uint32_t accumulatedTickError = 0; + public: + /** + * Perform any setup necessary for the timer device. + */ static void interrupt_setup() { static_assert(TIMERCYCLES_PER_TICK <= UINT32_MAX, "Cycles per tick can't be represented in 32 bits. " "Double check your platform config"); init(); - setnext(TIMERCYCLES_PER_TICK); + zeroTickTime = time(); } - static void do_interrupt() - { - ++Thread::ticksSinceBoot; + /** + * Expose the timer device's method for returning the current time. + */ + using TimerCore::time; - expiretimers(); - setnext(TIMERCYCLES_PER_TICK); + /** + * Update the timer to fire the next timeout for the thread at the + * front of the queue, or disable the timer if there are no threads + * blocked with a timeout and no threads with the same priority. + * + * The scheduler is a simple RTOS scheduler that does not allow any + * thread to run if a higher-priority thread is runnable. This means + * that we need a timer interrupt in one of two situations: + * + * - We have a thread of the same priority as the current thread and + * we are going to round-robin schedule it. + * - We have a thread of a higher priority than the current thread + * that is currently sleeping on a timeout and need it to preempt the + * current thread when its timeout expires. + * + * We currently over approximate the second condition by making the + * timer fire independent of the priority. If this is every changed, + * some care must be taken to ensure that dynamic priority propagation + * via priority-inheriting futexes behaves correctly. + * + * This should be called after scheduling has changed the list of + * waiting threads. + */ + static void update() + { + auto *thread = Thread::current_get(); + bool waitingListIsEmpty = ((Thread::waitingList == nullptr) || + (Thread::waitingList->expiryTime == -1)); + bool threadHasNoPeers = + (thread == nullptr) || (!thread->has_priority_peers()); + if (waitingListIsEmpty && threadHasNoPeers) + { + clear(); + } + else + { + uint64_t nextTimer = waitingListIsEmpty + ? time() + TIMERCYCLES_PER_TICK + : Thread::waitingList->expiryTime; + setnext(nextTimer); + } } - private: + /** + * Wake any threads that were sleeping until a timeout before the + * current time. This also wakes yielded threads if there are no + * runnable threads.
```suggestion * threads runnable or sleeping with earlier timeouts. ```
cheriot-rtos
github_2023
cpp
201
CHERIoT-Platform
rmn30
@@ -26,36 +26,96 @@ namespace IsTimer<TimerCore>, "Platform's timer implementation does not meet the required interface"); + /** + * Timer interface. Provides generic timer functionality to the scheduler, + * wrapping the platform's timer device. + */ class Timer final : private TimerCore { + inline static uint64_t lastTickTime = 0; + inline static uint64_t zeroTickTime = 0; + inline static uint32_t accumulatedTickError = 0; + public: + /** + * Perform any setup necessary for the timer device. + */ static void interrupt_setup() { static_assert(TIMERCYCLES_PER_TICK <= UINT32_MAX, "Cycles per tick can't be represented in 32 bits. " "Double check your platform config"); init(); - setnext(TIMERCYCLES_PER_TICK); + zeroTickTime = time(); } - static void do_interrupt() - { - ++Thread::ticksSinceBoot; + /** + * Expose the timer device's method for returning the current time. + */ + using TimerCore::time; - expiretimers(); - setnext(TIMERCYCLES_PER_TICK); + /** + * Update the timer to fire the next timeout for the thread at the + * front of the queue, or disable the timer if there are no threads + * blocked with a timeout and no threads with the same priority. + * + * The scheduler is a simple RTOS scheduler that does not allow any + * thread to run if a higher-priority thread is runnable. This means + * that we need a timer interrupt in one of two situations: + * + * - We have a thread of the same priority as the current thread and + * we are going to round-robin schedule it. + * - We have a thread of a higher priority than the current thread + * that is currently sleeping on a timeout and need it to preempt the + * current thread when its timeout expires. + * + * We currently over approximate the second condition by making the + * timer fire independent of the priority. If this is every changed, + * some care must be taken to ensure that dynamic priority propagation + * via priority-inheriting futexes behaves correctly. + * + * This should be called after scheduling has changed the list of + * waiting threads. + */ + static void update() + { + auto *thread = Thread::current_get(); + bool waitingListIsEmpty = ((Thread::waitingList == nullptr) || + (Thread::waitingList->expiryTime == -1)); + bool threadHasNoPeers = + (thread == nullptr) || (!thread->has_priority_peers()); + if (waitingListIsEmpty && threadHasNoPeers) + { + clear(); + } + else + { + uint64_t nextTimer = waitingListIsEmpty
@davidchisnall if the waiting list is non-empty *and* the current thread has peers I think this will set the timer for the next expiry time. Doesn't that mean the current thread could get more than one quantum?
cheriot-rtos
github_2023
others
225
CHERIoT-Platform
rmn30
@@ -352,7 +315,19 @@ struct DebugFormatArgumentAdaptor<CHERI::PermissionSet> construct(CHERI::PermissionSet value) { return {static_cast<uintptr_t>(value.as_raw()), - DebugFormatArgument::PermissionSet}; + DebugFormatArgumentKind::DebugFormatArgumentPermissionSet}; + } +}; + +/** + * Null pointer specialisation. + */ +template<> +struct DebugFormatArgumentAdaptor<std::nullptr_t>
Curious why this is required?
cheriot-rtos
github_2023
cpp
225
CHERIoT-Platform
rmn30
@@ -0,0 +1,138 @@ +#pragma once +#include <__debug.h> +#include <__macro_map.h> + +#ifndef __cplusplus + +/** + * Helper macro to convert the type of an argument to the corresponding + * `DebugFormatArgument` value. + * + * Should not be used directly. + */ +# define CHERIOT_DEBUG_MAP_ARGUMENT(x) \
Maybe prefix with `_` or something to discourage direct use?
cheriot-rtos
github_2023
others
226
CHERIoT-Platform
rmn30
@@ -13,9 +13,6 @@ .p2align 2 .type start,@function start: - cjal .Lregs_clear - // The common register clearing function will not zero these registers. - zeroRegisters ra, sp, gp, a0 // At this point all registers are cleared.
```suggestion // HW should have initialised all general purpose registers to NULL // but we don't rely on that. Most will be cleared below before jumping to loader. ```
cheriot-rtos
github_2023
cpp
311
CHERIoT-Platform
sleffler
@@ -61,23 +61,41 @@ using _Bool = bool; #define __section(x) __attribute__((section(x))) #define __alloc_size(x) __attribute__((alloc_size(x))) #define __alloc_align(x) __attribute__((alloc_align(x))) -#define __cheri_callback __attribute__((cheri_ccallback)) #if __has_attribute(cheriot_minimum_stack) # define __cheriot_minimum_stack(x) __attribute__((cheriot_minimum_stack(x))) #else # warning \ "cheriot_minimum_stack attribute not supported, please update your compiler" # define __cheriot_minimum_stack(x) #endif + // When running clang-tidy, we use the same compile flags for everything and so // will get errors about things being defined in the wrong compartment, so // define away the compartment name and pretend everything is local for now. -#ifdef CLANG_TIDY +#if defined(CLANG_TIDY) || defined(__CHERIOT_BAREMETAL__) # define __cheri_compartment(x) #else # define __cheri_compartment(x) __attribute__((cheri_compartment(x))) #endif -#define __cheri_libcall __attribute__((cheri_libcall)) + +// Define the CHERIoT calling-convention attributes macros to nothing if we're +// targeting bare metal and to the correct attributes if we're targeting the +// RTOS. +#ifdef __CHERIOT_BAREMETAL__
<pre>__CHERIOT_BAREMETAL__</pre> or <pre>_CHERIOT_BAREMETAL_</pre> (I originally used the latter)
cheriot-rtos
github_2023
others
185
CHERIoT-Platform
rmn30
@@ -27,3 +27,99 @@ This is the kind of isolation that device drivers typically provide in operating Note in addition that we've added one more attribute to the function exposed here: `[[cheri::interrupt_state(disabled)]]`. This means that the uart compartment will write the entire string to the UART, so two different threads writing to it will not interfere. This is not ideal for something like a `write` function, which can take a caller-controlled amount of time to complete, because it prevents any other thread from making progress, even ones that don't touch the uart. + +## Validating the compartmentalisation model + +The goal of this refactoring was to ensure that only the `uart` compartment has access to the UART device. +How do we know if we achieved that? +This is where the [cheriot-audit](https://github.com/CHERIoT-Platform/cheriot-audit) tool comes in. +If you're using the dev container, this is installed in `/cheriot-tools/bin/`, if you've built it somewhere else then replace `/cheriot-tools/bin/` with the correct path. + +First, let's use it to see which compartments or libraries have access to the UART: + +``` +$ /cheriot-tools/bin/cheriot-audit -b ../../sdk/boards/sail.json -j build/cheriot/cheriot/release/hello_compartment.json -q 'data.compartment.compartments_with_mmio_import(data.board.devices.uart)' +["debug", "scheduler"] +``` + +This uses `-b` to find the board description file and `-j` the report that the linker generated during the build. +This tells us that the `debug` library and the `scheduler` compartment both have direct access to the UART. +The latter is an artefact of how some simulators exit: simulation builds will have the UART exposed to the scheduler. + +Note that our `uart` compartment isn't on this list. +It accesses the UART via the `debug` library. +This means that, in addition to the compartments and libraries that have direct access to the UART, we need to determine which compartments have access to the `debug` library. +Let's run that as another query: + +``` +$ /cheriot-tools/bin/cheriot-audit -b ../../sdk/boards/sail.json -j build/cheriot/cheriot/release/hello_compartment.json -q 'data.compartment.compartments_calling("debug")' +["uart"] +``` + +Great! +Our compartmentalisation goal has been achieved! + +Note that it was *not* in the first version of this example (ooops!). +The `fail-simulator-on-error.h` header adds an error handler that writes debug messages via direct access to the UART. +This was difficult to spot manually, but would show up in auditing easily. +Try uncommenting this line in `hello.cc`: + +```c++ +//#include <fail-simulator-on-error.h> +``` + +Rerunning the above query should now show the following output: + +```json +["hello", "uart"] +``` + +Now that we have something that is correct, we'd like to make sure that it *remains* correct. +We do this by writing a Rego module that encapsulates out policy.
```suggestion We do this by writing a Rego module that encapsulates our policy. ```
cheriot-rtos
github_2023
others
185
CHERIoT-Platform
rmn30
@@ -27,3 +27,99 @@ This is the kind of isolation that device drivers typically provide in operating Note in addition that we've added one more attribute to the function exposed here: `[[cheri::interrupt_state(disabled)]]`. This means that the uart compartment will write the entire string to the UART, so two different threads writing to it will not interfere. This is not ideal for something like a `write` function, which can take a caller-controlled amount of time to complete, because it prevents any other thread from making progress, even ones that don't touch the uart. + +## Validating the compartmentalisation model + +The goal of this refactoring was to ensure that only the `uart` compartment has access to the UART device. +How do we know if we achieved that? +This is where the [cheriot-audit](https://github.com/CHERIoT-Platform/cheriot-audit) tool comes in. +If you're using the dev container, this is installed in `/cheriot-tools/bin/`, if you've built it somewhere else then replace `/cheriot-tools/bin/` with the correct path. + +First, let's use it to see which compartments or libraries have access to the UART: + +``` +$ /cheriot-tools/bin/cheriot-audit -b ../../sdk/boards/sail.json -j build/cheriot/cheriot/release/hello_compartment.json -q 'data.compartment.compartments_with_mmio_import(data.board.devices.uart)' +["debug", "scheduler"] +``` + +This uses `-b` to find the board description file and `-j` the report that the linker generated during the build.
```suggestion This uses `-b` to find the board description file and `-j` the report that the linker generated during the build. The query passed with `-q` asks which compartments or libraries import the UART's MMIO capability. ```
cheriot-rtos
github_2023
cpp
174
CHERIoT-Platform
nwf-msr
@@ -289,7 +289,13 @@ namespace displacement_proxy struct __packed __aligned(MallocAlignment) MChunkHeader { - static constexpr size_t OwnerIDWidth = 14; + /** + * Each chunk has a 16-bit metadata field that is used to store a small + * bitfield and the owner ID in the remaining bits. This is the space not + * consumed by the metadata. It must be reduced if additional bits are + * stolen for other fields. + */ + static constexpr size_t OwnerIDWidth = 13;
For a follow-up PR, perhaps: do we ever actually check that the `uint16_t` owner IDs we're passing around fit in this width? Maybe just in debug builds?
cheriot-rtos
github_2023
cpp
174
CHERIoT-Platform
nwf-msr
@@ -301,8 +307,15 @@ MChunkHeader /// The unique identifier of the allocator. uint16_t ownerID : OwnerIDWidth; - bool isPrevInUse : 1; - bool isCurrInUse : 1; + /** + * Is this a sealed object? If so, it should be exempted from free in + * `heap_free_all` because deallocation requires consensus between the + * holder of the allocator capability and the holder of the sealing + * capability. + */
Probably also worth a quick comment that this, like `isCurrInUse`, effectively is a _type tag_ on the body of the chunk, indicating that it is a `struct SObjStruct`. By that token, it'd be good explicitly zero the bit in `mspace_free` (or maybe `quarantine_pending_push`) and to teach the `ok_free_chunk` consistency test that `isSealedObject` must be `0` (because we can't have both a `struct SObjStruct` and a `MChunk` or `TChunk` in the chunk body). (At the moment, the bit is ignored through the entire quarantine/free/coalesce part of heap bytes' lifetimes, and will be set or cleared when a header is allocated.)
cheriot-rtos
github_2023
c
162
CHERIoT-Platform
nwf-msr
@@ -88,3 +88,9 @@ void *__cheri_libcall memset(void *dst0, int c0, size_t length) } while (--t != 0); return (dst0); } + +void __cheri_libcall explicit_bzero(void *s, size_t n) +{ + memset(s, 0, n);
Does this result in an extra call/return within the library?
cheriot-rtos
github_2023
others
161
CHERIoT-Platform
nwf-msr
@@ -0,0 +1,65 @@ +#pragma once +#include "compartment-macros.h" +#include <platform/concepts/entropy.h> +#include <ds/xoroshiro.h> +#include <riscvreg.h> +#include <interrupt.h> +#include <fail-simulator-on-error.h> + +DECLARE_AND_DEFINE_INTERRUPT_CAPABILITY( + RevokerInterruptEntropy, InterruptName::EthernetReceiveInterrupt, true, false) + + +/** + * A simple entropy source. This wraps a few weak entropy sources to seed a + * PRNG. It is absolutely not secure and should not be used for anything that + * depends on cryptographically secure random numbers! Unfortunately, there is + * nothing on the Arty A7 instantiation of CHERIoT SAFE that can be used as a + * secure entropy source. + */ +class EntropySource +{ + ds::xoroshiro::P128R64 prng; + const uint32_t *ethernetInterruptCount; + public: + + using ValueType = uint64_t; + + /// Definitely not secure! + static constexpr bool IsSecure = false; + + /// Constructor, tries to generate an independent sequence of random numbers + EntropySource() + { + ethernetInterruptCount = interrupt_futex_get(STATIC_SEALED_VALUE(RevokerInterruptEntropy)); + reseed(); + } + + /// Reseed the PRNG + void reseed() + { + // Start from a not very random seed + uint64_t seed = rdcycle64(); + prng.set_state(seed, seed >> 24); + uint32_t interrupts = *ethernetInterruptCount; + // Permute it with another not-very-random number + for (uint32_t i = 0 ; i<((interrupts & 0xff) >> 8); i++)
I am pretty sure you didn't mean `(interrupts & 0xff) >> 8`. ```suggestion for (uint32_t i = 0 ; i<((interrupts & 0xff00) >> 8); i++) ```
cheriot-rtos
github_2023
cpp
161
CHERIoT-Platform
nwf-msr
@@ -85,7 +142,15 @@ namespace ds::xoroshiro * * Parameters from https://prng.di.unimi.it/xoroshiro128plus.c . */ - using P128R64 = detail::XorOshiro<uint64_t, uint64_t, 24, 16, 37>; + using P128R64 = detail::XorOshiro<uint64_t, + uint64_t, + 24, + 16, + 37, + 0xdf900294d8f554a5, + 0x170865df4b3201fc, + 0xd2a98b26625eee7b, + 0xdddf9b1090aa7ac1>;
"Let's see... types, small numbers... omg". I trust that those are the right big numbers.
cheriot-rtos
github_2023
cpp
161
CHERIoT-Platform
nwf-msr
@@ -0,0 +1,36 @@ +#pragma once +#include <array> +#include <concepts> +#include <cstdint> + +/** + * Concept for an Ethernet adaptor. + */ +template<typename T> +concept IsEntropySource = requires(T source) +{ + /** + * Must export a flag indicating whether this is a cryptographically + * secure random number. + */ + { + T::IsSecure + } -> std::convertible_to<const bool>; + + /** + * Must return a random number. All bits of the value type are assumed to + * be random, this should use a narrower type if it guarantees less + * entropy.
Requiring distillation in the application-facing source is probably fine, but I'm not sure it's worth it if one starts stacking/pooling sources a la Fortuna.
cheriot-rtos
github_2023
others
161
CHERIoT-Platform
nwf-msr
@@ -0,0 +1,65 @@ +#pragma once +#include "compartment-macros.h" +#include <platform/concepts/entropy.h> +#include <ds/xoroshiro.h> +#include <riscvreg.h> +#include <interrupt.h> +#include <fail-simulator-on-error.h> + +DECLARE_AND_DEFINE_INTERRUPT_CAPABILITY( + RevokerInterruptEntropy, InterruptName::EthernetReceiveInterrupt, true, false) + + +/** + * A simple entropy source. This wraps a few weak entropy sources to seed a + * PRNG. It is absolutely not secure and should not be used for anything that + * depends on cryptographically secure random numbers! Unfortunately, there is + * nothing on the Arty A7 instantiation of CHERIoT SAFE that can be used as a + * secure entropy source.
Huh! That's kind of surprising. Maybe something like https://dl.acm.org/doi/10.1145/3610295 is worth adding to the FPGA image? But either way, this looks fine for testing and demo purposes.
cheriot-rtos
github_2023
cpp
155
CHERIoT-Platform
nwf-msr
@@ -53,34 +178,272 @@ xSemaphoreCreateCounting(UBaseType_t uxMaxCount, UBaseType_t uxInitialCount) } /** - * Delete a heap-allocated semaphore. + * Create a heap-allocated binary semaphore. + * + * Binary semaphores are implemented as counting semaphores with a maximum count + * of 1. + */ +__always_inline static inline SemaphoreHandle_t xSemaphoreCreateBinary() +{ + return xSemaphoreCreateCounting(1, 0); +} + +/** + * Create a statically allocated binary semaphore. + * + * Binary semaphores are implemented as counting semaphores with a maximum count + * of 1. + */ +__always_inline static inline SemaphoreHandle_t +xSemaphoreCreateBinaryStatic(StaticSemaphore_t *pxSemaphoreBuffer) +{ + return xSemaphoreCreateCountingStatic(1, 0, pxSemaphoreBuffer); +} +#endif + +#if CHERIOT_FREERTOS_MUTEX +/** + * Create statically allocated mutex. + */ +__always_inline static inline SemaphoreHandle_t +xSemaphoreCreateMutexStatic(StaticSemaphore_t *pxMutexBuffer) +{ + pxMutexBuffer->mutex.lockWord = 0; + CHERIOT_FREERTOS_SEMAPHORE_KIND_SET(pxMutexBuffer, CheriotFreeRTOS_Mutex); + return pxMutexBuffer; +} + +/** + * Create a heap-allocated mutex. + */ +__always_inline static inline SemaphoreHandle_t xSemaphoreCreateMutex() +{ + SemaphoreHandle_t semaphore = + (SemaphoreHandle_t)malloc(sizeof(SemaphoreHandle_t)); + if (semaphore != NULL) + { + xSemaphoreCreateMutexStatic(semaphore); + } + return semaphore; +} +#endif + +#if CHERIOT_FREERTOS_RECURSIVE_MUTEX + +/** + * Create a statically allocated recursive mutex. + */ +__always_inline static inline SemaphoreHandle_t +xSemaphoreCreateRecursiveMutexStatic(StaticSemaphore_t *pxMutexBuffer) +{ + pxMutexBuffer->recursiveMutex.lock.lockWord = 0; + pxMutexBuffer->recursiveMutex.depth = 0; + CHERIOT_FREERTOS_SEMAPHORE_KIND_SET(pxMutexBuffer, + CheriotFreeRTOS_RecursiveMutex); + return pxMutexBuffer; +} + +/** + * Create a heap-allocated recursive mutex. + */ +__always_inline static inline SemaphoreHandle_t +xSemaphoreCreateRecursiveMutex(void) +{ + SemaphoreHandle_t semaphore = + (SemaphoreHandle_t)malloc(sizeof(SemaphoreHandle_t)); + if (semaphore != NULL) + { + xSemaphoreCreateRecursiveMutexStatic(semaphore); + } + return semaphore; +} +#endif + +/** + * Delete a heap-allocated semaphore, of any kind. + * + * Note: As on FreeRTOS, if there are waiters blocked on this semaphore then + * they will remain blocked until their timeout (if ever). */ __always_inline static inline void vSemaphoreDelete(SemaphoreHandle_t xSemaphore) { free(xSemaphore); } +/** + * Get the current owner (thread ID) of a mutex. If this is a counting + * semaphore, or if the lock is not held, returns zero. + */ +__always_inline static inline TaskHandle_t +xSemaphoreGetMutexHolder(SemaphoreHandle_t xMutex) +{ + CHERIOT_FREERTOS_SEMAPHORE_SWITCH(xMutex) + { + CHERIOT_FREERTOS_SEMAPHORE_CASE(return 0;) + CHERIOT_FREERTOS_RECURSIVE_MUTEX_CASE( + return xMutex->recursiveMutex.lock.lockWord & 0xffff;) + CHERIOT_FREERTOS_MUTEX_CASE(return xMutex->mutex.lockWord & 0xffff;) + } + return 0; +} + +/** + * Returns the current count of a counting semaphore, or whether a mutex or + * binary semaphore is available + * + * Note: This API is inherently racy. Unless run with interrupts disabled, + * there is no guarantee that the value returned is still valid by the time the + * caller inspects it. + */ +static inline UBaseType_t uxSemaphoreGetCount(SemaphoreHandle_t xSemaphore) +{ + CHERIOT_FREERTOS_SEMAPHORE_SWITCH(xSemaphore) + { + CHERIOT_FREERTOS_SEMAPHORE_CASE(return xSemaphore->semaphore.count;) + CHERIOT_FREERTOS_RECURSIVE_MUTEX_CASE( + return xSemaphore->recursiveMutex.lock.lockWord != 0;) + CHERIOT_FREERTOS_MUTEX_CASE(return xSemaphore->mutex.lockWord != 0;) + } + return 0; +} + /** * A semaphore get (down) operation. If the semaphore value is zero, this can * block for up to `xTicksToWait` ticks. Returns true if the semaphore was * obtained, false if the timeout expired. */ -__always_inline static inline _Bool xSemaphoreTake(SemaphoreHandle_t xSemaphore, - TickType_t xTicksToWait) +static inline _Bool xSemaphoreTake(SemaphoreHandle_t xSemaphore, + TickType_t xTicksToWait) { Timeout t = {0, xTicksToWait}; - int ret = semaphore_get(&t, xSemaphore); + int ret = -1; + CHERIOT_FREERTOS_SEMAPHORE_SWITCH(xSemaphore) + { + CHERIOT_FREERTOS_SEMAPHORE_CASE( + ret = semaphore_get(&t, &xSemaphore->semaphore);) + CHERIOT_FREERTOS_MUTEX_CASE( + ret = flaglock_priority_inheriting_trylock(&t, &xSemaphore->mutex);) + // Recursive mutexes are not supposed to use this interface. + CHERIOT_FREERTOS_RECURSIVE_MUTEX_CASE(;); + } return ret == 0; } +/** + * Take a semaphore from code that may run in an ISR. CHERIoT RTOS does not + * permit code to run in ISRs and so this simply calls the normal code paths. + * + * The second parameter is a pointer to a variable that will be set to true if + * the caller needs to yield to wake a higher-priority task.
Not yet supported?
cheriot-rtos
github_2023
cpp
155
CHERIoT-Platform
nwf-msr
@@ -53,34 +178,272 @@ xSemaphoreCreateCounting(UBaseType_t uxMaxCount, UBaseType_t uxInitialCount) } /** - * Delete a heap-allocated semaphore. + * Create a heap-allocated binary semaphore. + * + * Binary semaphores are implemented as counting semaphores with a maximum count + * of 1. + */ +__always_inline static inline SemaphoreHandle_t xSemaphoreCreateBinary() +{ + return xSemaphoreCreateCounting(1, 0); +} + +/** + * Create a statically allocated binary semaphore. + * + * Binary semaphores are implemented as counting semaphores with a maximum count + * of 1. + */ +__always_inline static inline SemaphoreHandle_t +xSemaphoreCreateBinaryStatic(StaticSemaphore_t *pxSemaphoreBuffer) +{ + return xSemaphoreCreateCountingStatic(1, 0, pxSemaphoreBuffer); +} +#endif + +#if CHERIOT_FREERTOS_MUTEX +/** + * Create statically allocated mutex. + */ +__always_inline static inline SemaphoreHandle_t +xSemaphoreCreateMutexStatic(StaticSemaphore_t *pxMutexBuffer) +{ + pxMutexBuffer->mutex.lockWord = 0; + CHERIOT_FREERTOS_SEMAPHORE_KIND_SET(pxMutexBuffer, CheriotFreeRTOS_Mutex); + return pxMutexBuffer; +} + +/** + * Create a heap-allocated mutex. + */ +__always_inline static inline SemaphoreHandle_t xSemaphoreCreateMutex() +{ + SemaphoreHandle_t semaphore = + (SemaphoreHandle_t)malloc(sizeof(SemaphoreHandle_t)); + if (semaphore != NULL) + { + xSemaphoreCreateMutexStatic(semaphore); + } + return semaphore; +} +#endif + +#if CHERIOT_FREERTOS_RECURSIVE_MUTEX + +/** + * Create a statically allocated recursive mutex. + */ +__always_inline static inline SemaphoreHandle_t +xSemaphoreCreateRecursiveMutexStatic(StaticSemaphore_t *pxMutexBuffer) +{ + pxMutexBuffer->recursiveMutex.lock.lockWord = 0; + pxMutexBuffer->recursiveMutex.depth = 0; + CHERIOT_FREERTOS_SEMAPHORE_KIND_SET(pxMutexBuffer, + CheriotFreeRTOS_RecursiveMutex); + return pxMutexBuffer; +} + +/** + * Create a heap-allocated recursive mutex. + */ +__always_inline static inline SemaphoreHandle_t +xSemaphoreCreateRecursiveMutex(void) +{ + SemaphoreHandle_t semaphore = + (SemaphoreHandle_t)malloc(sizeof(SemaphoreHandle_t)); + if (semaphore != NULL) + { + xSemaphoreCreateRecursiveMutexStatic(semaphore); + } + return semaphore; +} +#endif + +/** + * Delete a heap-allocated semaphore, of any kind. + * + * Note: As on FreeRTOS, if there are waiters blocked on this semaphore then + * they will remain blocked until their timeout (if ever). */ __always_inline static inline void vSemaphoreDelete(SemaphoreHandle_t xSemaphore) { free(xSemaphore); } +/** + * Get the current owner (thread ID) of a mutex. If this is a counting + * semaphore, or if the lock is not held, returns zero.
This probably deserves the same comment about racing as below, with the (anti)caveat that an answer of "this thread" _is_ stable.
cheriot-rtos
github_2023
cpp
155
CHERIoT-Platform
nwf-msr
@@ -44,7 +169,7 @@ __always_inline static inline SemaphoreHandle_t xSemaphoreCreateCounting(UBaseType_t uxMaxCount, UBaseType_t uxInitialCount) { SemaphoreHandle_t semaphore = - (SemaphoreHandle_t)malloc(sizeof(struct CountingSemaphoreState)); + (SemaphoreHandle_t)malloc(sizeof(SemaphoreHandle_t));
Do you really mean `sizeof(SemaphoreHandle_t)`? ```suggestion (SemaphoreHandle_t)malloc(sizeof(StaticSemaphore_t)); ```
cheriot-rtos
github_2023
cpp
155
CHERIoT-Platform
nwf-msr
@@ -1,18 +1,141 @@ #pragma once +/** + * FreeRTOS semaphore compatibility layer. This maps FreeRTOS semaphore types + * to their CHERIoT RTOS equivalents. + * + * There is some overhead from dynamic dispatch that can be avoided if only one + * of the FreeRTOS semaphore types needs to be supported in a particular + * component. You can enable individual semaphore types by defining the + * following macros: + * + * - `CHERIOT_EXPOSE_FREERTOS_SEMAPHORE`: Enable counting and binary semaphores. + * - `CHERIOT_EXPOSE_FREERTOS_MUTEX`: Enable non-recursive, priority-inheriting + * mutexes. + * - `CHERIOT_EXPOSE_FREERTOS_RECURSIVE_MUTEX`: Enable recursive mutexes. + */ #include "FreeRTOS.h" #include <locks.h> #include <stdatomic.h> +#if !defined(CHERIOT_EXPOSE_FREERTOS_SEMAPHORE) && \ + !defined(CHERIOT_EXPOSE_FREERTOS_MUTEX) && \ + !defined(CHERIOT_EXPOSE_FREERTOS_RECURSIVE_MUTEX) +# error At least one out of CHERIOT_EXPOSE_FREERTOS_SEMAPHORE, \ + CHERIOT_EXPOSE_FREERTOS_MUTEX, or CHERIOT_EXPOSE_FREERTOS_RECURSIVE_MUTEX \ + must be defined. +#endif + +#ifdef CHERIOT_EXPOSE_FREERTOS_SEMAPHORE +# define CHERIOT_FREERTOS_SEMAPHORE 1
While I don't object to these `EXPOSE`-less `define`s, are they doing anything that `defined(CHERIOT_EXPOSE_...)` can't?
cheriot-rtos
github_2023
cpp
155
CHERIoT-Platform
nwf-msr
@@ -53,34 +178,272 @@ xSemaphoreCreateCounting(UBaseType_t uxMaxCount, UBaseType_t uxInitialCount) } /** - * Delete a heap-allocated semaphore. + * Create a heap-allocated binary semaphore. + * + * Binary semaphores are implemented as counting semaphores with a maximum count + * of 1. + */ +__always_inline static inline SemaphoreHandle_t xSemaphoreCreateBinary() +{ + return xSemaphoreCreateCounting(1, 0); +} + +/** + * Create a statically allocated binary semaphore. + * + * Binary semaphores are implemented as counting semaphores with a maximum count + * of 1. + */ +__always_inline static inline SemaphoreHandle_t +xSemaphoreCreateBinaryStatic(StaticSemaphore_t *pxSemaphoreBuffer) +{ + return xSemaphoreCreateCountingStatic(1, 0, pxSemaphoreBuffer); +} +#endif + +#if CHERIOT_FREERTOS_MUTEX +/** + * Create statically allocated mutex. + */ +__always_inline static inline SemaphoreHandle_t +xSemaphoreCreateMutexStatic(StaticSemaphore_t *pxMutexBuffer) +{ + pxMutexBuffer->mutex.lockWord = 0; + CHERIOT_FREERTOS_SEMAPHORE_KIND_SET(pxMutexBuffer, CheriotFreeRTOS_Mutex); + return pxMutexBuffer; +} + +/** + * Create a heap-allocated mutex. + */ +__always_inline static inline SemaphoreHandle_t xSemaphoreCreateMutex() +{ + SemaphoreHandle_t semaphore = + (SemaphoreHandle_t)malloc(sizeof(SemaphoreHandle_t));
As above?
cheriot-rtos
github_2023
cpp
155
CHERIoT-Platform
nwf-msr
@@ -53,34 +178,272 @@ xSemaphoreCreateCounting(UBaseType_t uxMaxCount, UBaseType_t uxInitialCount) } /** - * Delete a heap-allocated semaphore. + * Create a heap-allocated binary semaphore. + * + * Binary semaphores are implemented as counting semaphores with a maximum count + * of 1. + */ +__always_inline static inline SemaphoreHandle_t xSemaphoreCreateBinary() +{ + return xSemaphoreCreateCounting(1, 0); +} + +/** + * Create a statically allocated binary semaphore. + * + * Binary semaphores are implemented as counting semaphores with a maximum count + * of 1. + */ +__always_inline static inline SemaphoreHandle_t +xSemaphoreCreateBinaryStatic(StaticSemaphore_t *pxSemaphoreBuffer) +{ + return xSemaphoreCreateCountingStatic(1, 0, pxSemaphoreBuffer); +} +#endif + +#if CHERIOT_FREERTOS_MUTEX +/** + * Create statically allocated mutex. + */ +__always_inline static inline SemaphoreHandle_t +xSemaphoreCreateMutexStatic(StaticSemaphore_t *pxMutexBuffer) +{ + pxMutexBuffer->mutex.lockWord = 0; + CHERIOT_FREERTOS_SEMAPHORE_KIND_SET(pxMutexBuffer, CheriotFreeRTOS_Mutex); + return pxMutexBuffer; +} + +/** + * Create a heap-allocated mutex. + */ +__always_inline static inline SemaphoreHandle_t xSemaphoreCreateMutex() +{ + SemaphoreHandle_t semaphore = + (SemaphoreHandle_t)malloc(sizeof(SemaphoreHandle_t)); + if (semaphore != NULL) + { + xSemaphoreCreateMutexStatic(semaphore); + } + return semaphore; +} +#endif + +#if CHERIOT_FREERTOS_RECURSIVE_MUTEX + +/** + * Create a statically allocated recursive mutex. + */ +__always_inline static inline SemaphoreHandle_t +xSemaphoreCreateRecursiveMutexStatic(StaticSemaphore_t *pxMutexBuffer) +{ + pxMutexBuffer->recursiveMutex.lock.lockWord = 0; + pxMutexBuffer->recursiveMutex.depth = 0; + CHERIOT_FREERTOS_SEMAPHORE_KIND_SET(pxMutexBuffer, + CheriotFreeRTOS_RecursiveMutex); + return pxMutexBuffer; +} + +/** + * Create a heap-allocated recursive mutex. + */ +__always_inline static inline SemaphoreHandle_t +xSemaphoreCreateRecursiveMutex(void) +{ + SemaphoreHandle_t semaphore = + (SemaphoreHandle_t)malloc(sizeof(SemaphoreHandle_t));
Third time's the charm?
cheriot-rtos
github_2023
others
142
CHERIoT-Platform
rmn30
@@ -777,7 +777,7 @@ exception_entry_asm: // Restore the stack pointer. All other spilled values are spilled there. clc csp, TrustedStackFrame_offset_csp(ct1) // Update the current frame offset. - csw t2, TrustedStack_offset_frameoffset(ctp) + csh t2, TrustedStack_offset_frameoffset(ctp)
Was this previously a bug where this write was overflowing into the padding?
cheriot-rtos
github_2023
others
427
CHERIoT-Platform
nwf
@@ -1055,27 +1119,32 @@ namespace CHERI * all other cases. */ template<typename U> - bool is_subset_of(Capability<U> other) + bool is_subset_of(Capability<U, IsSealed> other) { return __builtin_cheri_subset_test(other.ptr, ptr); } /** * Seal this capability with the given key. */ - Capability<T> &seal(void *key) + [[nodiscard]] Capability<T, true> seal(void *key) { - ptr = static_cast<T *>(__builtin_cheri_seal(ptr, key)); - return *this; + return {reinterpret_cast<CHERI_SEALED(T *)>( + __builtin_cheri_seal(ptr, key))}; } /** * Unseal this capability with the given key. */ - Capability<T> &unseal(void *key) + [[nodiscard]] Capability<T, false> unseal(void *key)
Do you want to `requires IsSealed` here?
cheriot-rtos
github_2023
others
427
CHERIoT-Platform
nwf
@@ -1055,27 +1119,32 @@ namespace CHERI * all other cases. */ template<typename U> - bool is_subset_of(Capability<U> other) + bool is_subset_of(Capability<U, IsSealed> other) { return __builtin_cheri_subset_test(other.ptr, ptr); } /** * Seal this capability with the given key. */ - Capability<T> &seal(void *key) + [[nodiscard]] Capability<T, true> seal(void *key) { - ptr = static_cast<T *>(__builtin_cheri_seal(ptr, key)); - return *this; + return {reinterpret_cast<CHERI_SEALED(T *)>( + __builtin_cheri_seal(ptr, key))}; } /** * Unseal this capability with the given key. */ - Capability<T> &unseal(void *key) + [[nodiscard]] Capability<T, false> unseal(void *key) { - ptr = static_cast<T *>(__builtin_cheri_unseal(ptr, key)); - return *this; +#if __has_extension(cheri_sealed_pointers) && \ + defined(CHERIOT_NO_SEALED_POINTERS)
Do you mean `!defined` here as everywhere else? I don't see `CHERIOT_NO_SEALED_POINTERS` documented anywhere, so I'm not quite sure what it's supposed to be doing...
cheriot-rtos
github_2023
others
427
CHERIoT-Platform
nwf
@@ -132,8 +132,8 @@ namespace /** * Append a capability. */ - template<typename T> - __always_inline void append(CHERI::Capability<T> capability) + template<typename T, bool IsSealed> + __always_inline void append(CHERI::Capability<T, IsSealed> capability)
I wonder if it's worth a check and warning if the sealed state of the capability differs from the static annotation?
cheriot-rtos
github_2023
others
427
CHERIoT-Platform
nwf
@@ -1055,27 +1119,32 @@ namespace CHERI * all other cases. */ template<typename U> - bool is_subset_of(Capability<U> other) + bool is_subset_of(Capability<U, IsSealed> other) { return __builtin_cheri_subset_test(other.ptr, ptr); } /** * Seal this capability with the given key. */ - Capability<T> &seal(void *key) + [[nodiscard]] Capability<T, true> seal(void *key) { - ptr = static_cast<T *>(__builtin_cheri_seal(ptr, key)); - return *this; + return {reinterpret_cast<CHERI_SEALED(T *)>( + __builtin_cheri_seal(ptr, key))};
The lack of write-back to `ptr` is a breaking change. The `[[nodiscard]]` is nice, and I think you've updated all the call-sites in tree, but... some more words in the commentary might be useful and an announcement on the blog or signal group or something could be good, too.
cheriot-rtos
github_2023
cpp
427
CHERIoT-Platform
nwf
@@ -40,7 +41,10 @@ struct AllocatorCapabilityState uintptr_t reserved[2]; }; -struct SObjStruct; +/** + * Type for allocator capabilities. + */ +typedef CHERI_SEALED(struct AllocatorCapabilityState *) AllocatorCapability;
Why this wasn't a `typedef` far longer ago... sorry.
cheriot-rtos
github_2023
others
460
CHERIoT-Platform
davidchisnall
@@ -10,7 +10,8 @@ riscv32-unknown-unknown -fshort-wchar -nostdinc -fomit-frame-pointer --fno-builtin +-fno-builtin-setjmp +-fno-builtin-longjmp
These are only used for clangd, so don't matter too much.