├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── pr-check.yml │ └── tests.yml ├── .gitignore ├── .golangci.yaml ├── .licenserc.yaml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE-APACHE ├── README.md ├── _typos.toml ├── g_amd64.s ├── g_arm64.s ├── go.mod ├── go.sum ├── go_tls.h ├── runtimex.go ├── runtimex_other.go └── runtimex_test.go /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | 12 | A clear and concise description of what the bug is. 13 | 14 | **To Reproduce** 15 | 16 | Steps to reproduce the behavior: 17 | 1. Go to '...' 18 | 2. Click on '....' 19 | 3. Scroll down to '....' 20 | 4. See error 21 | 22 | **Expected behavior** 23 | 24 | A clear and concise description of what you expected to happen. 25 | 26 | **Screenshots** 27 | 28 | If applicable, add screenshots to help explain your problem. 29 | 30 | **Kitex version:** 31 | 32 | Please provide the version of Kitex you are using. 33 | 34 | **Environment:** 35 | 36 | The output of `go env`. 37 | 38 | **Additional context** 39 | 40 | Add any other context about the problem here. 41 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | 12 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 13 | 14 | **Describe the solution you'd like** 15 | 16 | A clear and concise description of what you want to happen. 17 | 18 | **Describe alternatives you've considered** 19 | 20 | A clear and concise description of any alternative solutions or features you've considered. 21 | 22 | **Additional context** 23 | 24 | Add any other context or screenshots about the feature request here. 25 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | #### What type of PR is this? 2 | 17 | 18 | #### Check the PR title. 19 | 24 | - [ ] This PR title match the format: \(optional scope): \ 25 | - [ ] The description of this PR title is user-oriented and clear enough for others to understand. 26 | - [ ] Attach the PR updating the user documentation if the current PR requires user awareness at the usage level. [User docs repo](https://github.com/cloudwego/cloudwego.github.io) 27 | 28 | 29 | #### (Optional) Translate the PR title into Chinese. 30 | 31 | 32 | #### (Optional) More detailed description for this PR(en: English/zh: Chinese). 33 | 36 | en: 37 | zh(optional): 38 | 39 | 40 | #### (Optional) Which issue(s) this PR fixes: 41 | 45 | 46 | #### (optional) The PR that updates user documentation: 47 | 50 | -------------------------------------------------------------------------------- /.github/workflows/pr-check.yml: -------------------------------------------------------------------------------- 1 | name: Pull Request Check 2 | 3 | on: [ pull_request ] 4 | 5 | jobs: 6 | compliant: 7 | runs-on: [ self-hosted, X64 ] 8 | steps: 9 | - uses: actions/checkout@v3 10 | - name: Check License Header 11 | uses: apache/skywalking-eyes/header@v0.4.0 12 | env: 13 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 14 | - name: Check Spell 15 | uses: crate-ci/typos@master 16 | 17 | staticcheck: 18 | runs-on: [ self-hosted, X64 ] 19 | steps: 20 | - uses: actions/checkout@v3 21 | - name: Set up Go 22 | uses: actions/setup-go@v3 23 | with: 24 | go-version: "1.20" 25 | - uses: actions/cache@v3 26 | with: 27 | path: ~/go/pkg/mod 28 | key: reviewdog-${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} 29 | restore-keys: | 30 | reviewdog-${{ runner.os }}-go- 31 | - uses: reviewdog/action-staticcheck@v1 32 | with: 33 | github_token: ${{ secrets.github_token }} 34 | # Change reviewdog reporter if you need [github-pr-check,github-check,github-pr-review]. 35 | reporter: github-pr-review 36 | # Report all results. 37 | filter_mode: nofilter 38 | # Exit with 1 when it find at least one finding. 39 | fail_on_error: true 40 | # Set staticcheck flags 41 | staticcheck_flags: -checks=inherit,-SA1029 42 | 43 | lint: 44 | runs-on: [ self-hosted, X64 ] 45 | steps: 46 | - uses: actions/checkout@v3 47 | - name: Set up Go 48 | uses: actions/setup-go@v3 49 | with: 50 | go-version: "1.20" 51 | - name: Golangci Lint 52 | # https://golangci-lint.run/ 53 | uses: golangci/golangci-lint-action@v3 54 | with: 55 | version: latest 56 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: [ push, pull_request ] 4 | 5 | jobs: 6 | unit-benchmark-test: 7 | strategy: 8 | matrix: 9 | go: [ "1.18", "1.19", "1.20", "1.21" ] 10 | os: [ X64, ARM64 ] 11 | runs-on: ${{ matrix.os }} 12 | steps: 13 | - uses: actions/checkout@v3 14 | 15 | - name: Set up Go 16 | uses: actions/setup-go@v3 17 | with: 18 | go-version: ${{ matrix.go }} 19 | 20 | - name: Unit Test 21 | run: go test -race -covermode=atomic -coverprofile=coverage.out ./... 22 | 23 | - name: Benchmark 24 | run: go test -bench=. -benchmem -run=none ./... 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | 17 | # the result of the go build 18 | output* 19 | output/* 20 | 21 | # Files generated by IDEs 22 | .idea/ 23 | *.iml 24 | 25 | # Vim swap files 26 | *.swp 27 | 28 | # Vscode files 29 | .vscode 30 | 31 | -------------------------------------------------------------------------------- /.golangci.yaml: -------------------------------------------------------------------------------- 1 | # Options for analysis running. 2 | run: 3 | # include `vendor` `third_party` `testdata` `examples` `Godeps` `builtin` 4 | skip-dirs-use-default: true 5 | skip-dirs: 6 | - kitex_gen 7 | skip-files: 8 | - ".*\\.mock\\.go$" 9 | # output configuration options 10 | output: 11 | # Format: colored-line-number|line-number|json|tab|checkstyle|code-climate|junit-xml|github-actions 12 | format: colored-line-number 13 | # All available settings of specific linters. 14 | # Refer to https://golangci-lint.run/usage/linters 15 | linters-settings: 16 | gofumpt: 17 | # Choose whether to use the extra rules. 18 | # Default: false 19 | extra-rules: true 20 | govet: 21 | # Disable analyzers by name. 22 | # Run `go tool vet help` to see all analyzers. 23 | disable: 24 | - stdmethods 25 | linters: 26 | enable: 27 | - gofumpt 28 | - goimports 29 | - gofmt 30 | disable: 31 | - errcheck 32 | - typecheck 33 | - deadcode 34 | - varcheck 35 | - staticcheck 36 | issues: 37 | exclude-use-default: true 38 | -------------------------------------------------------------------------------- /.licenserc.yaml: -------------------------------------------------------------------------------- 1 | header: 2 | license: 3 | spdx-id: Apache-2.0 4 | copyright-owner: CloudWeGo Authors 5 | 6 | paths: 7 | - '**/*.go' 8 | - '**/*.s' 9 | 10 | comment: on-failure -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | conduct@cloudwego.io. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | ## Your First Pull Request 4 | We use github for our codebase. You can start by reading [How To Pull Request](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-requests). 5 | 6 | ## Branch Organization 7 | We use [git-flow](https://nvie.com/posts/a-successful-git-branching-model/) as our branch organization, as known as [FDD](https://en.wikipedia.org/wiki/Feature-driven_development) 8 | 9 | ## Bugs 10 | ### 1. How to Find Known Issues 11 | We are using [Github Issues](https://github.com/cloudwego/kitex/issues) for our public bugs. We keep a close eye on this and try to make it clear when we have an internal fix in progress. Before filing a new task, try to make sure your problem doesn’t already exist. 12 | 13 | ### 2. Reporting New Issues 14 | Providing a reduced test code is a recommended way for reporting issues. Then can placed in: 15 | - Just in issues 16 | - [Golang Playground](https://play.golang.org/) 17 | 18 | ### 3. Security Bugs 19 | Please do not report the safe disclosure of bugs to public issues. Contact us by [Support Email](mailto:conduct@cloudwego.io) 20 | 21 | ## How to Get in Touch 22 | - [Email](mailto:conduct@cloudwego.io) 23 | 24 | ## Submit a Pull Request 25 | Before you submit your Pull Request (PR) consider the following guidelines: 26 | 1. Search [GitHub](https://github.com/cloudwego/kitex/pulls) for an open or closed PR that relates to your submission. You don't want to duplicate existing efforts. 27 | 2. Be sure that an issue describes the problem you're fixing, or documents the design for the feature you'd like to add. Discussing the design upfront helps to ensure that we're ready to accept your work. 28 | 3. [Fork](https://docs.github.com/en/github/getting-started-with-github/fork-a-repo) the cloudwego/kitex repo. 29 | 4. In your forked repository, make your changes in a new git branch: 30 | ``` 31 | git checkout -b my-fix-branch develop 32 | ``` 33 | 5. Create your patch, including appropriate test cases. 34 | 6. Follow our [Style Guides](#code-style-guides). 35 | 7. Commit your changes using a descriptive commit message that follows [AngularJS Git Commit Message Conventions](https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit). 36 | Adherence to these conventions is necessary because release notes are automatically generated from these messages. 37 | 8. Push your branch to GitHub: 38 | ``` 39 | git push origin my-fix-branch 40 | ``` 41 | 9. In GitHub, send a pull request to `kitex:develop` 42 | 43 | ## Contribution Prerequisites 44 | - Our development environment keeps up with [Go Official](https://golang.org/project/). 45 | - You need fully checking with lint tools before submit your pull request. [gofmt](https://golang.org/pkg/cmd/gofmt/) and [golangci-lint](https://github.com/golangci/golangci-lint) 46 | - You are familiar with [Github](https://github.com) 47 | - Maybe you need familiar with [Actions](https://github.com/features/actions)(our default workflow tool). 48 | 49 | ## Code Style Guides 50 | Also see [Pingcap General advice](https://pingcap.github.io/style-guide/general.html). 51 | 52 | Good resources: 53 | - [Effective Go](https://golang.org/doc/effective_go) 54 | - [Go Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments) 55 | - [Uber Go Style Guide](https://github.com/uber-go/guide/blob/master/style.md) 56 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # runtimex 2 | 3 | Runtimex package help to expose Go Runtime internals representation safely. 4 | 5 | ## Usage 6 | 7 | ### Get Goroutine ID 8 | 9 | ```go 10 | gid, err := runtimex.GID() 11 | ``` 12 | 13 | ### Get Processor ID 14 | 15 | ```go 16 | pid, err := runtimex.PID() 17 | ``` 18 | 19 | ## Note 20 | 21 | Since we use a hack way to expose internal representation of the Go runtime, so if Go change some internal variable names, the package will return error. 22 | 23 | You should care about the error returned by runtimex and do the fallback logic If necessary. 24 | 25 | For now, we only depend on `runtime.g` and `g.goid`. 26 | -------------------------------------------------------------------------------- /_typos.toml: -------------------------------------------------------------------------------- 1 | # Typo check: https://github.com/crate-ci/typos 2 | 3 | [files] 4 | extend-exclude = ["go.mod", "go.sum", "check_branch_name.sh"] 5 | -------------------------------------------------------------------------------- /g_amd64.s: -------------------------------------------------------------------------------- 1 | // Copyright 2024 CloudWeGo Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #include "textflag.h" 16 | #include "go_tls.h" 17 | 18 | TEXT ·getg(SB), NOSPLIT, $0-8 19 | get_tls(CX) 20 | MOVQ g(CX), AX 21 | MOVQ AX, ret+0(FP) 22 | RET 23 | -------------------------------------------------------------------------------- /g_arm64.s: -------------------------------------------------------------------------------- 1 | // Copyright 2024 CloudWeGo Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #include "go_asm.h" 16 | #include "textflag.h" 17 | 18 | TEXT ·getg(SB), NOSPLIT, $0-8 19 | MOVD g, R8 20 | MOVD R8, ret+0(FP) 21 | RET 22 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/cloudwego/runtimex 2 | 3 | go 1.17 4 | 5 | require github.com/modern-go/reflect2 v1.0.2 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= 2 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= 3 | -------------------------------------------------------------------------------- /go_tls.h: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | #ifdef GOARCH_arm 6 | #define LR R14 7 | #endif 8 | 9 | #ifdef GOARCH_amd64 10 | #define get_tls(r) MOVQ TLS, r 11 | #define g(r) 0(r)(TLS*1) 12 | #endif 13 | 14 | #ifdef GOARCH_386 15 | #define get_tls(r) MOVL TLS, r 16 | #define g(r) 0(r)(TLS*1) 17 | #endif 18 | -------------------------------------------------------------------------------- /runtimex.go: -------------------------------------------------------------------------------- 1 | //go:build arm64 || amd64 2 | 3 | // Copyright 2024 CloudWeGo Authors 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | 17 | package runtimex 18 | 19 | import ( 20 | "fmt" 21 | "runtime" 22 | "unsafe" 23 | 24 | "github.com/modern-go/reflect2" 25 | ) 26 | 27 | var ( 28 | // Runtime internals variables 29 | gType reflect2.StructType 30 | gidField reflect2.StructField 31 | 32 | ErrNotSupported = fmt.Errorf("%s is not supported", runtime.Version()) 33 | ) 34 | 35 | func init() { 36 | gType, _ = reflect2.TypeByName("runtime.g").(reflect2.StructType) 37 | if gType != nil { 38 | gidField = gType.FieldByName("goid") 39 | } 40 | } 41 | 42 | func getg() unsafe.Pointer 43 | 44 | //go:noescape 45 | //go:linkname runtime_procPin runtime.procPin 46 | func runtime_procPin() int 47 | 48 | //go:noescape 49 | //go:linkname runtime_procUnpin runtime.procUnpin 50 | func runtime_procUnpin() 51 | 52 | // GID return current goroutine's ID 53 | func GID() (int, error) { 54 | if gidField == nil { 55 | return 0, ErrNotSupported 56 | } 57 | gp := getg() 58 | gid := *(*int64)(unsafe.Add(gp, gidField.Offset())) 59 | return int(gid), nil 60 | } 61 | 62 | // PID return current processor's ID 63 | // It may not 100% accurate because the scheduler may preempt current goroutine and re-schedule it to another P after the function call return, 64 | // so the caller should tolerate the preemption. 65 | func PID() (int, error) { 66 | id := runtime_procPin() 67 | runtime_procUnpin() 68 | return id, nil 69 | } 70 | -------------------------------------------------------------------------------- /runtimex_other.go: -------------------------------------------------------------------------------- 1 | //go:build !(arm64 || amd64) 2 | 3 | // Copyright 2024 CloudWeGo Authors 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | 17 | package runtimex 18 | 19 | import ( 20 | "fmt" 21 | "runtime" 22 | ) 23 | 24 | var ErrUnimplemented = fmt.Errorf("runtimex: unimplemented in this platform[%s]", runtime.GOARCH) 25 | 26 | func GID() (int, error) { 27 | return 0, ErrUnimplemented 28 | } 29 | 30 | func PID() (int, error) { 31 | return 0, ErrUnimplemented 32 | } 33 | -------------------------------------------------------------------------------- /runtimex_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2024 CloudWeGo Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package runtimex_test 16 | 17 | import ( 18 | "runtime" 19 | "sync" 20 | "sync/atomic" 21 | "testing" 22 | "time" 23 | 24 | "github.com/modern-go/reflect2" 25 | 26 | "github.com/cloudwego/runtimex" 27 | ) 28 | 29 | //go:noinline 30 | func testStackFunction(n int) int { 31 | var stack [1024 * 4]int64 32 | for i := 0; i < len(stack); i++ { 33 | stack[i] = int64(n + i) 34 | } 35 | return int(stack[len(stack)/2]) 36 | } 37 | 38 | func assert(t *testing.T, cond bool, args ...interface{}) { 39 | t.Helper() 40 | if cond { 41 | return 42 | } 43 | if len(args) > 0 { 44 | t.Fatal(args...) 45 | } 46 | t.Fatal("assertion failed") 47 | } 48 | 49 | func TestReflect2NotFound(t *testing.T) { 50 | notFound, _ := reflect2.TypeByName("runtime.xxx123").(reflect2.StructType) 51 | assert(t, notFound == nil) 52 | 53 | gType := reflect2.TypeByName("runtime.g").(reflect2.StructType) 54 | assert(t, gType != nil, gType) 55 | mField := gType.FieldByName("xxx123") 56 | assert(t, mField == nil) 57 | } 58 | 59 | func TestRuntimeStatus(t *testing.T) { 60 | goroutines := 8 61 | pnum := 4 62 | oldpnum := runtime.GOMAXPROCS(pnum) 63 | defer runtime.GOMAXPROCS(oldpnum) 64 | 65 | var ( 66 | stop int32 67 | wg sync.WaitGroup 68 | gm sync.Map 69 | pm sync.Map 70 | ) 71 | for i := 0; i < goroutines; i++ { 72 | wg.Add(1) 73 | go func(n int) { 74 | defer wg.Done() 75 | for j := 1; atomic.LoadInt32(&stop) == 0; j++ { 76 | testStackFunction(j % 102400) 77 | 78 | if j%1024 == 0 { 79 | gid, err := runtimex.GID() 80 | assert(t, err == nil) 81 | pid, err := runtimex.PID() 82 | assert(t, err == nil) 83 | t.Logf("gid=%d,pid=%d", gid, pid) 84 | 85 | gm.Store(gid, true) 86 | pm.Store(pid, true) 87 | } 88 | } 89 | }(i) 90 | } 91 | time.Sleep(time.Second) 92 | atomic.StoreInt32(&stop, 1) 93 | wg.Wait() 94 | gcount := 0 95 | gm.Range(func(key, value interface{}) bool { 96 | gcount++ 97 | return true 98 | }) 99 | pcount := 0 100 | pm.Range(func(key, value interface{}) bool { 101 | pcount++ 102 | return true 103 | }) 104 | assert(t, gcount == goroutines, gcount, goroutines) 105 | assert(t, pcount == pnum, pcount, pnum) 106 | } 107 | 108 | func BenchmarkGID(b *testing.B) { 109 | b.ReportAllocs() 110 | // 0 allocs/op 111 | for i := 0; i < b.N; i++ { 112 | id, err := runtimex.GID() 113 | if id < 0 || err != nil { 114 | b.Fatal(err) 115 | } 116 | } 117 | } 118 | 119 | func BenchmarkPID(b *testing.B) { 120 | b.ReportAllocs() 121 | // 0 allocs/op 122 | for i := 0; i < b.N; i++ { 123 | id, err := runtimex.PID() 124 | if id < 0 || err != nil { 125 | b.Fatal(err) 126 | } 127 | } 128 | } 129 | --------------------------------------------------------------------------------