Compare commits

..

3 Commits

Author SHA1 Message Date
Ayke van Laethem 65a059a973 samd51: add support for async SPI using DMA 2023-11-05 19:35:00 +01:00
Ayke van Laethem cb95259adf rp2040: add SPI DMA support 2023-11-04 16:18:45 +01:00
Ayke van Laethem 24d718fa05 machine: add dummy async SPI methods
This prepares all devices for actual async SPI support.
2023-11-04 16:14:47 +01:00
339 changed files with 5098 additions and 8239 deletions
+13 -13
View File
@@ -5,17 +5,17 @@ commands:
steps: steps:
- run: - run:
name: "Pull submodules" name: "Pull submodules"
command: git submodule update --init command: git submodule update --init --recursive
llvm-source-linux: llvm-source-linux:
steps: steps:
- restore_cache: - restore_cache:
keys: keys:
- llvm-source-18-v1 - llvm-source-16-v3
- run: - run:
name: "Fetch LLVM source" name: "Fetch LLVM source"
command: make llvm-source command: make llvm-source
- save_cache: - save_cache:
key: llvm-source-18-v1 key: llvm-source-16-v3
paths: paths:
- llvm-project/clang/lib/Headers - llvm-project/clang/lib/Headers
- llvm-project/clang/include - llvm-project/clang/include
@@ -33,13 +33,13 @@ commands:
steps: steps:
- restore_cache: - restore_cache:
keys: keys:
- binaryen-linux-v3 - binaryen-linux-v2
- run: - run:
name: "Build Binaryen" name: "Build Binaryen"
command: | command: |
make binaryen make binaryen
- save_cache: - save_cache:
key: binaryen-linux-v3 key: binaryen-linux-v2
paths: paths:
- build/wasm-opt - build/wasm-opt
test-linux: test-linux:
@@ -75,10 +75,10 @@ commands:
- run: go install -tags=llvm<<parameters.llvm>> . - run: go install -tags=llvm<<parameters.llvm>> .
- restore_cache: - restore_cache:
keys: keys:
- wasi-libc-sysroot-systemclang-v7 - wasi-libc-sysroot-systemclang-v6
- run: make wasi-libc - run: make wasi-libc
- save_cache: - save_cache:
key: wasi-libc-sysroot-systemclang-v7 key: wasi-libc-sysroot-systemclang-v6
paths: paths:
- lib/wasi-libc/sysroot - lib/wasi-libc/sysroot
- when: - when:
@@ -88,7 +88,7 @@ commands:
# Do this before gen-device so that it doesn't check the # Do this before gen-device so that it doesn't check the
# formatting of generated files. # formatting of generated files.
name: Check Go code formatting name: Check Go code formatting
command: make fmt-check lint command: make fmt-check
- run: make gen-device -j4 - run: make gen-device -j4
- run: make smoketest XTENSA=0 - run: make smoketest XTENSA=0
- save_cache: - save_cache:
@@ -105,12 +105,12 @@ jobs:
- test-linux: - test-linux:
llvm: "15" llvm: "15"
resource_class: large resource_class: large
test-llvm18-go122: test-llvm17-go121:
docker: docker:
- image: golang:1.22-bullseye - image: golang:1.21-bullseye
steps: steps:
- test-linux: - test-linux:
llvm: "18" llvm: "17"
resource_class: large resource_class: large
workflows: workflows:
@@ -119,5 +119,5 @@ workflows:
# This tests our lowest supported versions of Go and LLVM, to make sure at # This tests our lowest supported versions of Go and LLVM, to make sure at
# least the smoke tests still pass. # least the smoke tests still pass.
- test-llvm15-go118 - test-llvm15-go118
# This tests LLVM 18 support when linking against system libraries. # This tests the upcoming LLVM 17 support.
- test-llvm18-go122 - test-llvm17-go121
+27 -36
View File
@@ -14,36 +14,26 @@ concurrency:
jobs: jobs:
build-macos: build-macos:
name: build-macos name: build-macos
strategy: runs-on: macos-11
matrix:
# macos-12: amd64 (oldest supported version as of 05-02-2024)
# macos-14: arm64 (oldest arm64 version)
os: [macos-12, macos-14]
include:
- os: macos-12
goarch: amd64
- os: macos-14
goarch: arm64
runs-on: ${{ matrix.os }}
steps: steps:
- name: Install Dependencies - name: Install Dependencies
shell: bash shell: bash
run: | run: |
HOMEBREW_NO_AUTO_UPDATE=1 brew install qemu binaryen HOMEBREW_NO_AUTO_UPDATE=1 brew install qemu binaryen
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v3
with: with:
submodules: true submodules: true
- name: Install Go - name: Install Go
uses: actions/setup-go@v5 uses: actions/setup-go@v3
with: with:
go-version: '1.22' go-version: '1.21'
cache: true cache: true
- name: Restore LLVM source cache - name: Restore LLVM source cache
uses: actions/cache/restore@v4 uses: actions/cache/restore@v3
id: cache-llvm-source id: cache-llvm-source
with: with:
key: llvm-source-18-${{ matrix.os }}-v2 key: llvm-source-16-macos-v1
path: | path: |
llvm-project/clang/lib/Headers llvm-project/clang/lib/Headers
llvm-project/clang/include llvm-project/clang/include
@@ -54,7 +44,7 @@ jobs:
if: steps.cache-llvm-source.outputs.cache-hit != 'true' if: steps.cache-llvm-source.outputs.cache-hit != 'true'
run: make llvm-source run: make llvm-source
- name: Save LLVM source cache - name: Save LLVM source cache
uses: actions/cache/save@v4 uses: actions/cache/save@v3
if: steps.cache-llvm-source.outputs.cache-hit != 'true' if: steps.cache-llvm-source.outputs.cache-hit != 'true'
with: with:
key: ${{ steps.cache-llvm-source.outputs.cache-primary-key }} key: ${{ steps.cache-llvm-source.outputs.cache-primary-key }}
@@ -65,10 +55,10 @@ jobs:
llvm-project/lld/include llvm-project/lld/include
llvm-project/llvm/include llvm-project/llvm/include
- name: Restore LLVM build cache - name: Restore LLVM build cache
uses: actions/cache/restore@v4 uses: actions/cache/restore@v3
id: cache-llvm-build id: cache-llvm-build
with: with:
key: llvm-build-18-${{ matrix.os }}-v2 key: llvm-build-16-macos-v1
path: llvm-build path: llvm-build
- name: Build LLVM - name: Build LLVM
if: steps.cache-llvm-build.outputs.cache-hit != 'true' if: steps.cache-llvm-build.outputs.cache-hit != 'true'
@@ -83,16 +73,16 @@ jobs:
make llvm-build make llvm-build
find llvm-build -name CMakeFiles -prune -exec rm -r '{}' \; find llvm-build -name CMakeFiles -prune -exec rm -r '{}' \;
- name: Save LLVM build cache - name: Save LLVM build cache
uses: actions/cache/save@v4 uses: actions/cache/save@v3
if: steps.cache-llvm-build.outputs.cache-hit != 'true' if: steps.cache-llvm-build.outputs.cache-hit != 'true'
with: with:
key: ${{ steps.cache-llvm-build.outputs.cache-primary-key }} key: ${{ steps.cache-llvm-build.outputs.cache-primary-key }}
path: llvm-build path: llvm-build
- name: Cache wasi-libc sysroot - name: Cache wasi-libc sysroot
uses: actions/cache@v4 uses: actions/cache@v3
id: cache-wasi-libc id: cache-wasi-libc
with: with:
key: wasi-libc-sysroot-${{ matrix.os }}-v1 key: wasi-libc-sysroot-v4
path: lib/wasi-libc/sysroot path: lib/wasi-libc/sysroot
- name: Build wasi-libc - name: Build wasi-libc
if: steps.cache-wasi-libc.outputs.cache-hit != 'true' if: steps.cache-wasi-libc.outputs.cache-hit != 'true'
@@ -108,7 +98,7 @@ jobs:
run: make tinygo-test run: make tinygo-test
- name: Make release artifact - name: Make release artifact
shell: bash shell: bash
run: cp -p build/release.tar.gz build/tinygo.darwin-${{ matrix.goarch }}.tar.gz run: cp -p build/release.tar.gz build/tinygo.darwin-amd64.tar.gz
- name: Publish release artifact - name: Publish release artifact
# Note: this release artifact is double-zipped, see: # Note: this release artifact is double-zipped, see:
# https://github.com/actions/upload-artifact/issues/39 # https://github.com/actions/upload-artifact/issues/39
@@ -116,10 +106,10 @@ jobs:
# - have a double-zipped artifact when downloaded from the UI # - have a double-zipped artifact when downloaded from the UI
# - have a very slow artifact upload # - have a very slow artifact upload
# We're doing the former here, to keep artifact uploads fast. # We're doing the former here, to keep artifact uploads fast.
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v2
with: with:
name: darwin-${{ matrix.goarch }}-double-zipped name: darwin-amd64-double-zipped
path: build/tinygo.darwin-${{ matrix.goarch }}.tar.gz path: build/tinygo.darwin-amd64.tar.gz
- name: Smoke tests - name: Smoke tests
shell: bash shell: bash
run: make smoketest TINYGO=$(PWD)/build/tinygo run: make smoketest TINYGO=$(PWD)/build/tinygo
@@ -128,32 +118,33 @@ jobs:
runs-on: macos-latest runs-on: macos-latest
strategy: strategy:
matrix: matrix:
version: [16, 17, 18] version: [16, 17]
steps: steps:
- name: Set up Homebrew - name: Update Homebrew
uses: Homebrew/actions/setup-homebrew@master run: brew update
- name: Fix Python symlinks - name: Fix Python symlinks
run: | run: |
# Github runners have broken symlinks, so relink # Github runners have broken symlinks, so relink
# see: https://github.com/actions/setup-python/issues/577 # see: https://github.com/actions/setup-python/issues/577
brew list -1 | grep python | while read formula; do brew unlink $formula; brew link --overwrite $formula; done brew unlink python
brew link --overwrite python
- name: Install LLVM - name: Install LLVM
run: | run: |
brew install llvm@${{ matrix.version }} HOMEBREW_NO_AUTO_UPDATE=1 brew install llvm@${{ matrix.version }}
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v3
- name: Install Go - name: Install Go
uses: actions/setup-go@v5 uses: actions/setup-go@v3
with: with:
go-version: '1.22' go-version: '1.21'
cache: true cache: true
- name: Build TinyGo (LLVM ${{ matrix.version }}) - name: Build TinyGo (LLVM ${{ matrix.version }})
run: go install -tags=llvm${{ matrix.version }} run: go install -tags=llvm${{ matrix.version }}
- name: Check binary - name: Check binary
run: tinygo version run: tinygo version
- name: Build TinyGo (default LLVM) - name: Build TinyGo (default LLVM)
if: matrix.version == 18 if: matrix.version == 16
run: go install run: go install
- name: Check binary - name: Check binary
if: matrix.version == 18 if: matrix.version == 16
run: tinygo version run: tinygo version
+7 -17
View File
@@ -19,26 +19,15 @@ jobs:
packages: write packages: write
contents: read contents: read
steps: steps:
- name: Free Disk space
shell: bash
run: |
df -h
sudo rm -rf /opt/hostedtoolcache
sudo rm -rf /usr/local/lib/android
sudo rm -rf /usr/share/dotnet
sudo rm -rf /opt/ghc
sudo rm -rf /usr/local/graalvm
sudo rm -rf /usr/local/share/boost
df -h
- name: Check out the repo - name: Check out the repo
uses: actions/checkout@v4 uses: actions/checkout@v3
with: with:
submodules: recursive submodules: recursive
- name: Set up Docker Buildx - name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3 uses: docker/setup-buildx-action@v2
- name: Docker meta - name: Docker meta
id: meta id: meta
uses: docker/metadata-action@v5 uses: docker/metadata-action@v4
with: with:
images: | images: |
tinygo/tinygo-dev tinygo/tinygo-dev
@@ -47,23 +36,24 @@ jobs:
type=sha,format=long type=sha,format=long
type=raw,value=latest type=raw,value=latest
- name: Log in to Docker Hub - name: Log in to Docker Hub
uses: docker/login-action@v3 uses: docker/login-action@v2
with: with:
username: ${{ secrets.DOCKER_HUB_USERNAME }} username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}
- name: Log in to Github Container Registry - name: Log in to Github Container Registry
uses: docker/login-action@v3 uses: docker/login-action@v2
with: with:
registry: ghcr.io registry: ghcr.io
username: ${{ github.actor }} username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push - name: Build and push
uses: docker/build-push-action@v5 uses: docker/build-push-action@v3
with: with:
context: . context: .
push: true push: true
tags: ${{ steps.meta.outputs.tags }} tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }} labels: ${{ steps.meta.outputs.labels }}
build-contexts: tinygo-llvm-build=docker-image://tinygo/llvm-16
cache-from: type=gha cache-from: type=gha
cache-to: type=gha,mode=max cache-to: type=gha,mode=max
- name: Trigger Drivers repo build on Github Actions - name: Trigger Drivers repo build on Github Actions
+47 -49
View File
@@ -18,32 +18,32 @@ jobs:
# statically linked binary. # statically linked binary.
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: container:
image: golang:1.22-alpine image: golang:1.21-alpine
steps: steps:
- name: Install apk dependencies - name: Install apk dependencies
# tar: needed for actions/cache@v4 # tar: needed for actions/cache@v3
# git+openssh: needed for checkout (I think?) # git+openssh: needed for checkout (I think?)
# ruby: needed to install fpm # ruby: needed to install fpm
run: apk add tar git openssh make g++ ruby-dev run: apk add tar git openssh make g++ ruby
- name: Work around CVE-2022-24765 - name: Work around CVE-2022-24765
# We're not on a multi-user machine, so this is safe. # We're not on a multi-user machine, so this is safe.
run: git config --global --add safe.directory "$GITHUB_WORKSPACE" run: git config --global --add safe.directory "$GITHUB_WORKSPACE"
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v3
with: with:
submodules: true submodules: true
- name: Cache Go - name: Cache Go
uses: actions/cache@v4 uses: actions/cache@v3
with: with:
key: go-cache-linux-alpine-v1-${{ hashFiles('go.mod') }} key: go-cache-linux-alpine-v1-${{ hashFiles('go.mod') }}
path: | path: |
~/.cache/go-build ~/.cache/go-build
~/go/pkg/mod ~/go/pkg/mod
- name: Restore LLVM source cache - name: Restore LLVM source cache
uses: actions/cache/restore@v4 uses: actions/cache/restore@v3
id: cache-llvm-source id: cache-llvm-source
with: with:
key: llvm-source-18-linux-alpine-v1 key: llvm-source-16-linux-alpine-v1
path: | path: |
llvm-project/clang/lib/Headers llvm-project/clang/lib/Headers
llvm-project/clang/include llvm-project/clang/include
@@ -54,7 +54,7 @@ jobs:
if: steps.cache-llvm-source.outputs.cache-hit != 'true' if: steps.cache-llvm-source.outputs.cache-hit != 'true'
run: make llvm-source run: make llvm-source
- name: Save LLVM source cache - name: Save LLVM source cache
uses: actions/cache/save@v4 uses: actions/cache/save@v3
if: steps.cache-llvm-source.outputs.cache-hit != 'true' if: steps.cache-llvm-source.outputs.cache-hit != 'true'
with: with:
key: ${{ steps.cache-llvm-source.outputs.cache-primary-key }} key: ${{ steps.cache-llvm-source.outputs.cache-primary-key }}
@@ -65,10 +65,10 @@ jobs:
llvm-project/lld/include llvm-project/lld/include
llvm-project/llvm/include llvm-project/llvm/include
- name: Restore LLVM build cache - name: Restore LLVM build cache
uses: actions/cache/restore@v4 uses: actions/cache/restore@v3
id: cache-llvm-build id: cache-llvm-build
with: with:
key: llvm-build-18-linux-alpine-v1 key: llvm-build-16-linux-alpine-v1
path: llvm-build path: llvm-build
- name: Build LLVM - name: Build LLVM
if: steps.cache-llvm-build.outputs.cache-hit != 'true' if: steps.cache-llvm-build.outputs.cache-hit != 'true'
@@ -83,13 +83,13 @@ jobs:
# Remove unnecessary object files (to reduce cache size). # Remove unnecessary object files (to reduce cache size).
find llvm-build -name CMakeFiles -prune -exec rm -r '{}' \; find llvm-build -name CMakeFiles -prune -exec rm -r '{}' \;
- name: Save LLVM build cache - name: Save LLVM build cache
uses: actions/cache/save@v4 uses: actions/cache/save@v3
if: steps.cache-llvm-build.outputs.cache-hit != 'true' if: steps.cache-llvm-build.outputs.cache-hit != 'true'
with: with:
key: ${{ steps.cache-llvm-build.outputs.cache-primary-key }} key: ${{ steps.cache-llvm-build.outputs.cache-primary-key }}
path: llvm-build path: llvm-build
- name: Cache Binaryen - name: Cache Binaryen
uses: actions/cache@v4 uses: actions/cache@v3
id: cache-binaryen id: cache-binaryen
with: with:
key: binaryen-linux-alpine-v1 key: binaryen-linux-alpine-v1
@@ -100,10 +100,10 @@ jobs:
apk add cmake samurai python3 apk add cmake samurai python3
make binaryen STATIC=1 make binaryen STATIC=1
- name: Cache wasi-libc - name: Cache wasi-libc
uses: actions/cache@v4 uses: actions/cache@v3
id: cache-wasi-libc id: cache-wasi-libc
with: with:
key: wasi-libc-sysroot-linux-alpine-v2 key: wasi-libc-sysroot-linux-alpine-v1
path: lib/wasi-libc/sysroot path: lib/wasi-libc/sysroot
- name: Build wasi-libc - name: Build wasi-libc
if: steps.cache-wasi-libc.outputs.cache-hit != 'true' if: steps.cache-wasi-libc.outputs.cache-hit != 'true'
@@ -113,15 +113,13 @@ jobs:
gem install --version 4.0.7 public_suffix gem install --version 4.0.7 public_suffix
gem install --version 2.7.6 dotenv gem install --version 2.7.6 dotenv
gem install --no-document fpm gem install --no-document fpm
- name: Run linter
run: make lint
- name: Build TinyGo release - name: Build TinyGo release
run: | run: |
make release deb -j3 STATIC=1 make release deb -j3 STATIC=1
cp -p build/release.tar.gz /tmp/tinygo.linux-amd64.tar.gz cp -p build/release.tar.gz /tmp/tinygo.linux-amd64.tar.gz
cp -p build/release.deb /tmp/tinygo_amd64.deb cp -p build/release.deb /tmp/tinygo_amd64.deb
- name: Publish release artifact - name: Publish release artifact
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v3
with: with:
name: linux-amd64-double-zipped name: linux-amd64-double-zipped
path: | path: |
@@ -133,11 +131,11 @@ jobs:
needs: build-linux needs: build-linux
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v3
- name: Install Go - name: Install Go
uses: actions/setup-go@v5 uses: actions/setup-go@v3
with: with:
go-version: '1.22' go-version: '1.21'
cache: true cache: true
- name: Install wasmtime - name: Install wasmtime
run: | run: |
@@ -146,7 +144,7 @@ jobs:
tar -C $HOME/.wasmtime/bin --wildcards -xf wasmtime-v14.0.4-x86_64-linux.tar.xz --strip-components=1 wasmtime-v14.0.4-x86_64-linux/* tar -C $HOME/.wasmtime/bin --wildcards -xf wasmtime-v14.0.4-x86_64-linux.tar.xz --strip-components=1 wasmtime-v14.0.4-x86_64-linux/*
echo "$HOME/.wasmtime/bin" >> $GITHUB_PATH echo "$HOME/.wasmtime/bin" >> $GITHUB_PATH
- name: Download release artifact - name: Download release artifact
uses: actions/download-artifact@v4 uses: actions/download-artifact@v3
with: with:
name: linux-amd64-double-zipped name: linux-amd64-double-zipped
- name: Extract release tarball - name: Extract release tarball
@@ -163,7 +161,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v3
with: with:
submodules: true submodules: true
- name: Install apt dependencies - name: Install apt dependencies
@@ -178,14 +176,14 @@ jobs:
simavr \ simavr \
ninja-build ninja-build
- name: Install Go - name: Install Go
uses: actions/setup-go@v5 uses: actions/setup-go@v3
with: with:
go-version: '1.22' go-version: '1.21'
cache: true cache: true
- name: Install Node.js - name: Install Node.js
uses: actions/setup-node@v4 uses: actions/setup-node@v3
with: with:
node-version: '18' node-version: '16'
- name: Install wasmtime - name: Install wasmtime
run: | run: |
mkdir -p $HOME/.wasmtime $HOME/.wasmtime/bin mkdir -p $HOME/.wasmtime $HOME/.wasmtime/bin
@@ -193,10 +191,10 @@ jobs:
tar -C $HOME/.wasmtime/bin --wildcards -xf wasmtime-v14.0.4-x86_64-linux.tar.xz --strip-components=1 wasmtime-v14.0.4-x86_64-linux/* tar -C $HOME/.wasmtime/bin --wildcards -xf wasmtime-v14.0.4-x86_64-linux.tar.xz --strip-components=1 wasmtime-v14.0.4-x86_64-linux/*
echo "$HOME/.wasmtime/bin" >> $GITHUB_PATH echo "$HOME/.wasmtime/bin" >> $GITHUB_PATH
- name: Restore LLVM source cache - name: Restore LLVM source cache
uses: actions/cache/restore@v4 uses: actions/cache/restore@v3
id: cache-llvm-source id: cache-llvm-source
with: with:
key: llvm-source-18-linux-asserts-v1 key: llvm-source-16-linux-asserts-v1
path: | path: |
llvm-project/clang/lib/Headers llvm-project/clang/lib/Headers
llvm-project/clang/include llvm-project/clang/include
@@ -207,7 +205,7 @@ jobs:
if: steps.cache-llvm-source.outputs.cache-hit != 'true' if: steps.cache-llvm-source.outputs.cache-hit != 'true'
run: make llvm-source run: make llvm-source
- name: Save LLVM source cache - name: Save LLVM source cache
uses: actions/cache/save@v4 uses: actions/cache/save@v3
if: steps.cache-llvm-source.outputs.cache-hit != 'true' if: steps.cache-llvm-source.outputs.cache-hit != 'true'
with: with:
key: ${{ steps.cache-llvm-source.outputs.cache-primary-key }} key: ${{ steps.cache-llvm-source.outputs.cache-primary-key }}
@@ -218,10 +216,10 @@ jobs:
llvm-project/lld/include llvm-project/lld/include
llvm-project/llvm/include llvm-project/llvm/include
- name: Restore LLVM build cache - name: Restore LLVM build cache
uses: actions/cache/restore@v4 uses: actions/cache/restore@v3
id: cache-llvm-build id: cache-llvm-build
with: with:
key: llvm-build-18-linux-asserts-v1 key: llvm-build-16-linux-asserts-v1
path: llvm-build path: llvm-build
- name: Build LLVM - name: Build LLVM
if: steps.cache-llvm-build.outputs.cache-hit != 'true' if: steps.cache-llvm-build.outputs.cache-hit != 'true'
@@ -234,13 +232,13 @@ jobs:
# Remove unnecessary object files (to reduce cache size). # Remove unnecessary object files (to reduce cache size).
find llvm-build -name CMakeFiles -prune -exec rm -r '{}' \; find llvm-build -name CMakeFiles -prune -exec rm -r '{}' \;
- name: Save LLVM build cache - name: Save LLVM build cache
uses: actions/cache/save@v4 uses: actions/cache/save@v3
if: steps.cache-llvm-build.outputs.cache-hit != 'true' if: steps.cache-llvm-build.outputs.cache-hit != 'true'
with: with:
key: ${{ steps.cache-llvm-build.outputs.cache-primary-key }} key: ${{ steps.cache-llvm-build.outputs.cache-primary-key }}
path: llvm-build path: llvm-build
- name: Cache Binaryen - name: Cache Binaryen
uses: actions/cache@v4 uses: actions/cache@v3
id: cache-binaryen id: cache-binaryen
with: with:
key: binaryen-linux-asserts-v1 key: binaryen-linux-asserts-v1
@@ -249,10 +247,10 @@ jobs:
if: steps.cache-binaryen.outputs.cache-hit != 'true' if: steps.cache-binaryen.outputs.cache-hit != 'true'
run: make binaryen run: make binaryen
- name: Cache wasi-libc - name: Cache wasi-libc
uses: actions/cache@v4 uses: actions/cache@v3
id: cache-wasi-libc id: cache-wasi-libc
with: with:
key: wasi-libc-sysroot-linux-asserts-v6 key: wasi-libc-sysroot-linux-asserts-v5
path: lib/wasi-libc/sysroot path: lib/wasi-libc/sysroot
- name: Build wasi-libc - name: Build wasi-libc
if: steps.cache-wasi-libc.outputs.cache-hit != 'true' if: steps.cache-wasi-libc.outputs.cache-hit != 'true'
@@ -292,7 +290,7 @@ jobs:
needs: build-linux needs: build-linux
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v3
- name: Install apt dependencies - name: Install apt dependencies
run: | run: |
sudo apt-get update sudo apt-get update
@@ -301,15 +299,15 @@ jobs:
g++-${{ matrix.toolchain }} \ g++-${{ matrix.toolchain }} \
libc6-dev-${{ matrix.libc }}-cross libc6-dev-${{ matrix.libc }}-cross
- name: Install Go - name: Install Go
uses: actions/setup-go@v5 uses: actions/setup-go@v3
with: with:
go-version: '1.22' go-version: '1.21'
cache: true cache: true
- name: Restore LLVM source cache - name: Restore LLVM source cache
uses: actions/cache/restore@v4 uses: actions/cache/restore@v3
id: cache-llvm-source id: cache-llvm-source
with: with:
key: llvm-source-18-linux-v1 key: llvm-source-16-linux-v1
path: | path: |
llvm-project/clang/lib/Headers llvm-project/clang/lib/Headers
llvm-project/clang/include llvm-project/clang/include
@@ -320,7 +318,7 @@ jobs:
if: steps.cache-llvm-source.outputs.cache-hit != 'true' if: steps.cache-llvm-source.outputs.cache-hit != 'true'
run: make llvm-source run: make llvm-source
- name: Save LLVM source cache - name: Save LLVM source cache
uses: actions/cache/save@v4 uses: actions/cache/save@v3
if: steps.cache-llvm-source.outputs.cache-hit != 'true' if: steps.cache-llvm-source.outputs.cache-hit != 'true'
with: with:
key: ${{ steps.cache-llvm-source.outputs.cache-primary-key }} key: ${{ steps.cache-llvm-source.outputs.cache-primary-key }}
@@ -331,10 +329,10 @@ jobs:
llvm-project/lld/include llvm-project/lld/include
llvm-project/llvm/include llvm-project/llvm/include
- name: Restore LLVM build cache - name: Restore LLVM build cache
uses: actions/cache/restore@v4 uses: actions/cache/restore@v3
id: cache-llvm-build id: cache-llvm-build
with: with:
key: llvm-build-18-linux-${{ matrix.goarch }}-v1 key: llvm-build-16-linux-${{ matrix.goarch }}-v1
path: llvm-build path: llvm-build
- name: Build LLVM - name: Build LLVM
if: steps.cache-llvm-build.outputs.cache-hit != 'true' if: steps.cache-llvm-build.outputs.cache-hit != 'true'
@@ -349,22 +347,22 @@ jobs:
# Remove unnecessary object files (to reduce cache size). # Remove unnecessary object files (to reduce cache size).
find llvm-build -name CMakeFiles -prune -exec rm -r '{}' \; find llvm-build -name CMakeFiles -prune -exec rm -r '{}' \;
- name: Save LLVM build cache - name: Save LLVM build cache
uses: actions/cache/save@v4 uses: actions/cache/save@v3
if: steps.cache-llvm-build.outputs.cache-hit != 'true' if: steps.cache-llvm-build.outputs.cache-hit != 'true'
with: with:
key: ${{ steps.cache-llvm-build.outputs.cache-primary-key }} key: ${{ steps.cache-llvm-build.outputs.cache-primary-key }}
path: llvm-build path: llvm-build
- name: Cache Binaryen - name: Cache Binaryen
uses: actions/cache@v4 uses: actions/cache@v3
id: cache-binaryen id: cache-binaryen
with: with:
key: binaryen-linux-${{ matrix.goarch }}-v4 key: binaryen-linux-${{ matrix.goarch }}-v3
path: build/wasm-opt path: build/wasm-opt
- name: Build Binaryen - name: Build Binaryen
if: steps.cache-binaryen.outputs.cache-hit != 'true' if: steps.cache-binaryen.outputs.cache-hit != 'true'
run: | run: |
sudo apt-get install --no-install-recommends ninja-build sudo apt-get install --no-install-recommends ninja-build
git submodule update --init lib/binaryen git submodule update --init --recursive lib/binaryen
make CROSS=${{ matrix.toolchain }} binaryen make CROSS=${{ matrix.toolchain }} binaryen
- name: Install fpm - name: Install fpm
run: | run: |
@@ -375,7 +373,7 @@ jobs:
run: | run: |
make CROSS=${{ matrix.toolchain }} make CROSS=${{ matrix.toolchain }}
- name: Download amd64 release - name: Download amd64 release
uses: actions/download-artifact@v4 uses: actions/download-artifact@v3
with: with:
name: linux-amd64-double-zipped name: linux-amd64-double-zipped
- name: Extract amd64 release - name: Extract amd64 release
@@ -392,7 +390,7 @@ jobs:
cp -p build/release.tar.gz /tmp/tinygo.linux-${{ matrix.goarch }}.tar.gz cp -p build/release.tar.gz /tmp/tinygo.linux-${{ matrix.goarch }}.tar.gz
cp -p build/release.deb /tmp/tinygo_${{ matrix.libc }}.deb cp -p build/release.deb /tmp/tinygo_${{ matrix.libc }}.deb
- name: Publish release artifact - name: Publish release artifact
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v3
with: with:
name: linux-${{ matrix.goarch }}-double-zipped name: linux-${{ matrix.goarch }}-double-zipped
path: | path: |
+7 -7
View File
@@ -25,18 +25,18 @@ jobs:
contents: read contents: read
steps: steps:
- name: Check out the repo - name: Check out the repo
uses: actions/checkout@v4 uses: actions/checkout@v3
with: with:
submodules: recursive submodules: recursive
- name: Set up Docker Buildx - name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3 uses: docker/setup-buildx-action@v2
- name: Docker meta - name: Docker meta
id: meta id: meta
uses: docker/metadata-action@v5 uses: docker/metadata-action@v4
with: with:
images: | images: |
tinygo/llvm-18 tinygo/llvm-16
ghcr.io/${{ github.repository_owner }}/llvm-18 ghcr.io/${{ github.repository_owner }}/llvm-16
tags: | tags: |
type=sha,format=long type=sha,format=long
type=raw,value=latest type=raw,value=latest
@@ -46,13 +46,13 @@ jobs:
username: ${{ secrets.DOCKER_HUB_USERNAME }} username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}
- name: Log in to Github Container Registry - name: Log in to Github Container Registry
uses: docker/login-action@v3 uses: docker/login-action@v2
with: with:
registry: ghcr.io registry: ghcr.io
username: ${{ github.actor }} username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push - name: Build and push
uses: docker/build-push-action@v5 uses: docker/build-push-action@v4
with: with:
target: tinygo-llvm-build target: tinygo-llvm-build
context: . context: .
+4 -4
View File
@@ -16,22 +16,22 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v3
- name: Pull musl - name: Pull musl
run: | run: |
git submodule update --init lib/musl git submodule update --init lib/musl
- name: Restore LLVM source cache - name: Restore LLVM source cache
uses: actions/cache/restore@v4 uses: actions/cache/restore@v3
id: cache-llvm-source id: cache-llvm-source
with: with:
key: llvm-source-18-linux-nix-v1 key: llvm-source-16-linux-nix-v1
path: | path: |
llvm-project/compiler-rt llvm-project/compiler-rt
- name: Download LLVM source - name: Download LLVM source
if: steps.cache-llvm-source.outputs.cache-hit != 'true' if: steps.cache-llvm-source.outputs.cache-hit != 'true'
run: make llvm-source run: make llvm-source
- name: Save LLVM source cache - name: Save LLVM source cache
uses: actions/cache/save@v4 uses: actions/cache/save@v3
if: steps.cache-llvm-source.outputs.cache-hit != 'true' if: steps.cache-llvm-source.outputs.cache-hit != 'true'
with: with:
key: ${{ steps.cache-llvm-source.outputs.cache-primary-key }} key: ${{ steps.cache-llvm-source.outputs.cache-primary-key }}
@@ -1,12 +0,0 @@
# Command that's part of sizediff.yml. This is put in a separate file so that it
# still works after checking out the dev branch (that is, when going from LLVM
# 16 to LLVM 17 for example, both Clang 16 and Clang 17 are installed).
echo 'deb https://apt.llvm.org/jammy/ llvm-toolchain-jammy-18 main' | sudo tee /etc/apt/sources.list.d/llvm.list
wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add -
sudo apt-get update
sudo apt-get install --no-install-recommends -y \
llvm-18-dev \
clang-18 \
libclang-18-dev \
lld-18
+23 -18
View File
@@ -18,26 +18,34 @@ jobs:
run: | run: |
echo "$HOME/go/bin" >> $GITHUB_PATH echo "$HOME/go/bin" >> $GITHUB_PATH
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v3
with: with:
fetch-depth: 0 # fetch all history (no sparse checkout) fetch-depth: 0 # fetch all history (no sparse checkout)
submodules: true submodules: true
- name: Install apt dependencies - name: Install apt dependencies
run: ./.github/workflows/sizediff-install-pkgs.sh run: |
echo 'deb https://apt.llvm.org/jammy/ llvm-toolchain-jammy-16 main' | sudo tee /etc/apt/sources.list.d/llvm.list
wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add -
sudo apt-get update
sudo apt-get install --no-install-recommends -y \
llvm-16-dev \
clang-16 \
libclang-16-dev \
lld-16
- name: Restore LLVM source cache - name: Restore LLVM source cache
uses: actions/cache@v4 uses: actions/cache@v3
id: cache-llvm-source id: cache-llvm-source
with: with:
key: llvm-source-18-sizediff-v1 key: llvm-source-16-sizediff-v1
path: | path: |
llvm-project/compiler-rt llvm-project/compiler-rt
- name: Download LLVM source - name: Download LLVM source
if: steps.cache-llvm-source.outputs.cache-hit != 'true' if: steps.cache-llvm-source.outputs.cache-hit != 'true'
run: make llvm-source run: make llvm-source
- name: Cache Go - name: Cache Go
uses: actions/cache@v4 uses: actions/cache@v3
with: with:
key: go-cache-linux-sizediff-v2-${{ hashFiles('go.mod') }} key: go-cache-linux-sizediff-v1-${{ hashFiles('go.mod') }}
path: | path: |
~/.cache/go-build ~/.cache/go-build
~/go/pkg/mod ~/go/pkg/mod
@@ -47,25 +55,22 @@ jobs:
- name: Save HEAD - name: Save HEAD
run: git branch github-actions-saved-HEAD HEAD run: git branch github-actions-saved-HEAD HEAD
# Compute sizes for the PR branch
- name: Build tinygo binary for the PR branch
run: go install
- name: Determine binary sizes on the PR branch
run: (cd drivers; make smoke-test XTENSA=0 | tee sizes-pr.txt)
# Compute sizes for the dev branch # Compute sizes for the dev branch
- name: Checkout dev branch - name: Checkout dev branch
run: | run: git checkout --no-recurse-submodules `git merge-base HEAD origin/dev`
git reset --hard origin/dev
git checkout --no-recurse-submodules `git merge-base HEAD origin/dev`
- name: Install apt dependencies on the dev branch
# this is only needed on a PR that changes the LLVM version
run: ./.github/workflows/sizediff-install-pkgs.sh
- name: Build tinygo binary for the dev branch - name: Build tinygo binary for the dev branch
run: go install run: go install
- name: Determine binary sizes on the dev branch - name: Determine binary sizes on the dev branch
run: (cd drivers; make smoke-test XTENSA=0 | tee sizes-dev.txt) run: (cd drivers; make smoke-test XTENSA=0 | tee sizes-dev.txt)
# Compute sizes for the PR branch
- name: Checkout PR branch
run: git checkout --no-recurse-submodules github-actions-saved-HEAD
- name: Build tinygo binary for the PR branch
run: go install
- name: Determine binary sizes on the PR branch
run: (cd drivers; make smoke-test XTENSA=0 | tee sizes-pr.txt)
# Create comment # Create comment
# TODO: add a summary, something like: # TODO: add a summary, something like:
# - overall size difference (percent) # - overall size difference (percent)
+28 -28
View File
@@ -16,7 +16,7 @@ jobs:
runs-on: windows-2022 runs-on: windows-2022
steps: steps:
- name: Configure pagefile - name: Configure pagefile
uses: al-cheb/configure-pagefile-action@v1.4 uses: al-cheb/configure-pagefile-action@v1.3
with: with:
minimum-size: 8GB minimum-size: 8GB
maximum-size: 24GB maximum-size: 24GB
@@ -29,19 +29,19 @@ jobs:
run: | run: |
scoop install ninja binaryen scoop install ninja binaryen
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v3
with: with:
submodules: true submodules: true
- name: Install Go - name: Install Go
uses: actions/setup-go@v5 uses: actions/setup-go@v3
with: with:
go-version: '1.22' go-version: '1.21'
cache: true cache: true
- name: Restore cached LLVM source - name: Restore cached LLVM source
uses: actions/cache/restore@v4 uses: actions/cache/restore@v3
id: cache-llvm-source id: cache-llvm-source
with: with:
key: llvm-source-18-windows-v1 key: llvm-source-16-windows-v1
path: | path: |
llvm-project/clang/lib/Headers llvm-project/clang/lib/Headers
llvm-project/clang/include llvm-project/clang/include
@@ -52,7 +52,7 @@ jobs:
if: steps.cache-llvm-source.outputs.cache-hit != 'true' if: steps.cache-llvm-source.outputs.cache-hit != 'true'
run: make llvm-source run: make llvm-source
- name: Save cached LLVM source - name: Save cached LLVM source
uses: actions/cache/save@v4 uses: actions/cache/save@v3
if: steps.cache-llvm-source.outputs.cache-hit != 'true' if: steps.cache-llvm-source.outputs.cache-hit != 'true'
with: with:
key: ${{ steps.cache-llvm-source.outputs.cache-primary-key }} key: ${{ steps.cache-llvm-source.outputs.cache-primary-key }}
@@ -63,10 +63,10 @@ jobs:
llvm-project/lld/include llvm-project/lld/include
llvm-project/llvm/include llvm-project/llvm/include
- name: Restore cached LLVM build - name: Restore cached LLVM build
uses: actions/cache/restore@v4 uses: actions/cache/restore@v3
id: cache-llvm-build id: cache-llvm-build
with: with:
key: llvm-build-18-windows-v1 key: llvm-build-16-windows-v2
path: llvm-build path: llvm-build
- name: Build LLVM - name: Build LLVM
if: steps.cache-llvm-build.outputs.cache-hit != 'true' if: steps.cache-llvm-build.outputs.cache-hit != 'true'
@@ -80,16 +80,16 @@ jobs:
# Remove unnecessary object files (to reduce cache size). # Remove unnecessary object files (to reduce cache size).
find llvm-build -name CMakeFiles -prune -exec rm -r '{}' \; find llvm-build -name CMakeFiles -prune -exec rm -r '{}' \;
- name: Save cached LLVM build - name: Save cached LLVM build
uses: actions/cache/save@v4 uses: actions/cache/save@v3
if: steps.cache-llvm-build.outputs.cache-hit != 'true' if: steps.cache-llvm-build.outputs.cache-hit != 'true'
with: with:
key: ${{ steps.cache-llvm-build.outputs.cache-primary-key }} key: ${{ steps.cache-llvm-build.outputs.cache-primary-key }}
path: llvm-build path: llvm-build
- name: Cache wasi-libc sysroot - name: Cache wasi-libc sysroot
uses: actions/cache@v4 uses: actions/cache@v3
id: cache-wasi-libc id: cache-wasi-libc
with: with:
key: wasi-libc-sysroot-v5 key: wasi-libc-sysroot-v4
path: lib/wasi-libc/sysroot path: lib/wasi-libc/sysroot
- name: Build wasi-libc - name: Build wasi-libc
if: steps.cache-wasi-libc.outputs.cache-hit != 'true' if: steps.cache-wasi-libc.outputs.cache-hit != 'true'
@@ -116,7 +116,7 @@ jobs:
# - have a dobule-zipped artifact when downloaded from the UI # - have a dobule-zipped artifact when downloaded from the UI
# - have a very slow artifact upload # - have a very slow artifact upload
# We're doing the former here, to keep artifact uploads fast. # We're doing the former here, to keep artifact uploads fast.
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v3
with: with:
name: windows-amd64-double-zipped name: windows-amd64-double-zipped
path: build/release/release.zip path: build/release/release.zip
@@ -126,7 +126,7 @@ jobs:
needs: build-windows needs: build-windows
steps: steps:
- name: Configure pagefile - name: Configure pagefile
uses: al-cheb/configure-pagefile-action@v1.4 uses: al-cheb/configure-pagefile-action@v1.3
with: with:
minimum-size: 8GB minimum-size: 8GB
maximum-size: 24GB maximum-size: 24GB
@@ -139,14 +139,14 @@ jobs:
run: | run: |
scoop install binaryen scoop install binaryen
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v3
- name: Install Go - name: Install Go
uses: actions/setup-go@v5 uses: actions/setup-go@v3
with: with:
go-version: '1.22' go-version: '1.21'
cache: true cache: true
- name: Download TinyGo build - name: Download TinyGo build
uses: actions/download-artifact@v4 uses: actions/download-artifact@v2
with: with:
name: windows-amd64-double-zipped name: windows-amd64-double-zipped
path: build/ path: build/
@@ -163,20 +163,20 @@ jobs:
needs: build-windows needs: build-windows
steps: steps:
- name: Configure pagefile - name: Configure pagefile
uses: al-cheb/configure-pagefile-action@v1.4 uses: al-cheb/configure-pagefile-action@v1.3
with: with:
minimum-size: 8GB minimum-size: 8GB
maximum-size: 24GB maximum-size: 24GB
disk-root: "C:" disk-root: "C:"
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v3
- name: Install Go - name: Install Go
uses: actions/setup-go@v5 uses: actions/setup-go@v3
with: with:
go-version: '1.22' go-version: '1.21'
cache: true cache: true
- name: Download TinyGo build - name: Download TinyGo build
uses: actions/download-artifact@v4 uses: actions/download-artifact@v2
with: with:
name: windows-amd64-double-zipped name: windows-amd64-double-zipped
path: build/ path: build/
@@ -192,7 +192,7 @@ jobs:
needs: build-windows needs: build-windows
steps: steps:
- name: Configure pagefile - name: Configure pagefile
uses: al-cheb/configure-pagefile-action@v1.4 uses: al-cheb/configure-pagefile-action@v1.3
with: with:
minimum-size: 8GB minimum-size: 8GB
maximum-size: 24GB maximum-size: 24GB
@@ -205,14 +205,14 @@ jobs:
run: | run: |
scoop install binaryen && scoop install wasmtime@14.0.4 scoop install binaryen && scoop install wasmtime@14.0.4
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v3
- name: Install Go - name: Install Go
uses: actions/setup-go@v5 uses: actions/setup-go@v3
with: with:
go-version: '1.22' go-version: '1.21'
cache: true cache: true
- name: Download TinyGo build - name: Download TinyGo build
uses: actions/download-artifact@v4 uses: actions/download-artifact@v2
with: with:
name: windows-amd64-double-zipped name: windows-amd64-double-zipped
path: build/ path: build/
+2 -7
View File
@@ -9,11 +9,10 @@
url = https://github.com/avr-rust/avr-mcu.git url = https://github.com/avr-rust/avr-mcu.git
[submodule "lib/cmsis-svd"] [submodule "lib/cmsis-svd"]
path = lib/cmsis-svd path = lib/cmsis-svd
url = https://github.com/cmsis-svd/cmsis-svd-data.git url = https://github.com/tinygo-org/cmsis-svd
branch = main
[submodule "lib/wasi-libc"] [submodule "lib/wasi-libc"]
path = lib/wasi-libc path = lib/wasi-libc
url = https://github.com/WebAssembly/wasi-libc url = https://github.com/CraneStation/wasi-libc
[submodule "lib/picolibc"] [submodule "lib/picolibc"]
path = lib/picolibc path = lib/picolibc
url = https://github.com/keith-packard/picolibc.git url = https://github.com/keith-packard/picolibc.git
@@ -35,7 +34,3 @@
[submodule "lib/renesas-svd"] [submodule "lib/renesas-svd"]
path = lib/renesas-svd path = lib/renesas-svd
url = https://github.com/tinygo-org/renesas-svd.git url = https://github.com/tinygo-org/renesas-svd.git
[submodule "src/net"]
path = src/net
url = https://github.com/tinygo-org/net.git
branch = dev
+1 -1
View File
@@ -85,7 +85,7 @@ Now that we have a working static build, it's time to make a release tarball:
If you did not clone the repository with the `--recursive` option, you will get errors until you initialize the project submodules: If you did not clone the repository with the `--recursive` option, you will get errors until you initialize the project submodules:
git submodule update --init git submodule update --init --recursive
The release tarball is stored in build/release.tar.gz, and can be extracted with The release tarball is stored in build/release.tar.gz, and can be extracted with
the following command (for example in ~/lib): the following command (for example in ~/lib):
-102
View File
@@ -1,105 +1,3 @@
0.31.2
---
* **general**
* update the `net` submodule to updated version with `Buffers` implementation
* **compiler**
* `syscall`: add wasm_unknown tag to some additional files so it can compile more code
* **standard library**
* `runtime`: add Frame.Entry field
0.31.1
---
* **general**
* fix Binaryen build in make task
* update final build stage of Docker `dev` image to go1.22
* only use GHA cache for building Docker `dev` image
* update the `net` submodule to latest version
* **compiler**
* `interp`: make getelementptr offsets signed
* `interp`: return a proper error message when indexing out of range
0.31.0
---
* **general**
* remove LLVM 14 support
* add LLVM 17 support, and use it by default
* add Nix flake support
* update bundled Binaryen to version 116
* add `ports` subcommand that lists available serial ports for `-port` and `-monitor`
* support wasmtime version 14
* add `-serial=rtt` for serial output over SWD
* add Go 1.22 support and use it by default
* change minimum Node.js version from 16 to 18
* **compiler**
* use the new LLVM pass manager
* allow systems with more stack space to allocate larger values on the stack
* `build`: fix a crash due to sharing GlobalValues between build instances
* `cgo`: add `C._Bool` type
* `cgo`: fix calling CGo callback inside generic function
* `compileopts`: set `purego` build tag by default so that more packages can be built
* `compileopts`: force-enable CGo to avoid build issues
* `compiler`: fix crash on type assert on interfaces with no methods
* `interp`: print LLVM instruction in traceback
* `interp`: support runtime times by running them at runtime
* `loader`: enforce Go language version in the type checker (this may break existing programs with an incorrect Go version in go.mod)
* `transform`: fix bug in StringToBytes optimization pass
* **standard library**
* `crypto/tls`: stub out a lot of functions
* `internal/task`, `machine`: make TinyGo code usable with "big Go" CGo
* `machine`: implement `I2C.SetBaudRate` consistently across chips
* `machine`: implement `SPI.Configure` consistently across chips
* `machine`: add `DeviceID` for nrf, rp2040, sam, stm32
* `machine`: use smaller UART buffer size on atmega chips
* `machine/usb`: allow setting a serial number using a linker flag
* `math`: support more math functions on baremetal (picolibc) systems
* `net`: replace entire net package with a new one based on the netdev driver
* `os/user`: add bare-bones implementation of this package
* `reflect`: stub `CallSlice` and `FuncOf`
* `reflect`: add `TypeFor[T]`
* `reflect`: update `IsZero` to Go 1.22 semantics
* `reflect`: move indirect values into interface when setting interfaces
* `runtime`: stub `Breakpoint`
* `sync`: implement trylock
* **targets**
* `atmega`: use UART double speed mode for fewer errors and higher throughput
* `atmega328pb`: refactor to enable extra uart
* `avr`: don't compile large parts of picolibc (math, stdio) for LLVM 17 support
* `esp32`: switch over to the official SVD file
* `esp32c3`: implement USB_SERIAL for USBCDC communication
* `esp32c3`: implement I2C
* `esp32c3`: implement RNG
* `esp32c3`: add more ROM functions and update linker script for the in-progress wifi support
* `esp32c3`: update to newer SVD files
* `rp2040`: add support for UART hardware flow control
* `rp2040`: add definition for `machine.PinToggle`
* `rp2040`: set XOSC startup delay multiplier
* `samd21`: add support for UART hardware flow control
* `samd51`: add support for UART hardware flow control
* `wasm`: increase default stack size to 64k for wasi/wasm targets
* `wasm`: bump wasi-libc version to SDK 20
* `wasm`: remove line of dead code in wasm_exec.js
* **new targets/boards**
* `qtpy-esp32c3`: add Adafruit QT Py ESP32-C3 board
* `mksnanov3`: add support for the MKS Robin Nano V3.x
* `nrf52840-generic`: add generic nrf52840 chip support
* `thumby`: add support for Thumby
* `wasm`: add new `wasm-unknown` target that doesn't depend on WASI or a browser
* **boards**
* `arduino-mkrwifi1010`, `arduino-nano33`, `nano-rp2040`, `matrixportal-m4`, `metro-m4-airlift`, `pybadge`, `pyportal`: add `ninafw` build tag and some constants for BLE support
* `gopher-badge`: fix typo in USB product name
* `nano-rp2040`: add UART1 and correct mappings for NINA via UART
* `pico`: bump default stack size from 2kB to 8kB
* `wioterminal`: expose UART4
0.30.0 0.30.0
--- ---
+19 -22
View File
@@ -1,15 +1,10 @@
# tinygo-llvm stage obtains the llvm source for TinyGo # tinygo-llvm stage obtains the llvm source for TinyGo
FROM golang:1.22 AS tinygo-llvm FROM golang:1.21 AS tinygo-llvm
RUN apt-get update && \ RUN apt-get update && \
apt-get install -y apt-utils make cmake clang-15 ninja-build && \ apt-get install -y apt-utils make cmake clang-15 ninja-build
rm -rf \
/var/lib/apt/lists/* \
/var/log/* \
/var/tmp/* \
/tmp/*
COPY ./GNUmakefile /tinygo/GNUmakefile COPY ./Makefile /tinygo/Makefile
RUN cd /tinygo/ && \ RUN cd /tinygo/ && \
make llvm-source make llvm-source
@@ -20,24 +15,26 @@ FROM tinygo-llvm AS tinygo-llvm-build
RUN cd /tinygo/ && \ RUN cd /tinygo/ && \
make llvm-build make llvm-build
# tinygo-compiler-build stage builds the compiler itself # tinygo-compiler stage builds the compiler itself
FROM tinygo-llvm-build AS tinygo-compiler-build FROM tinygo-llvm-build AS tinygo-compiler
COPY . /tinygo COPY . /tinygo
# build the compiler and tools # update submodules
RUN cd /tinygo/ && \ RUN cd /tinygo/ && \
git submodule update --init && \ rm -rf ./lib/*/ && \
git submodule sync && \
git submodule update --init --recursive --force
RUN cd /tinygo/ && \
make
# tinygo-tools stage installs the needed dependencies to compile TinyGo programs for all platforms.
FROM tinygo-compiler AS tinygo-tools
RUN cd /tinygo/ && \
make wasi-libc binaryen && \
make gen-device -j4 && \ make gen-device -j4 && \
make build/release cp build/* $GOPATH/bin/
# tinygo-compiler copies the compiler build over to a base Go container (without
# all the build tools etc).
FROM golang:1.22 AS tinygo-compiler
# Copy tinygo build.
COPY --from=tinygo-compiler-build /tinygo/build/release/tinygo /tinygo
# Configure the container.
ENV PATH="${PATH}:/tinygo/bin"
CMD ["tinygo"] CMD ["tinygo"]
+22 -65
View File
@@ -10,7 +10,7 @@ LLD_SRC ?= $(LLVM_PROJECTDIR)/lld
# Try to autodetect LLVM build tools. # Try to autodetect LLVM build tools.
# Versions are listed here in descending priority order. # Versions are listed here in descending priority order.
LLVM_VERSIONS = 18 17 16 15 LLVM_VERSIONS = 17 16 15
errifempty = $(if $(1),$(1),$(error $(2))) errifempty = $(if $(1),$(1),$(error $(2)))
detect = $(shell which $(call errifempty,$(firstword $(foreach p,$(2),$(shell command -v $(p) 2> /dev/null && echo $(p)))),failed to locate $(1) at any of: $(2))) detect = $(shell which $(call errifempty,$(firstword $(foreach p,$(2),$(shell command -v $(p) 2> /dev/null && echo $(p)))),failed to locate $(1) at any of: $(2)))
toolSearchPathsVersion = $(1)-$(2) toolSearchPathsVersion = $(1)-$(2)
@@ -31,7 +31,6 @@ export GOROOT = $(shell $(GO) env GOROOT)
# Flags to pass to go test. # Flags to pass to go test.
GOTESTFLAGS ?= GOTESTFLAGS ?=
GOTESTPKGS ?= ./builder ./cgo ./compileopts ./compiler ./interp ./transform .
# tinygo binary for tests # tinygo binary for tests
TINYGO ?= $(call detect,tinygo,tinygo $(CURDIR)/build/tinygo) TINYGO ?= $(call detect,tinygo,tinygo $(CURDIR)/build/tinygo)
@@ -111,7 +110,7 @@ endif
.PHONY: all tinygo test $(LLVM_BUILDDIR) llvm-source clean fmt gen-device gen-device-nrf gen-device-nxp gen-device-avr gen-device-rp .PHONY: all tinygo test $(LLVM_BUILDDIR) llvm-source clean fmt gen-device gen-device-nrf gen-device-nxp gen-device-avr gen-device-rp
LLVM_COMPONENTS = all-targets analysis asmparser asmprinter bitreader bitwriter codegen core coroutines coverage debuginfodwarf debuginfopdb executionengine frontenddriver frontendhlsl frontendopenmp instrumentation interpreter ipo irreader libdriver linker lto mc mcjit objcarcopts option profiledata scalaropts support target windowsdriver windowsmanifest LLVM_COMPONENTS = all-targets analysis asmparser asmprinter bitreader bitwriter codegen core coroutines coverage debuginfodwarf debuginfopdb executionengine frontendhlsl frontendopenmp instrumentation interpreter ipo irreader libdriver linker lto mc mcjit objcarcopts option profiledata scalaropts support target windowsdriver windowsmanifest
ifeq ($(OS),Windows_NT) ifeq ($(OS),Windows_NT)
EXE = .exe EXE = .exe
@@ -147,7 +146,7 @@ endif
MD5SUM ?= md5sum MD5SUM ?= md5sum
# Libraries that should be linked in for the statically linked Clang. # Libraries that should be linked in for the statically linked Clang.
CLANG_LIB_NAMES = clangAnalysis clangAPINotes clangAST clangASTMatchers clangBasic clangCodeGen clangCrossTU clangDriver clangDynamicASTMatchers clangEdit clangExtractAPI clangFormat clangFrontend clangFrontendTool clangHandleCXX clangHandleLLVM clangIndex clangLex clangParse clangRewrite clangRewriteFrontend clangSema clangSerialization clangSupport clangTooling clangToolingASTDiff clangToolingCore clangToolingInclusions CLANG_LIB_NAMES = clangAnalysis clangAST clangASTMatchers clangBasic clangCodeGen clangCrossTU clangDriver clangDynamicASTMatchers clangEdit clangExtractAPI clangFormat clangFrontend clangFrontendTool clangHandleCXX clangHandleLLVM clangIndex clangLex clangParse clangRewrite clangRewriteFrontend clangSema clangSerialization clangSupport clangTooling clangToolingASTDiff clangToolingCore clangToolingInclusions
CLANG_LIBS = $(START_GROUP) $(addprefix -l,$(CLANG_LIB_NAMES)) $(END_GROUP) -lstdc++ CLANG_LIBS = $(START_GROUP) $(addprefix -l,$(CLANG_LIB_NAMES)) $(END_GROUP) -lstdc++
# Libraries that should be linked in for the statically linked LLD. # Libraries that should be linked in for the statically linked LLD.
@@ -166,7 +165,7 @@ LIB_NAMES = clang $(CLANG_LIB_NAMES) $(LLD_LIB_NAMES) $(EXTRA_LIB_NAMES)
# library path (for ninja). # library path (for ninja).
# This list also includes a few tools that are necessary as part of the full # This list also includes a few tools that are necessary as part of the full
# TinyGo build. # TinyGo build.
NINJA_BUILD_TARGETS = clang llvm-config llvm-ar llvm-nm lld $(addprefix lib/lib,$(addsuffix .a,$(LIB_NAMES))) NINJA_BUILD_TARGETS = clang llvm-config llvm-ar llvm-nm $(addprefix lib/lib,$(addsuffix .a,$(LIB_NAMES)))
# For static linking. # For static linking.
ifneq ("$(wildcard $(LLVM_BUILDDIR)/bin/llvm-config*)","") ifneq ("$(wildcard $(LLVM_BUILDDIR)/bin/llvm-config*)","")
@@ -191,7 +190,7 @@ gen-device: gen-device-stm32
endif endif
gen-device-avr: gen-device-avr:
@if [ ! -e lib/avr/README.md ]; then echo "Submodules have not been downloaded. Please download them using:\n git submodule update --init"; exit 1; fi @if [ ! -e lib/avr/README.md ]; then echo "Submodules have not been downloaded. Please download them using:\n git submodule update --init --recursive"; exit 1; fi
$(GO) build -o ./build/gen-device-avr ./tools/gen-device-avr/ $(GO) build -o ./build/gen-device-avr ./tools/gen-device-avr/
./build/gen-device-avr lib/avr/packs/atmega src/device/avr/ ./build/gen-device-avr lib/avr/packs/atmega src/device/avr/
./build/gen-device-avr lib/avr/packs/tiny src/device/avr/ ./build/gen-device-avr lib/avr/packs/tiny src/device/avr/
@@ -239,7 +238,7 @@ gen-device-renesas: build/gen-device-svd
# Get LLVM sources. # Get LLVM sources.
$(LLVM_PROJECTDIR)/llvm: $(LLVM_PROJECTDIR)/llvm:
git clone -b tinygo_xtensa_release_18.1.2 --depth=1 https://github.com/tinygo-org/llvm-project $(LLVM_PROJECTDIR) git clone -b xtensa_release_16.x --depth=1 https://github.com/espressif/llvm-project $(LLVM_PROJECTDIR)
llvm-source: $(LLVM_PROJECTDIR)/llvm llvm-source: $(LLVM_PROJECTDIR)/llvm
# Configure LLVM. # Configure LLVM.
@@ -257,7 +256,7 @@ ifneq ($(USE_SYSTEM_BINARYEN),1)
binaryen: build/wasm-opt$(EXE) binaryen: build/wasm-opt$(EXE)
build/wasm-opt$(EXE): build/wasm-opt$(EXE):
mkdir -p build mkdir -p build
cd lib/binaryen && cmake -G Ninja . -DBUILD_STATIC_LIB=ON -DBUILD_TESTS=OFF $(BINARYEN_OPTION) && ninja bin/wasm-opt$(EXE) cd lib/binaryen && cmake -G Ninja . -DBUILD_STATIC_LIB=ON $(BINARYEN_OPTION) && ninja bin/wasm-opt$(EXE)
cp lib/binaryen/bin/wasm-opt$(EXE) build/wasm-opt$(EXE) cp lib/binaryen/bin/wasm-opt$(EXE) build/wasm-opt$(EXE)
endif endif
@@ -265,26 +264,26 @@ endif
.PHONY: wasi-libc .PHONY: wasi-libc
wasi-libc: lib/wasi-libc/sysroot/lib/wasm32-wasi/libc.a wasi-libc: lib/wasi-libc/sysroot/lib/wasm32-wasi/libc.a
lib/wasi-libc/sysroot/lib/wasm32-wasi/libc.a: lib/wasi-libc/sysroot/lib/wasm32-wasi/libc.a:
@if [ ! -e lib/wasi-libc/Makefile ]; then echo "Submodules have not been downloaded. Please download them using:\n git submodule update --init"; exit 1; fi @if [ ! -e lib/wasi-libc/Makefile ]; then echo "Submodules have not been downloaded. Please download them using:\n git submodule update --init --recursive"; exit 1; fi
cd lib/wasi-libc && $(MAKE) -j4 EXTRA_CFLAGS="-O2 -g -DNDEBUG -mnontrapping-fptoint -msign-ext" MALLOC_IMPL=none CC="$(CLANG)" AR=$(LLVM_AR) NM=$(LLVM_NM) cd lib/wasi-libc && $(MAKE) -j4 EXTRA_CFLAGS="-O2 -g -DNDEBUG -mnontrapping-fptoint -msign-ext" MALLOC_IMPL=none CC="$(CLANG)" AR=$(LLVM_AR) NM=$(LLVM_NM)
# Check for Node.js used during WASM tests. # Check for Node.js used during WASM tests.
NODEJS_VERSION := $(word 1,$(subst ., ,$(shell node -v | cut -c 2-))) NODEJS_VERSION := $(word 1,$(subst ., ,$(shell node -v | cut -c 2-)))
MIN_NODEJS_VERSION=18 MIN_NODEJS_VERSION=16
.PHONY: check-nodejs-version .PHONY: check-nodejs-version
check-nodejs-version: check-nodejs-version:
ifeq (, $(shell which node)) ifeq (, $(shell which node))
@echo "Install NodeJS version 18+ to run tests."; exit 1; @echo "Install NodeJS version 16+ to run tests."; exit 1;
endif endif
@if [ $(NODEJS_VERSION) -lt $(MIN_NODEJS_VERSION) ]; then echo "Install NodeJS version 18+ to run tests."; exit 1; fi @if [ $(NODEJS_VERSION) -lt $(MIN_NODEJS_VERSION) ]; then echo "Install NodeJS version 16+ to run tests."; exit 1; fi
# Build the Go compiler. # Build the Go compiler.
tinygo: tinygo:
@if [ ! -f "$(LLVM_BUILDDIR)/bin/llvm-config" ]; then echo "Fetch and build LLVM first by running:"; echo " $(MAKE) llvm-source"; echo " $(MAKE) $(LLVM_BUILDDIR)"; exit 1; fi @if [ ! -f "$(LLVM_BUILDDIR)/bin/llvm-config" ]; then echo "Fetch and build LLVM first by running:"; echo " $(MAKE) llvm-source"; echo " $(MAKE) $(LLVM_BUILDDIR)"; exit 1; fi
CGO_CPPFLAGS="$(CGO_CPPFLAGS)" CGO_CXXFLAGS="$(CGO_CXXFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" $(GOENVFLAGS) $(GO) build -buildmode exe -o build/tinygo$(EXE) -tags "byollvm osusergo" -ldflags="-X github.com/tinygo-org/tinygo/goenv.GitSha1=`git rev-parse --short HEAD`" . CGO_CPPFLAGS="$(CGO_CPPFLAGS)" CGO_CXXFLAGS="$(CGO_CXXFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" $(GOENVFLAGS) $(GO) build -buildmode exe -o build/tinygo$(EXE) -tags "byollvm osusergo" -ldflags="-X github.com/tinygo-org/tinygo/goenv.GitSha1=`git rev-parse --short HEAD`" .
test: wasi-libc check-nodejs-version test: wasi-libc check-nodejs-version
CGO_CPPFLAGS="$(CGO_CPPFLAGS)" CGO_CXXFLAGS="$(CGO_CXXFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" $(GO) test $(GOTESTFLAGS) -timeout=20m -buildmode exe -tags "byollvm osusergo" $(GOTESTPKGS) CGO_CPPFLAGS="$(CGO_CPPFLAGS)" CGO_CXXFLAGS="$(CGO_CXXFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" $(GO) test $(GOTESTFLAGS) -timeout=20m -buildmode exe -tags "byollvm osusergo" ./builder ./cgo ./compileopts ./compiler ./interp ./transform .
# Standard library packages that pass tests on darwin, linux, wasi, and windows, but take over a minute in wasi # Standard library packages that pass tests on darwin, linux, wasi, and windows, but take over a minute in wasi
TEST_PACKAGES_SLOW = \ TEST_PACKAGES_SLOW = \
@@ -427,17 +426,17 @@ tinygo-bench-fast:
# Same thing, except for wasi rather than the current platform. # Same thing, except for wasi rather than the current platform.
tinygo-test-wasi: tinygo-test-wasi:
$(TINYGO) test -target wasip1 $(TEST_PACKAGES_FAST) $(TEST_PACKAGES_SLOW) ./tests/runtime_wasi $(TINYGO) test -target wasi $(TEST_PACKAGES_FAST) $(TEST_PACKAGES_SLOW) ./tests/runtime_wasi
tinygo-test-wasip1: tinygo-test-wasip1:
GOOS=wasip1 GOARCH=wasm $(TINYGO) test $(TEST_PACKAGES_FAST) $(TEST_PACKAGES_SLOW) ./tests/runtime_wasi GOOS=wasip1 GOARCH=wasm $(TINYGO) test $(TEST_PACKAGES_FAST) $(TEST_PACKAGES_SLOW) ./tests/runtime_wasi
tinygo-test-wasi-fast: tinygo-test-wasi-fast:
$(TINYGO) test -target wasip1 $(TEST_PACKAGES_FAST) ./tests/runtime_wasi $(TINYGO) test -target wasi $(TEST_PACKAGES_FAST) ./tests/runtime_wasi
tinygo-test-wasip1-fast: tinygo-test-wasip1-fast:
GOOS=wasip1 GOARCH=wasm $(TINYGO) test $(TEST_PACKAGES_FAST) ./tests/runtime_wasi GOOS=wasip1 GOARCH=wasm $(TINYGO) test $(TEST_PACKAGES_FAST) ./tests/runtime_wasi
tinygo-bench-wasi: tinygo-bench-wasi:
$(TINYGO) test -target wasip1 -bench . $(TEST_PACKAGES_FAST) $(TEST_PACKAGES_SLOW) $(TINYGO) test -target wasi -bench . $(TEST_PACKAGES_FAST) $(TEST_PACKAGES_SLOW)
tinygo-bench-wasi-fast: tinygo-bench-wasi-fast:
$(TINYGO) test -target wasip1 -bench . $(TEST_PACKAGES_FAST) $(TINYGO) test -target wasi -bench . $(TEST_PACKAGES_FAST)
# Test external packages in a large corpus. # Test external packages in a large corpus.
test-corpus: test-corpus:
@@ -445,7 +444,7 @@ test-corpus:
test-corpus-fast: test-corpus-fast:
CGO_CPPFLAGS="$(CGO_CPPFLAGS)" CGO_CXXFLAGS="$(CGO_CXXFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" $(GO) test $(GOTESTFLAGS) -timeout=1h -buildmode exe -tags byollvm -run TestCorpus -short . -corpus=testdata/corpus.yaml CGO_CPPFLAGS="$(CGO_CPPFLAGS)" CGO_CXXFLAGS="$(CGO_CXXFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" $(GO) test $(GOTESTFLAGS) -timeout=1h -buildmode exe -tags byollvm -run TestCorpus -short . -corpus=testdata/corpus.yaml
test-corpus-wasi: wasi-libc test-corpus-wasi: wasi-libc
CGO_CPPFLAGS="$(CGO_CPPFLAGS)" CGO_CXXFLAGS="$(CGO_CXXFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" $(GO) test $(GOTESTFLAGS) -timeout=1h -buildmode exe -tags byollvm -run TestCorpus . -corpus=testdata/corpus.yaml -target=wasip1 CGO_CPPFLAGS="$(CGO_CPPFLAGS)" CGO_CXXFLAGS="$(CGO_CXXFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" $(GO) test $(GOTESTFLAGS) -timeout=1h -buildmode exe -tags byollvm -run TestCorpus . -corpus=testdata/corpus.yaml -target=wasi
tinygo-baremetal: tinygo-baremetal:
# Regression tests that run on a baremetal target and don't fit in either main_test.go or smoketest. # Regression tests that run on a baremetal target and don't fit in either main_test.go or smoketest.
@@ -525,8 +524,6 @@ ifneq ($(WASM), 0)
@$(MD5SUM) test.wasm @$(MD5SUM) test.wasm
$(TINYGO) build -size short -o test.wasm -tags=mch2022 examples/serial $(TINYGO) build -size short -o test.wasm -tags=mch2022 examples/serial
@$(MD5SUM) test.wasm @$(MD5SUM) test.wasm
$(TINYGO) build -size short -o test.wasm -tags=gopher_badge examples/blinky1
@$(MD5SUM) test.wasm
endif endif
# test all targets/boards # test all targets/boards
$(TINYGO) build -size short -o test.hex -target=pca10040-s132v6 examples/blinky1 $(TINYGO) build -size short -o test.hex -target=pca10040-s132v6 examples/blinky1
@@ -601,8 +598,6 @@ endif
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=pca10056-s140v7 examples/blinky1 $(TINYGO) build -size short -o test.hex -target=pca10056-s140v7 examples/blinky1
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=pca10059-s140v7 examples/blinky1
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=reelboard-s140v7 examples/blinky1 $(TINYGO) build -size short -o test.hex -target=reelboard-s140v7 examples/blinky1
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=wioterminal examples/blinky1 $(TINYGO) build -size short -o test.hex -target=wioterminal examples/blinky1
@@ -659,8 +654,6 @@ endif
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=badger2040 examples/blinky1 $(TINYGO) build -size short -o test.hex -target=badger2040 examples/blinky1
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=badger2040-w examples/blinky1
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=tufty2040 examples/blinky1 $(TINYGO) build -size short -o test.hex -target=tufty2040 examples/blinky1
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=thingplus-rp2040 examples/blinky1 $(TINYGO) build -size short -o test.hex -target=thingplus-rp2040 examples/blinky1
@@ -677,8 +670,6 @@ endif
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=ae-rp2040 examples/echo $(TINYGO) build -size short -o test.hex -target=ae-rp2040 examples/echo
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=thumby examples/echo
@$(MD5SUM) test.hex
# test pwm # test pwm
$(TINYGO) build -size short -o test.hex -target=itsybitsy-m0 examples/pwm $(TINYGO) build -size short -o test.hex -target=itsybitsy-m0 examples/pwm
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
@@ -693,8 +684,6 @@ endif
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=feather-nrf52840 examples/usb-midi $(TINYGO) build -size short -o test.hex -target=feather-nrf52840 examples/usb-midi
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=nrf52840-s140v6-uf2-generic examples/serial
@$(MD5SUM) test.hex
ifneq ($(STM32), 0) ifneq ($(STM32), 0)
$(TINYGO) build -size short -o test.hex -target=bluepill examples/blinky1 $(TINYGO) build -size short -o test.hex -target=bluepill examples/blinky1
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
@@ -710,8 +699,6 @@ ifneq ($(STM32), 0)
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=nucleo-l432kc examples/blinky1 $(TINYGO) build -size short -o test.hex -target=nucleo-l432kc examples/blinky1
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=nucleo-l476rg examples/blinky1
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=nucleo-l552ze examples/blinky1 $(TINYGO) build -size short -o test.hex -target=nucleo-l552ze examples/blinky1
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=nucleo-wl55jc examples/blinky1 $(TINYGO) build -size short -o test.hex -target=nucleo-wl55jc examples/blinky1
@@ -730,11 +717,7 @@ ifneq ($(STM32), 0)
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=swan examples/blinky1 $(TINYGO) build -size short -o test.hex -target=swan examples/blinky1
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=mksnanov3 examples/blinky1
@$(MD5SUM) test.hex
endif endif
$(TINYGO) build -size short -o test.hex -target=atmega328pb examples/blinkm
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=atmega1284p examples/serial $(TINYGO) build -size short -o test.hex -target=atmega1284p examples/serial
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=arduino examples/blinky1 $(TINYGO) build -size short -o test.hex -target=arduino examples/blinky1
@@ -768,12 +751,12 @@ ifneq ($(XTENSA), 0)
@$(MD5SUM) test.bin @$(MD5SUM) test.bin
$(TINYGO) build -size short -o test.bin -target m5stick-c examples/serial $(TINYGO) build -size short -o test.bin -target m5stick-c examples/serial
@$(MD5SUM) test.bin @$(MD5SUM) test.bin
$(TINYGO) build -size short -o test.bin -target m5paper examples/serial
@$(MD5SUM) test.bin
$(TINYGO) build -size short -o test.bin -target mch2022 examples/serial $(TINYGO) build -size short -o test.bin -target mch2022 examples/serial
@$(MD5SUM) test.bin @$(MD5SUM) test.bin
endif endif
$(TINYGO) build -size short -o test.bin -target=qtpy-esp32c3 examples/serial $(TINYGO) build -size short -o test.bin -target=esp32c3 examples/serial
@$(MD5SUM) test.bin
$(TINYGO) build -size short -o test.bin -target=esp32c3-12f examples/serial
@$(MD5SUM) test.bin @$(MD5SUM) test.bin
$(TINYGO) build -size short -o test.bin -target=m5stamp-c3 examples/serial $(TINYGO) build -size short -o test.bin -target=m5stamp-c3 examples/serial
@$(MD5SUM) test.bin @$(MD5SUM) test.bin
@@ -786,7 +769,6 @@ endif
ifneq ($(WASM), 0) ifneq ($(WASM), 0)
$(TINYGO) build -size short -o wasm.wasm -target=wasm examples/wasm/export $(TINYGO) build -size short -o wasm.wasm -target=wasm examples/wasm/export
$(TINYGO) build -size short -o wasm.wasm -target=wasm examples/wasm/main $(TINYGO) build -size short -o wasm.wasm -target=wasm examples/wasm/main
$(TINYGO) build -size short -o wasm.wasm -target=wasm-unknown examples/hello-wasm-unknown
endif endif
# test various compiler flags # test various compiler flags
$(TINYGO) build -size short -o test.hex -target=pca10040 -gc=none -scheduler=none examples/blinky1 $(TINYGO) build -size short -o test.hex -target=pca10040 -gc=none -scheduler=none examples/blinky1
@@ -795,8 +777,6 @@ endif
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=pca10040 -serial=none examples/echo $(TINYGO) build -size short -o test.hex -target=pca10040 -serial=none examples/echo
@$(MD5SUM) test.hex @$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=pca10040 -serial=rtt examples/echo
@$(MD5SUM) test.hex
$(TINYGO) build -o test.nro -target=nintendoswitch examples/serial $(TINYGO) build -o test.nro -target=nintendoswitch examples/serial
@$(MD5SUM) test.nro @$(MD5SUM) test.nro
$(TINYGO) build -size short -o test.hex -target=pca10040 -opt=0 ./testdata/stdlib.go $(TINYGO) build -size short -o test.hex -target=pca10040 -opt=0 ./testdata/stdlib.go
@@ -829,9 +809,7 @@ build/release: tinygo gen-device wasi-libc $(if $(filter 1,$(USE_SYSTEM_BINARYEN
@mkdir -p build/release/tinygo/lib/nrfx @mkdir -p build/release/tinygo/lib/nrfx
@mkdir -p build/release/tinygo/lib/picolibc/newlib/libc @mkdir -p build/release/tinygo/lib/picolibc/newlib/libc
@mkdir -p build/release/tinygo/lib/picolibc/newlib/libm @mkdir -p build/release/tinygo/lib/picolibc/newlib/libm
@mkdir -p build/release/tinygo/lib/wasi-libc/libc-bottom-half/headers @mkdir -p build/release/tinygo/lib/wasi-libc
@mkdir -p build/release/tinygo/lib/wasi-libc/libc-top-half/musl/arch
@mkdir -p build/release/tinygo/lib/wasi-libc/libc-top-half/musl/src
@mkdir -p build/release/tinygo/pkg/thumbv6m-unknown-unknown-eabi-cortex-m0 @mkdir -p build/release/tinygo/pkg/thumbv6m-unknown-unknown-eabi-cortex-m0
@mkdir -p build/release/tinygo/pkg/thumbv6m-unknown-unknown-eabi-cortex-m0plus @mkdir -p build/release/tinygo/pkg/thumbv6m-unknown-unknown-eabi-cortex-m0plus
@mkdir -p build/release/tinygo/pkg/thumbv7em-unknown-unknown-eabi-cortex-m4 @mkdir -p build/release/tinygo/pkg/thumbv7em-unknown-unknown-eabi-cortex-m4
@@ -858,7 +836,6 @@ endif
@cp -rp lib/musl/src/include build/release/tinygo/lib/musl/src @cp -rp lib/musl/src/include build/release/tinygo/lib/musl/src
@cp -rp lib/musl/src/internal build/release/tinygo/lib/musl/src @cp -rp lib/musl/src/internal build/release/tinygo/lib/musl/src
@cp -rp lib/musl/src/legacy build/release/tinygo/lib/musl/src @cp -rp lib/musl/src/legacy build/release/tinygo/lib/musl/src
@cp -rp lib/musl/src/linux build/release/tinygo/lib/musl/src
@cp -rp lib/musl/src/malloc build/release/tinygo/lib/musl/src @cp -rp lib/musl/src/malloc build/release/tinygo/lib/musl/src
@cp -rp lib/musl/src/mman build/release/tinygo/lib/musl/src @cp -rp lib/musl/src/mman build/release/tinygo/lib/musl/src
@cp -rp lib/musl/src/math build/release/tinygo/lib/musl/src @cp -rp lib/musl/src/math build/release/tinygo/lib/musl/src
@@ -882,15 +859,7 @@ endif
@cp -rp lib/picolibc/newlib/libm/common build/release/tinygo/lib/picolibc/newlib/libm @cp -rp lib/picolibc/newlib/libm/common build/release/tinygo/lib/picolibc/newlib/libm
@cp -rp lib/picolibc/newlib/libm/math build/release/tinygo/lib/picolibc/newlib/libm @cp -rp lib/picolibc/newlib/libm/math build/release/tinygo/lib/picolibc/newlib/libm
@cp -rp lib/picolibc-stdio.c build/release/tinygo/lib @cp -rp lib/picolibc-stdio.c build/release/tinygo/lib
@cp -rp lib/wasi-libc/libc-bottom-half/headers/public build/release/tinygo/lib/wasi-libc/libc-bottom-half/headers @cp -rp lib/wasi-libc/sysroot build/release/tinygo/lib/wasi-libc/sysroot
@cp -rp lib/wasi-libc/libc-top-half/musl/arch/generic build/release/tinygo/lib/wasi-libc/libc-top-half/musl/arch
@cp -rp lib/wasi-libc/libc-top-half/musl/arch/wasm32 build/release/tinygo/lib/wasi-libc/libc-top-half/musl/arch
@cp -rp lib/wasi-libc/libc-top-half/musl/src/include build/release/tinygo/lib/wasi-libc/libc-top-half/musl/src
@cp -rp lib/wasi-libc/libc-top-half/musl/src/internal build/release/tinygo/lib/wasi-libc/libc-top-half/musl/src
@cp -rp lib/wasi-libc/libc-top-half/musl/src/math build/release/tinygo/lib/wasi-libc/libc-top-half/musl/src
@cp -rp lib/wasi-libc/libc-top-half/musl/src/string build/release/tinygo/lib/wasi-libc/libc-top-half/musl/src
@cp -rp lib/wasi-libc/libc-top-half/musl/include build/release/tinygo/lib/wasi-libc/libc-top-half/musl
@cp -rp lib/wasi-libc/sysroot build/release/tinygo/lib/wasi-libc/sysroot
@cp -rp llvm-project/compiler-rt/lib/builtins build/release/tinygo/lib/compiler-rt-builtins @cp -rp llvm-project/compiler-rt/lib/builtins build/release/tinygo/lib/compiler-rt-builtins
@cp -rp llvm-project/compiler-rt/LICENSE.TXT build/release/tinygo/lib/compiler-rt-builtins @cp -rp llvm-project/compiler-rt/LICENSE.TXT build/release/tinygo/lib/compiler-rt-builtins
@cp -rp src build/release/tinygo/src @cp -rp src build/release/tinygo/src
@@ -917,15 +886,3 @@ ifneq ($(RELEASEONLY), 1)
release: build/release release: build/release
deb: build/release deb: build/release
endif endif
lint:
go run github.com/mgechev/revive -version
# TODO: lint more directories!
# revive.toml isn't flexible enough to filter out just one kind of error from a checker, so do it with grep here.
# Can't use grep with friendly formatter. Plain output isn't too bad, though.
# Use 'grep .' to get rid of stray blank line
go run github.com/mgechev/revive -config revive.toml compiler/... src/{os,reflect}/*.go | grep -v "should have comment or be unexported" | grep '.' | awk '{print}; END {exit NR>0}'
spell:
# Check for typos in comments. Skip git submodules etc.
go run github.com/client9/misspell/cmd/misspell -i 'ackward,devided,extint,inbetween,programmmer,rela' $$( find . -depth 1 -type d | egrep -w -v 'lib|llvm|src/net' )
+3 -3
View File
@@ -41,7 +41,7 @@ tinygo flash -target arduino examples/blinky1
TinyGo is very useful for compiling programs both for use in browsers (WASM) as well as for use on servers and other edge devices (WASI). TinyGo is very useful for compiling programs both for use in browsers (WASM) as well as for use on servers and other edge devices (WASI).
TinyGo programs can run in [Fastly Compute](https://www.fastly.com/documentation/guides/compute/go/), [Fermyon Spin](https://developer.fermyon.com/spin/go-components), [wazero](https://wazero.io/languages/tinygo/) and many other WebAssembly runtimes. TinyGo programs can run in Fastly Compute@Edge (https://developer.fastly.com/learning/compute/go/), Fermyon Spin (https://developer.fermyon.com/spin/go-components), wazero (https://wazero.io/languages/tinygo/) and many other WebAssembly runtimes.
Here is a small TinyGo program for use by a WASI host application: Here is a small TinyGo program for use by a WASI host application:
@@ -54,14 +54,14 @@ func add(x, y uint32) uint32 {
return x + y return x + y
} }
// main is required for the `wasip1` target, even if it isn't used. // main is required for the `wasi` target, even if it isn't used.
func main() {} func main() {}
``` ```
This compiles the above TinyGo program for use on any WASI runtime: This compiles the above TinyGo program for use on any WASI runtime:
```shell ```shell
tinygo build -o main.wasm -target=wasip1 main.go tinygo build -o main.wasm -target=wasi main.go
``` ```
## Installation ## Installation
+6 -16
View File
@@ -78,27 +78,17 @@ func makeArchive(arfile *os.File, objs []string) error {
} else if dbg, err := wasm.Parse(objfile); err == nil { } else if dbg, err := wasm.Parse(objfile); err == nil {
for _, s := range dbg.Sections { for _, s := range dbg.Sections {
switch section := s.(type) { switch section := s.(type) {
case *wasm.SectionLinking: case *wasm.SectionImport:
for _, symbol := range section.Symbols { for _, ln := range section.Entries {
if symbol.Flags&wasm.LinkingSymbolFlagUndefined != 0 {
// Don't list undefined functions. if ln.Kind != wasm.ExtKindFunction {
// Not a function
continue continue
} }
if symbol.Flags&wasm.LinkingSymbolFlagBindingLocal != 0 {
// Don't include local symbols.
continue
}
if symbol.Kind != wasm.LinkingSymbolKindFunction && symbol.Kind != wasm.LinkingSymbolKindData {
// Link functions and data symbols.
// Some data symbols need to be included, such as
// __log_data.
continue
}
// Include in the archive.
symbolTable = append(symbolTable, struct { symbolTable = append(symbolTable, struct {
name string name string
fileIndex int fileIndex int
}{symbol.Name, i}) }{ln.Field, i})
} }
} }
} }
+20 -36
View File
@@ -168,13 +168,6 @@ func Build(pkgName, outpath, tmpdir string, config *compileopts.Config) (BuildRe
return BuildResult{}, errors.New("could not find wasi-libc, perhaps you need to run `make wasi-libc`?") return BuildResult{}, errors.New("could not find wasi-libc, perhaps you need to run `make wasi-libc`?")
} }
libcDependencies = append(libcDependencies, dummyCompileJob(path)) libcDependencies = append(libcDependencies, dummyCompileJob(path))
case "wasmbuiltins":
libcJob, unlock, err := WasmBuiltins.load(config, tmpdir)
if err != nil {
return BuildResult{}, err
}
defer unlock()
libcDependencies = append(libcDependencies, libcJob)
case "mingw-w64": case "mingw-w64":
_, unlock, err := MinGW.load(config, tmpdir) _, unlock, err := MinGW.load(config, tmpdir)
if err != nil { if err != nil {
@@ -204,10 +197,8 @@ func Build(pkgName, outpath, tmpdir string, config *compileopts.Config) (BuildRe
Scheduler: config.Scheduler(), Scheduler: config.Scheduler(),
AutomaticStackSize: config.AutomaticStackSize(), AutomaticStackSize: config.AutomaticStackSize(),
DefaultStackSize: config.StackSize(), DefaultStackSize: config.StackSize(),
MaxStackAlloc: config.MaxStackAlloc(),
NeedsStackObjects: config.NeedsStackObjects(), NeedsStackObjects: config.NeedsStackObjects(),
Debug: !config.Options.SkipDWARF, // emit DWARF except when -internal-nodwarf is passed Debug: !config.Options.SkipDWARF, // emit DWARF except when -internal-nodwarf is passed
PanicStrategy: config.PanicStrategy(),
} }
// Load the target machine, which is the LLVM object that contains all // Load the target machine, which is the LLVM object that contains all
@@ -243,7 +234,6 @@ func Build(pkgName, outpath, tmpdir string, config *compileopts.Config) (BuildRe
// Create the *ssa.Program. This does not yet build the entire SSA of the // Create the *ssa.Program. This does not yet build the entire SSA of the
// program so it's pretty fast and doesn't need to be parallelized. // program so it's pretty fast and doesn't need to be parallelized.
program := lprogram.LoadSSA() program := lprogram.LoadSSA()
program.Build()
// Add jobs to compile each package. // Add jobs to compile each package.
// Packages that have a cache hit will not be compiled again. // Packages that have a cache hit will not be compiled again.
@@ -355,8 +345,8 @@ func Build(pkgName, outpath, tmpdir string, config *compileopts.Config) (BuildRe
packageActionIDJobs[pkg.ImportPath] = packageActionIDJob packageActionIDJobs[pkg.ImportPath] = packageActionIDJob
// Build the SSA for the given package. // Build the SSA for the given package.
//ssaPkg := program.Package(pkg.Pkg) ssaPkg := program.Package(pkg.Pkg)
//ssaPkg.Build() ssaPkg.Build()
// Now create the job to actually build the package. It will exit early // Now create the job to actually build the package. It will exit early
// if the package is already compiled. // if the package is already compiled.
@@ -371,12 +361,7 @@ func Build(pkgName, outpath, tmpdir string, config *compileopts.Config) (BuildRe
if _, err := os.Stat(job.result); err == nil { if _, err := os.Stat(job.result); err == nil {
// Already cached, don't recreate this package. // Already cached, don't recreate this package.
switch pkg.ImportPath { return nil
case "context": // seems to be needed
case "time": // often crashes in this package, so probably needed
default:
return nil
}
} }
// Compile AST to IR. The compiler.CompilePackage function will // Compile AST to IR. The compiler.CompilePackage function will
@@ -523,8 +508,6 @@ func Build(pkgName, outpath, tmpdir string, config *compileopts.Config) (BuildRe
run: func(*compileJob) error { run: func(*compileJob) error {
// Load and link all the bitcode files. This does not yet optimize // Load and link all the bitcode files. This does not yet optimize
// anything, it only links the bitcode files together. // anything, it only links the bitcode files together.
println("exit")
os.Exit(0)
ctx := llvm.NewContext() ctx := llvm.NewContext()
mod = ctx.NewModule("main") mod = ctx.NewModule("main")
for _, pkgJob := range packageJobs { for _, pkgJob := range packageJobs {
@@ -781,7 +764,7 @@ func Build(pkgName, outpath, tmpdir string, config *compileopts.Config) (BuildRe
if sizeLevel >= 2 { if sizeLevel >= 2 {
// Workaround with roughly the same effect as // Workaround with roughly the same effect as
// https://reviews.llvm.org/D119342. // https://reviews.llvm.org/D119342.
// Can hopefully be removed in LLVM 19. // Can hopefully be removed in LLVM 18.
ldflags = append(ldflags, ldflags = append(ldflags,
"-mllvm", "--rotation-max-header-size=0") "-mllvm", "--rotation-max-header-size=0")
} }
@@ -824,8 +807,21 @@ func Build(pkgName, outpath, tmpdir string, config *compileopts.Config) (BuildRe
// Run wasm-opt for wasm binaries // Run wasm-opt for wasm binaries
if arch := strings.Split(config.Triple(), "-")[0]; arch == "wasm32" { if arch := strings.Split(config.Triple(), "-")[0]; arch == "wasm32" {
optLevel, _, _ := config.OptLevel() var opt string
opt := "-" + optLevel switch config.Options.Opt {
case "none", "0":
opt = "-O0"
case "1":
opt = "-O1"
case "2":
opt = "-O2"
case "s":
opt = "-Os"
case "z":
opt = "-Oz"
default:
return fmt.Errorf("unknown opt level: %q", config.Options.Opt)
}
var args []string var args []string
@@ -833,25 +829,13 @@ func Build(pkgName, outpath, tmpdir string, config *compileopts.Config) (BuildRe
args = append(args, "--asyncify") args = append(args, "--asyncify")
} }
exeunopt := result.Executable
if config.Options.Work {
// Keep the work direction around => don't overwrite the .wasm binary with the optimized version
exeunopt += ".pre-wasm-opt"
os.Rename(result.Executable, exeunopt)
}
args = append(args, args = append(args,
opt, opt,
"-g", "-g",
exeunopt, result.Executable,
"--output", result.Executable, "--output", result.Executable,
) )
if config.Options.PrintCommands != nil {
config.Options.PrintCommands(goenv.Get("WASMOPT"), args...)
}
cmd := exec.Command(goenv.Get("WASMOPT"), args...) cmd := exec.Command(goenv.Get("WASMOPT"), args...)
cmd.Stdout = os.Stdout cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr cmd.Stderr = os.Stderr
+1 -2
View File
@@ -33,9 +33,8 @@ func TestClangAttributes(t *testing.T) {
"k210", "k210",
"nintendoswitch", "nintendoswitch",
"riscv-qemu", "riscv-qemu",
"wasip1", "wasi",
"wasm", "wasm",
"wasm-unknown",
} }
if hasBuiltinTools { if hasBuiltinTools {
// hasBuiltinTools is set when TinyGo is statically linked with LLVM, // hasBuiltinTools is set when TinyGo is statically linked with LLVM,
+7 -5
View File
@@ -8,14 +8,14 @@ import (
"github.com/tinygo-org/tinygo/goenv" "github.com/tinygo-org/tinygo/goenv"
) )
// These are the GENERIC_SOURCES according to CMakeList.txt except for // These are the GENERIC_SOURCES according to CMakeList.txt.
// divmodsi4.c and udivmodsi4.c.
var genericBuiltins = []string{ var genericBuiltins = []string{
"absvdi2.c", "absvdi2.c",
"absvsi2.c", "absvsi2.c",
"absvti2.c", "absvti2.c",
"adddf3.c", "adddf3.c",
"addsf3.c", "addsf3.c",
"addtf3.c",
"addvdi3.c", "addvdi3.c",
"addvsi3.c", "addvsi3.c",
"addvti3.c", "addvti3.c",
@@ -40,12 +40,12 @@ var genericBuiltins = []string{
"divdf3.c", "divdf3.c",
"divdi3.c", "divdi3.c",
"divmoddi4.c", "divmoddi4.c",
//"divmodsi4.c",
"divmodti4.c",
"divsc3.c", "divsc3.c",
"divsf3.c", "divsf3.c",
"divsi3.c", "divsi3.c",
"divtc3.c",
"divti3.c", "divti3.c",
"divtf3.c",
"extendsfdf2.c", "extendsfdf2.c",
"extendhfsf2.c", "extendhfsf2.c",
"ffsdi2.c", "ffsdi2.c",
@@ -91,6 +91,7 @@ var genericBuiltins = []string{
"mulsc3.c", "mulsc3.c",
"mulsf3.c", "mulsf3.c",
"multi3.c", "multi3.c",
"multf3.c",
"mulvdi3.c", "mulvdi3.c",
"mulvsi3.c", "mulvsi3.c",
"mulvti3.c", "mulvti3.c",
@@ -110,11 +111,13 @@ var genericBuiltins = []string{
"popcountti2.c", "popcountti2.c",
"powidf2.c", "powidf2.c",
"powisf2.c", "powisf2.c",
"powitf2.c",
"subdf3.c", "subdf3.c",
"subsf3.c", "subsf3.c",
"subvdi3.c", "subvdi3.c",
"subvsi3.c", "subvsi3.c",
"subvti3.c", "subvti3.c",
"subtf3.c",
"trampoline_setup.c", "trampoline_setup.c",
"truncdfhf2.c", "truncdfhf2.c",
"truncdfsf2.c", "truncdfsf2.c",
@@ -123,7 +126,6 @@ var genericBuiltins = []string{
"ucmpti2.c", "ucmpti2.c",
"udivdi3.c", "udivdi3.c",
"udivmoddi4.c", "udivmoddi4.c",
//"udivmodsi4.c",
"udivmodti4.c", "udivmodti4.c",
"udivsi3.c", "udivsi3.c",
"udivti3.c", "udivti3.c",
+13 -25
View File
@@ -1,12 +1,5 @@
//go:build byollvm //go:build byollvm
// Source: https://github.com/llvm/llvm-project/blob/main/clang/tools/driver/cc1as_main.cpp
// This file needs to be updated each LLVM release.
// There are a few small modifications to make, like:
// * ExecuteAssembler is made non-static.
// * The struct AssemblerImplementation is moved to cc1as.h so it can be
// included elsewhere.
//===-- cc1as.cpp - Clang Assembler --------------------------------------===// //===-- cc1as.cpp - Clang Assembler --------------------------------------===//
// //
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
@@ -28,8 +21,8 @@
#include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Frontend/Utils.h" #include "clang/Frontend/Utils.h"
#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Triple.h"
#include "llvm/IR/DataLayout.h" #include "llvm/IR/DataLayout.h"
#include "llvm/MC/MCAsmBackend.h" #include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCAsmInfo.h"
@@ -53,6 +46,7 @@
#include "llvm/Support/ErrorHandling.h" #include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h" #include "llvm/Support/FileSystem.h"
#include "llvm/Support/FormattedStream.h" #include "llvm/Support/FormattedStream.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h" #include "llvm/Support/Path.h"
#include "llvm/Support/Process.h" #include "llvm/Support/Process.h"
@@ -61,8 +55,6 @@
#include "llvm/Support/TargetSelect.h" #include "llvm/Support/TargetSelect.h"
#include "llvm/Support/Timer.h" #include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_ostream.h"
#include "llvm/TargetParser/Host.h"
#include "llvm/TargetParser/Triple.h"
#include <memory> #include <memory>
#include <optional> #include <optional>
#include <system_error> #include <system_error>
@@ -82,10 +74,10 @@ bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
// Parse the arguments. // Parse the arguments.
const OptTable &OptTbl = getDriverOptTable(); const OptTable &OptTbl = getDriverOptTable();
llvm::opt::Visibility VisibilityMask(options::CC1AsOption); const unsigned IncludedFlagsBitmask = options::CC1AsOption;
unsigned MissingArgIndex, MissingArgCount; unsigned MissingArgIndex, MissingArgCount;
InputArgList Args = InputArgList Args = OptTbl.ParseArgs(Argv, MissingArgIndex, MissingArgCount,
OptTbl.ParseArgs(Argv, MissingArgIndex, MissingArgCount, VisibilityMask); IncludedFlagsBitmask);
// Check for missing argument error. // Check for missing argument error.
if (MissingArgCount) { if (MissingArgCount) {
@@ -98,7 +90,7 @@ bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
for (const Arg *A : Args.filtered(OPT_UNKNOWN)) { for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
auto ArgString = A->getAsString(Args); auto ArgString = A->getAsString(Args);
std::string Nearest; std::string Nearest;
if (OptTbl.findNearest(ArgString, Nearest, VisibilityMask) > 1) if (OptTbl.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
Diags.Report(diag::err_drv_unknown_argument) << ArgString; Diags.Report(diag::err_drv_unknown_argument) << ArgString;
else else
Diags.Report(diag::err_drv_unknown_argument_with_suggestion) Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
@@ -159,7 +151,8 @@ bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) { for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
auto Split = StringRef(Arg).split('='); auto Split = StringRef(Arg).split('=');
Opts.DebugPrefixMap.emplace_back(Split.first, Split.second); Opts.DebugPrefixMap.insert(
{std::string(Split.first), std::string(Split.second)});
} }
// Frontend Options // Frontend Options
@@ -232,9 +225,6 @@ bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
.Case("default", EmitDwarfUnwindType::Default); .Case("default", EmitDwarfUnwindType::Default);
} }
Opts.EmitCompactUnwindNonCanonical =
Args.hasArg(OPT_femit_compact_unwind_non_canonical);
Opts.AsSecureLogFile = Args.getLastArgValue(OPT_as_secure_log_file); Opts.AsSecureLogFile = Args.getLastArgValue(OPT_as_secure_log_file);
return Success; return Success;
@@ -270,8 +260,8 @@ static bool ExecuteAssemblerImpl(AssemblerInvocation &Opts,
MemoryBuffer::getFileOrSTDIN(Opts.InputFile, /*IsText=*/true); MemoryBuffer::getFileOrSTDIN(Opts.InputFile, /*IsText=*/true);
if (std::error_code EC = Buffer.getError()) { if (std::error_code EC = Buffer.getError()) {
return Diags.Report(diag::err_fe_error_reading) Error = EC.message();
<< Opts.InputFile << EC.message(); return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
} }
SourceMgr SrcMgr; SourceMgr SrcMgr;
@@ -288,7 +278,6 @@ static bool ExecuteAssemblerImpl(AssemblerInvocation &Opts,
MCTargetOptions MCOptions; MCTargetOptions MCOptions;
MCOptions.EmitDwarfUnwind = Opts.EmitDwarfUnwind; MCOptions.EmitDwarfUnwind = Opts.EmitDwarfUnwind;
MCOptions.EmitCompactUnwindNonCanonical = Opts.EmitCompactUnwindNonCanonical;
MCOptions.AsSecureLogFile = Opts.AsSecureLogFile; MCOptions.AsSecureLogFile = Opts.AsSecureLogFile;
std::unique_ptr<MCAsmInfo> MAI( std::unique_ptr<MCAsmInfo> MAI(
@@ -521,10 +510,9 @@ int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
if (Asm.ShowHelp) { if (Asm.ShowHelp) {
getDriverOptTable().printHelp( getDriverOptTable().printHelp(
llvm::outs(), "clang -cc1as [options] file...", llvm::outs(), "clang -cc1as [options] file...",
"Clang Integrated Assembler", /*ShowHidden=*/false, "Clang Integrated Assembler",
/*ShowAllAliases=*/false, /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0,
llvm::opt::Visibility(driver::options::CC1AsOption)); /*ShowAllAliases=*/false);
return 0; return 0;
} }
+1 -9
View File
@@ -1,6 +1,3 @@
// Source: https://github.com/llvm/llvm-project/blob/main/clang/tools/driver/cc1as_main.cpp
// See cc1as.cpp for details.
//===-- cc1as.h - Clang Assembler ----------------------------------------===// //===-- cc1as.h - Clang Assembler ----------------------------------------===//
// //
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
@@ -47,7 +44,7 @@ struct AssemblerInvocation {
std::string DwarfDebugFlags; std::string DwarfDebugFlags;
std::string DwarfDebugProducer; std::string DwarfDebugProducer;
std::string DebugCompilationDir; std::string DebugCompilationDir;
llvm::SmallVector<std::pair<std::string, std::string>, 0> DebugPrefixMap; std::map<const std::string, const std::string> DebugPrefixMap;
llvm::DebugCompressionType CompressDebugSections = llvm::DebugCompressionType CompressDebugSections =
llvm::DebugCompressionType::None; llvm::DebugCompressionType::None;
std::string MainFileName; std::string MainFileName;
@@ -92,10 +89,6 @@ struct AssemblerInvocation {
/// Whether to emit DWARF unwind info. /// Whether to emit DWARF unwind info.
EmitDwarfUnwindType EmitDwarfUnwind; EmitDwarfUnwindType EmitDwarfUnwind;
// Whether to emit compact-unwind for non-canonical entries.
// Note: maybe overriden by other constraints.
unsigned EmitCompactUnwindNonCanonical : 1;
/// The name of the relocation model to use. /// The name of the relocation model to use.
std::string RelocationModel; std::string RelocationModel;
@@ -135,7 +128,6 @@ public:
DwarfVersion = 0; DwarfVersion = 0;
EmbedBitcode = 0; EmbedBitcode = 0;
EmitDwarfUnwind = EmitDwarfUnwindType::Default; EmitDwarfUnwind = EmitDwarfUnwindType::Default;
EmitCompactUnwindNonCanonical = false;
} }
static bool CreateFromArgs(AssemblerInvocation &Res, static bool CreateFromArgs(AssemblerInvocation &Res,
+1 -1
View File
@@ -11,7 +11,7 @@
#include <clang/FrontendTool/Utils.h> #include <clang/FrontendTool/Utils.h>
#include <llvm/ADT/IntrusiveRefCntPtr.h> #include <llvm/ADT/IntrusiveRefCntPtr.h>
#include <llvm/Option/Option.h> #include <llvm/Option/Option.h>
#include <llvm/TargetParser/Host.h> #include <llvm/Support/Host.h>
using namespace llvm; using namespace llvm;
using namespace clang; using namespace clang;
+2 -2
View File
@@ -27,10 +27,10 @@ func NewConfig(options *compileopts.Options) (*compileopts.Config, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
if major != 1 || minor < 18 || minor > 22 { if major != 1 || minor < 18 || minor > 21 {
// Note: when this gets updated, also update the Go compatibility matrix: // Note: when this gets updated, also update the Go compatibility matrix:
// https://github.com/tinygo-org/tinygo-site/blob/dev/content/docs/reference/go-compat-matrix.md // https://github.com/tinygo-org/tinygo-site/blob/dev/content/docs/reference/go-compat-matrix.md
return nil, fmt.Errorf("requires go version 1.18 through 1.22, got go%d.%d", major, minor) return nil, fmt.Errorf("requires go version 1.18 through 1.21, got go%d.%d", major, minor)
} }
return &compileopts.Config{ return &compileopts.Config{
+21 -10
View File
@@ -5,11 +5,7 @@
#include <lld/Common/Driver.h> #include <lld/Common/Driver.h>
#include <llvm/Support/Parallel.h> #include <llvm/Support/Parallel.h>
LLD_HAS_DRIVER(coff) extern "C" {
LLD_HAS_DRIVER(elf)
LLD_HAS_DRIVER(mingw)
LLD_HAS_DRIVER(macho)
LLD_HAS_DRIVER(wasm)
static void configure() { static void configure() {
#if _WIN64 #if _WIN64
@@ -20,13 +16,28 @@ static void configure() {
#endif #endif
} }
extern "C" { bool tinygo_link_elf(int argc, char **argv) {
bool tinygo_link(int argc, char **argv) {
configure(); configure();
std::vector<const char*> args(argv, argv + argc); std::vector<const char*> args(argv, argv + argc);
lld::Result r = lld::lldMain(args, llvm::outs(), llvm::errs(), LLD_ALL_DRIVERS); return lld::elf::link(args, llvm::outs(), llvm::errs(), false, false);
return !r.retCode; }
bool tinygo_link_macho(int argc, char **argv) {
configure();
std::vector<const char*> args(argv, argv + argc);
return lld::macho::link(args, llvm::outs(), llvm::errs(), false, false);
}
bool tinygo_link_mingw(int argc, char **argv) {
configure();
std::vector<const char*> args(argv, argv + argc);
return lld::mingw::link(args, llvm::outs(), llvm::errs(), false, false);
}
bool tinygo_link_wasm(int argc, char **argv) {
configure();
std::vector<const char*> args(argv, argv + argc);
return lld::wasm::link(args, llvm::outs(), llvm::errs(), false, false);
} }
} // external "C" } // external "C"
-1
View File
@@ -119,7 +119,6 @@ var Musl = Library{
"internal/syscall_ret.c", "internal/syscall_ret.c",
"internal/vdso.c", "internal/vdso.c",
"legacy/*.c", "legacy/*.c",
"linux/*.c",
"malloc/*.c", "malloc/*.c",
"malloc/mallocng/*.c", "malloc/mallocng/*.c",
"mman/*.c", "mman/*.c",
-6
View File
@@ -337,12 +337,6 @@ var picolibcSourcesLarge = []string{
"libm/common/math_err_may_uflow.c", "libm/common/math_err_may_uflow.c",
"libm/common/math_err_check_uflow.c", "libm/common/math_err_check_uflow.c",
"libm/common/math_err_check_oflow.c", "libm/common/math_err_check_oflow.c",
"libm/common/math_errf_divzerof.c",
"libm/common/math_errf_invalidf.c",
"libm/common/math_errf_may_uflowf.c",
"libm/common/math_errf_oflowf.c",
"libm/common/math_errf_uflowf.c",
"libm/common/math_errf_with_errnof.c",
"libm/common/math_inexact.c", "libm/common/math_inexact.c",
"libm/common/math_inexactf.c", "libm/common/math_inexactf.c",
"libm/common/log.c", "libm/common/log.c",
+2 -2
View File
@@ -42,8 +42,8 @@ func TestBinarySize(t *testing.T) {
tests := []sizeTest{ tests := []sizeTest{
// microcontrollers // microcontrollers
{"hifive1b", "examples/echo", 4484, 280, 0, 2252}, {"hifive1b", "examples/echo", 4484, 280, 0, 2252},
{"microbit", "examples/serial", 2732, 388, 8, 2256}, {"microbit", "examples/serial", 2724, 388, 8, 2256},
{"wioterminal", "examples/pininterrupt", 6016, 1484, 116, 6816}, {"wioterminal", "examples/pininterrupt", 6000, 1484, 116, 6816},
// TODO: also check wasm. Right now this is difficult, because // TODO: also check wasm. Right now this is difficult, because
// wasm binaries are run through wasm-opt and therefore the // wasm binaries are run through wasm-opt and therefore the
+27 -4
View File
@@ -12,7 +12,10 @@ import (
#include <stdbool.h> #include <stdbool.h>
#include <stdlib.h> #include <stdlib.h>
bool tinygo_clang_driver(int argc, char **argv); bool tinygo_clang_driver(int argc, char **argv);
bool tinygo_link(int argc, char **argv); bool tinygo_link_elf(int argc, char **argv);
bool tinygo_link_macho(int argc, char **argv);
bool tinygo_link_mingw(int argc, char **argv);
bool tinygo_link_wasm(int argc, char **argv);
*/ */
import "C" import "C"
@@ -23,7 +26,16 @@ const hasBuiltinTools = true
// This version actually runs the tools because TinyGo was compiled while // This version actually runs the tools because TinyGo was compiled while
// linking statically with LLVM (with the byollvm build tag). // linking statically with LLVM (with the byollvm build tag).
func RunTool(tool string, args ...string) error { func RunTool(tool string, args ...string) error {
args = append([]string{tool}, args...) linker := "elf"
if tool == "ld.lld" && len(args) >= 2 {
if args[0] == "-m" && (args[1] == "i386pep" || args[1] == "arm64pe") {
linker = "mingw"
} else if args[0] == "-flavor" {
linker = args[1]
args = args[2:]
}
}
args = append([]string{"tinygo:" + tool}, args...)
var cflag *C.char var cflag *C.char
buf := C.calloc(C.size_t(len(args)), C.size_t(unsafe.Sizeof(cflag))) buf := C.calloc(C.size_t(len(args)), C.size_t(unsafe.Sizeof(cflag)))
@@ -39,8 +51,19 @@ func RunTool(tool string, args ...string) error {
switch tool { switch tool {
case "clang": case "clang":
ok = C.tinygo_clang_driver(C.int(len(args)), (**C.char)(buf)) ok = C.tinygo_clang_driver(C.int(len(args)), (**C.char)(buf))
case "ld.lld", "wasm-ld": case "ld.lld":
ok = C.tinygo_link(C.int(len(args)), (**C.char)(buf)) switch linker {
case "darwin":
ok = C.tinygo_link_macho(C.int(len(args)), (**C.char)(buf))
case "elf":
ok = C.tinygo_link_elf(C.int(len(args)), (**C.char)(buf))
case "mingw":
ok = C.tinygo_link_mingw(C.int(len(args)), (**C.char)(buf))
default:
return errors.New("unknown linker: " + linker)
}
case "wasm-ld":
ok = C.tinygo_link_wasm(C.int(len(args)), (**C.char)(buf))
default: default:
return errors.New("unknown tool: " + tool) return errors.New("unknown tool: " + tool)
} }
-81
View File
@@ -1,81 +0,0 @@
package builder
import (
"os"
"path/filepath"
"github.com/tinygo-org/tinygo/goenv"
)
var WasmBuiltins = Library{
name: "wasmbuiltins",
makeHeaders: func(target, includeDir string) error {
if err := os.Mkdir(includeDir+"/bits", 0o777); err != nil {
return err
}
f, err := os.Create(includeDir + "/bits/alltypes.h")
if err != nil {
return err
}
if _, err := f.Write([]byte(wasmAllTypes)); err != nil {
return err
}
return f.Close()
},
cflags: func(target, headerPath string) []string {
libcDir := filepath.Join(goenv.Get("TINYGOROOT"), "lib/wasi-libc")
return []string{
"-Werror",
"-Wall",
"-std=gnu11",
"-nostdlibinc",
"-isystem", libcDir + "/libc-top-half/musl/arch/wasm32",
"-isystem", libcDir + "/libc-top-half/musl/arch/generic",
"-isystem", libcDir + "/libc-top-half/musl/src/internal",
"-isystem", libcDir + "/libc-top-half/musl/src/include",
"-isystem", libcDir + "/libc-top-half/musl/include",
"-isystem", libcDir + "/libc-bottom-half/headers/public",
"-I" + headerPath,
}
},
sourceDir: func() string { return filepath.Join(goenv.Get("TINYGOROOT"), "lib/wasi-libc") },
librarySources: func(target string) ([]string, error) {
return []string{
// memory builtins needed for llvm.memcpy.*, llvm.memmove.*, and
// llvm.memset.* LLVM intrinsics.
"libc-top-half/musl/src/string/memcpy.c",
"libc-top-half/musl/src/string/memmove.c",
"libc-top-half/musl/src/string/memset.c",
// exp, exp2, and log are needed for LLVM math builtin functions
// like llvm.exp.*.
"libc-top-half/musl/src/math/__math_divzero.c",
"libc-top-half/musl/src/math/__math_invalid.c",
"libc-top-half/musl/src/math/__math_oflow.c",
"libc-top-half/musl/src/math/__math_uflow.c",
"libc-top-half/musl/src/math/__math_xflow.c",
"libc-top-half/musl/src/math/exp.c",
"libc-top-half/musl/src/math/exp_data.c",
"libc-top-half/musl/src/math/exp2.c",
"libc-top-half/musl/src/math/log.c",
"libc-top-half/musl/src/math/log_data.c",
}, nil
},
}
// alltypes.h for wasm-libc, using the types as defined inside Clang.
const wasmAllTypes = `
typedef __SIZE_TYPE__ size_t;
typedef __INT8_TYPE__ int8_t;
typedef __INT16_TYPE__ int16_t;
typedef __INT32_TYPE__ int32_t;
typedef __INT64_TYPE__ int64_t;
typedef __UINT8_TYPE__ uint8_t;
typedef __UINT16_TYPE__ uint16_t;
typedef __UINT32_TYPE__ uint32_t;
typedef __UINT64_TYPE__ uint64_t;
typedef __UINTPTR_TYPE__ uintptr_t;
// This type is used internally in wasi-libc.
typedef double double_t;
`
+2 -10
View File
@@ -25,15 +25,9 @@ import (
"golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/ast/astutil"
) )
// Function that's only defined in Go 1.22.
var setASTFileFields = func(f *ast.File, start, end token.Pos) {
}
// cgoPackage holds all CGo-related information of a package. // cgoPackage holds all CGo-related information of a package.
type cgoPackage struct { type cgoPackage struct {
generated *ast.File generated *ast.File
packageName string
cgoFiles []*ast.File
generatedPos token.Pos generatedPos token.Pos
errors []error errors []error
currentDir string // current working directory currentDir string // current working directory
@@ -171,9 +165,8 @@ func GoBytes(ptr unsafe.Pointer, length C.int) []byte {
// functions), the CFLAGS and LDFLAGS found in #cgo lines, and a map of file // functions), the CFLAGS and LDFLAGS found in #cgo lines, and a map of file
// hashes of the accessed C header files. If there is one or more error, it // hashes of the accessed C header files. If there is one or more error, it
// returns these in the []error slice but still modifies the AST. // returns these in the []error slice but still modifies the AST.
func Process(files []*ast.File, dir, importPath string, fset *token.FileSet, cflags []string) ([]*ast.File, []string, []string, []string, map[string][]byte, []error) { func Process(files []*ast.File, dir, importPath string, fset *token.FileSet, cflags []string) (*ast.File, []string, []string, []string, map[string][]byte, []error) {
p := &cgoPackage{ p := &cgoPackage{
packageName: files[0].Name.Name,
currentDir: dir, currentDir: dir,
importPath: importPath, importPath: importPath,
fset: fset, fset: fset,
@@ -209,7 +202,6 @@ func Process(files []*ast.File, dir, importPath string, fset *token.FileSet, cfl
// This is always a bug in the cgo package. // This is always a bug in the cgo package.
panic("unexpected error: " + err.Error()) panic("unexpected error: " + err.Error())
} }
p.cgoFiles = append(p.cgoFiles, p.generated)
// If the Comments field is not set to nil, the go/format package will get // If the Comments field is not set to nil, the go/format package will get
// confused about where comments should go. // confused about where comments should go.
p.generated.Comments = nil p.generated.Comments = nil
@@ -340,7 +332,7 @@ func Process(files []*ast.File, dir, importPath string, fset *token.FileSet, cfl
// Print the newly generated in-memory AST, for debugging. // Print the newly generated in-memory AST, for debugging.
//ast.Print(fset, p.generated) //ast.Print(fset, p.generated)
return p.cgoFiles, p.cgoHeaders, p.cflags, p.ldflags, p.visitedFiles, p.errors return p.generated, p.cgoHeaders, p.cflags, p.ldflags, p.visitedFiles, p.errors
} }
func (p *cgoPackage) newCGoFile(file *ast.File, index int) *cgoFile { func (p *cgoPackage) newCGoFile(file *ast.File, index int) *cgoFile {
-17
View File
@@ -1,17 +0,0 @@
//go:build go1.22
package cgo
// Code specifically for Go 1.22.
import (
"go/ast"
"go/token"
)
func init() {
setASTFileFields = func(f *ast.File, start, end token.Pos) {
f.FileStart = start
f.FileEnd = end
}
}
+4 -4
View File
@@ -55,7 +55,7 @@ func TestCGo(t *testing.T) {
} }
// Process the AST with CGo. // Process the AST with CGo.
cgoFiles, _, _, _, _, cgoErrors := Process([]*ast.File{f}, "testdata", "main", fset, cflags) cgoAST, _, _, _, _, cgoErrors := Process([]*ast.File{f}, "testdata", "main", fset, cflags)
// Check the AST for type errors. // Check the AST for type errors.
var typecheckErrors []error var typecheckErrors []error
@@ -66,7 +66,7 @@ func TestCGo(t *testing.T) {
Importer: simpleImporter{}, Importer: simpleImporter{},
Sizes: types.SizesFor("gccgo", "arm"), Sizes: types.SizesFor("gccgo", "arm"),
} }
_, err = config.Check("", fset, append([]*ast.File{f}, cgoFiles...), nil) _, err = config.Check("", fset, []*ast.File{f, cgoAST}, nil)
if err != nil && len(typecheckErrors) == 0 { if err != nil && len(typecheckErrors) == 0 {
// Only report errors when no type errors are found (an // Only report errors when no type errors are found (an
// unexpected condition). // unexpected condition).
@@ -91,7 +91,7 @@ func TestCGo(t *testing.T) {
} }
buf.WriteString("\n") buf.WriteString("\n")
} }
err = format.Node(buf, fset, cgoFiles[0]) err = format.Node(buf, fset, cgoAST)
if err != nil { if err != nil {
t.Errorf("could not write out CGo AST: %v", err) t.Errorf("could not write out CGo AST: %v", err)
} }
@@ -216,7 +216,7 @@ func (i simpleImporter) Import(path string) (*types.Package, error) {
} }
} }
// formatDiagnostic formats the error message to be an indented comment. It // formatDiagnostics formats the error message to be an indented comment. It
// also fixes Windows path name issues (backward slashes). // also fixes Windows path name issues (backward slashes).
func formatDiagnostic(err error) string { func formatDiagnostic(err error) string {
msg := err.Error() msg := err.Error()
-7
View File
@@ -589,13 +589,6 @@ func (p *cgoPackage) getClangLocationPosition(location C.CXSourceLocation, tu C.
f := p.fset.AddFile(filename, -1, int(size)) f := p.fset.AddFile(filename, -1, int(size))
f.SetLines(lines) f.SetLines(lines)
p.tokenFiles[filename] = f p.tokenFiles[filename] = f
// Add dummy file AST, to satisfy the type checker.
astFile := &ast.File{
Package: f.Pos(0),
Name: ast.NewIdent(p.packageName),
}
setASTFileFields(astFile, f.Pos(0), f.Pos(int(size)))
p.cgoFiles = append(p.cgoFiles, astFile)
} }
positionFile := p.tokenFiles[filename] positionFile := p.tokenFiles[filename]
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build !byollvm && llvm16 //go:build !byollvm && !llvm15 && !llvm17
package cgo package cgo
-15
View File
@@ -1,15 +0,0 @@
//go:build !byollvm && !llvm15 && !llvm16 && !llvm17
package cgo
/*
#cgo linux CFLAGS: -I/usr/include/llvm-18 -I/usr/include/llvm-c-18 -I/usr/lib/llvm-18/include
#cgo darwin,amd64 CFLAGS: -I/usr/local/opt/llvm@18/include
#cgo darwin,arm64 CFLAGS: -I/opt/homebrew/opt/llvm@18/include
#cgo freebsd CFLAGS: -I/usr/local/llvm18/include
#cgo linux LDFLAGS: -L/usr/lib/llvm-18/lib -lclang
#cgo darwin,amd64 LDFLAGS: -L/usr/local/opt/llvm@18/lib -lclang
#cgo darwin,arm64 LDFLAGS: -L/opt/homebrew/opt/llvm@18/lib -lclang
#cgo freebsd LDFLAGS: -L/usr/local/llvm18/lib -lclang
*/
import "C"
+15 -24
View File
@@ -74,13 +74,7 @@ func (c *Config) GOARM() string {
// BuildTags returns the complete list of build tags used during this build. // BuildTags returns the complete list of build tags used during this build.
func (c *Config) BuildTags() []string { func (c *Config) BuildTags() []string {
tags := append([]string(nil), c.Target.BuildTags...) // copy slice (avoid a race) tags := append(c.Target.BuildTags, []string{"tinygo", "math_big_pure_go", "gc." + c.GC(), "scheduler." + c.Scheduler(), "serial." + c.Serial()}...)
tags = append(tags, []string{
"tinygo", // that's the compiler
"purego", // to get various crypto packages to work
"math_big_pure_go", // to get math/big to work
"gc." + c.GC(), "scheduler." + c.Scheduler(), // used inside the runtime package
"serial." + c.Serial()}...) // used inside the machine package
for i := 1; i <= c.GoMinorVersion; i++ { for i := 1; i <= c.GoMinorVersion; i++ {
tags = append(tags, fmt.Sprintf("go1.%d", i)) tags = append(tags, fmt.Sprintf("go1.%d", i))
} }
@@ -88,6 +82,12 @@ func (c *Config) BuildTags() []string {
return tags return tags
} }
// CgoEnabled returns true if (and only if) CGo is enabled. It is true by
// default and false if CGO_ENABLED is set to "0".
func (c *Config) CgoEnabled() bool {
return goenv.Get("CGO_ENABLED") == "1"
}
// GC returns the garbage collection strategy in use on this platform. Valid // GC returns the garbage collection strategy in use on this platform. Valid
// values are "none", "leaking", "conservative" and "precise". // values are "none", "leaking", "conservative" and "precise".
func (c *Config) GC() string { func (c *Config) GC() string {
@@ -189,15 +189,6 @@ func (c *Config) StackSize() uint64 {
return c.Target.DefaultStackSize return c.Target.DefaultStackSize
} }
// MaxStackAlloc returns the size of the maximum allocation to put on the stack vs heap.
func (c *Config) MaxStackAlloc() uint64 {
if c.StackSize() > 32*1024 {
return 1024
}
return 256
}
// RP2040BootPatch returns whether the RP2040 boot patch should be applied that // RP2040BootPatch returns whether the RP2040 boot patch should be applied that
// calculates and patches in the checksum for the 2nd stage bootloader. // calculates and patches in the checksum for the 2nd stage bootloader.
func (c *Config) RP2040BootPatch() bool { func (c *Config) RP2040BootPatch() bool {
@@ -281,6 +272,10 @@ func (c *Config) CFlags(libclang bool) []string {
cflags = append(cflags, cflags = append(cflags,
"-resource-dir="+resourceDir, "-resource-dir="+resourceDir,
) )
if strings.HasPrefix(c.Triple(), "xtensa") {
// workaround needed in LLVM 16, see: https://github.com/espressif/llvm-project/issues/83
cflags = append(cflags, "-isystem", filepath.Join(resourceDir, "include"))
}
} }
switch c.Target.Libc { switch c.Target.Libc {
case "darwin-libSystem": case "darwin-libSystem":
@@ -311,11 +306,7 @@ func (c *Config) CFlags(libclang bool) []string {
) )
case "wasi-libc": case "wasi-libc":
root := goenv.Get("TINYGOROOT") root := goenv.Get("TINYGOROOT")
cflags = append(cflags, cflags = append(cflags, "--sysroot="+root+"/lib/wasi-libc/sysroot")
"-nostdlibinc",
"-isystem", root+"/lib/wasi-libc/sysroot/include")
case "wasmbuiltins":
// nothing to add (library is purely for builtins)
case "mingw-w64": case "mingw-w64":
root := goenv.Get("TINYGOROOT") root := goenv.Get("TINYGOROOT")
path, _ := c.LibcPath("mingw-w64") path, _ := c.LibcPath("mingw-w64")
@@ -480,6 +471,9 @@ func (c *Config) OpenOCDConfiguration() (args []string, err error) {
return nil, fmt.Errorf("unknown OpenOCD transport: %#v", c.Target.OpenOCDTransport) return nil, fmt.Errorf("unknown OpenOCD transport: %#v", c.Target.OpenOCDTransport)
} }
args = []string{"-f", "interface/" + openocdInterface + ".cfg"} args = []string{"-f", "interface/" + openocdInterface + ".cfg"}
for _, cmd := range c.Target.OpenOCDCommands {
args = append(args, "-c", cmd)
}
if c.Target.OpenOCDTransport != "" { if c.Target.OpenOCDTransport != "" {
transport := c.Target.OpenOCDTransport transport := c.Target.OpenOCDTransport
if transport == "swd" { if transport == "swd" {
@@ -491,9 +485,6 @@ func (c *Config) OpenOCDConfiguration() (args []string, err error) {
args = append(args, "-c", "transport select "+transport) args = append(args, "-c", "transport select "+transport)
} }
args = append(args, "-f", "target/"+c.Target.OpenOCDTarget+".cfg") args = append(args, "-f", "target/"+c.Target.OpenOCDTarget+".cfg")
for _, cmd := range c.Target.OpenOCDCommands {
args = append(args, "-c", cmd)
}
return args, nil return args, nil
} }
+2 -2
View File
@@ -10,7 +10,7 @@ import (
var ( var (
validGCOptions = []string{"none", "leaking", "conservative", "custom", "precise"} validGCOptions = []string{"none", "leaking", "conservative", "custom", "precise"}
validSchedulerOptions = []string{"none", "tasks", "asyncify"} validSchedulerOptions = []string{"none", "tasks", "asyncify"}
validSerialOptions = []string{"none", "uart", "usb", "rtt"} validSerialOptions = []string{"none", "uart", "usb"}
validPrintSizeOptions = []string{"none", "short", "full"} validPrintSizeOptions = []string{"none", "short", "full"}
validPanicStrategyOptions = []string{"print", "trap"} validPanicStrategyOptions = []string{"print", "trap"}
validOptOptions = []string{"none", "0", "1", "2", "s", "z"} validOptOptions = []string{"none", "0", "1", "2", "s", "z"}
@@ -23,7 +23,6 @@ type Options struct {
GOOS string // environment variable GOOS string // environment variable
GOARCH string // environment variable GOARCH string // environment variable
GOARM string // environment variable (only used with GOARCH=arm) GOARM string // environment variable (only used with GOARCH=arm)
Directory string // working dir, leave it unset to use the current working dir
Target string Target string
Opt string Opt string
GC string GC string
@@ -49,6 +48,7 @@ type Options struct {
Programmer string Programmer string
OpenOCDCommands []string OpenOCDCommands []string
LLVMFeatures string LLVMFeatures string
Directory string
PrintJSON bool PrintJSON bool
Monitor bool Monitor bool
BaudRate int BaudRate int
+6 -22
View File
@@ -26,7 +26,7 @@ type TargetSpec struct {
Inherits []string `json:"inherits,omitempty"` Inherits []string `json:"inherits,omitempty"`
Triple string `json:"llvm-target,omitempty"` Triple string `json:"llvm-target,omitempty"`
CPU string `json:"cpu,omitempty"` CPU string `json:"cpu,omitempty"`
ABI string `json:"target-abi,omitempty"` // roughly equivalent to -mabi= flag ABI string `json:"target-abi,omitempty"` // rougly equivalent to -mabi= flag
Features string `json:"features,omitempty"` Features string `json:"features,omitempty"`
GOOS string `json:"goos,omitempty"` GOOS string `json:"goos,omitempty"`
GOARCH string `json:"goarch,omitempty"` GOARCH string `json:"goarch,omitempty"`
@@ -301,10 +301,10 @@ func defaultTarget(goos, goarch, triple string) (*TargetSpec, error) {
switch goarch { switch goarch {
case "386": case "386":
spec.CPU = "pentium4" spec.CPU = "pentium4"
spec.Features = "+cmov,+cx8,+fxsr,+mmx,+sse,+sse2,+x87" spec.Features = "+cx8,+fxsr,+mmx,+sse,+sse2,+x87"
case "amd64": case "amd64":
spec.CPU = "x86-64" spec.CPU = "x86-64"
spec.Features = "+cmov,+cx8,+fxsr,+mmx,+sse,+sse2,+x87" spec.Features = "+cx8,+fxsr,+mmx,+sse,+sse2,+x87"
case "arm": case "arm":
spec.CPU = "generic" spec.CPU = "generic"
spec.CFlags = append(spec.CFlags, "-fno-unwind-tables", "-fno-asynchronous-unwind-tables") spec.CFlags = append(spec.CFlags, "-fno-unwind-tables", "-fno-asynchronous-unwind-tables")
@@ -319,11 +319,9 @@ func defaultTarget(goos, goarch, triple string) (*TargetSpec, error) {
case "arm64": case "arm64":
spec.CPU = "generic" spec.CPU = "generic"
if goos == "darwin" { if goos == "darwin" {
spec.Features = "+fp-armv8,+neon" spec.Features = "+neon"
} else if goos == "windows" { } else { // windows, linux
spec.Features = "+fp-armv8,+neon,-fmv" spec.Features = "+neon,-fmv"
} else { // linux
spec.Features = "+fp-armv8,+neon,-fmv,-outline-atomics"
} }
case "wasm": case "wasm":
spec.CPU = "generic" spec.CPU = "generic"
@@ -351,20 +349,6 @@ func defaultTarget(goos, goarch, triple string) (*TargetSpec, error) {
spec.RTLib = "compiler-rt" spec.RTLib = "compiler-rt"
spec.Libc = "musl" spec.Libc = "musl"
spec.LDFlags = append(spec.LDFlags, "--gc-sections") spec.LDFlags = append(spec.LDFlags, "--gc-sections")
if goarch == "arm64" {
// Disable outline atomics. For details, see:
// https://cpufun.substack.com/p/atomics-in-aarch64
// A better way would be to fully support outline atomics, which
// makes atomics slightly more efficient on systems with many cores.
// But the instructions are only supported on newer aarch64 CPUs, so
// this feature is normally put in a system library which does
// feature detection for you.
// We take the lazy way out and simply disable this feature, instead
// of enabling it in compiler-rt (which is a bit more complicated).
// We don't really need this feature anyway as we don't even support
// proper threading.
spec.CFlags = append(spec.CFlags, "-mno-outline-atomics")
}
} else if goos == "windows" { } else if goos == "windows" {
spec.Linker = "ld.lld" spec.Linker = "ld.lld"
spec.Libc = "mingw-w64" spec.Libc = "mingw-w64"
+2 -6
View File
@@ -16,18 +16,14 @@ import "tinygo.org/x/go-llvm"
var stdlibAliases = map[string]string{ var stdlibAliases = map[string]string{
// crypto packages // crypto packages
"crypto/ed25519/internal/edwards25519/field.feMul": "crypto/ed25519/internal/edwards25519/field.feMulGeneric", "crypto/ed25519/internal/edwards25519/field.feMul": "crypto/ed25519/internal/edwards25519/field.feMulGeneric",
"crypto/internal/edwards25519/field.feSquare": "crypto/ed25519/internal/edwards25519/field.feSquareGeneric", "crypto/ed25519/internal/edwards25519/field.feSquare": "crypto/ed25519/internal/edwards25519/field.feSquareGeneric",
"crypto/md5.block": "crypto/md5.blockGeneric", "crypto/md5.block": "crypto/md5.blockGeneric",
"crypto/sha1.block": "crypto/sha1.blockGeneric", "crypto/sha1.block": "crypto/sha1.blockGeneric",
"crypto/sha1.blockAMD64": "crypto/sha1.blockGeneric", "crypto/sha1.blockAMD64": "crypto/sha1.blockGeneric",
"crypto/sha256.block": "crypto/sha256.blockGeneric", "crypto/sha256.block": "crypto/sha256.blockGeneric",
"crypto/sha512.blockAMD64": "crypto/sha512.blockGeneric", "crypto/sha512.blockAMD64": "crypto/sha512.blockGeneric",
// AES
"crypto/aes.decryptBlockAsm": "crypto/aes.decryptBlock",
"crypto/aes.encryptBlockAsm": "crypto/aes.encryptBlock",
// math package // math package
"math.archHypot": "math.hypot", "math.archHypot": "math.hypot",
"math.archMax": "math.max", "math.archMax": "math.max",
+2 -2
View File
@@ -135,7 +135,7 @@ func (b *builder) createChanBoundsCheck(elementSize uint64, bufSize llvm.Value,
// Calculate (^uintptr(0)) >> 1, which is the max value that fits in an // Calculate (^uintptr(0)) >> 1, which is the max value that fits in an
// uintptr if uintptrs were signed. // uintptr if uintptrs were signed.
maxBufSize := b.CreateLShr(llvm.ConstNot(llvm.ConstInt(b.uintptrType, 0, false)), llvm.ConstInt(b.uintptrType, 1, false), "") maxBufSize := llvm.ConstLShr(llvm.ConstNot(llvm.ConstInt(b.uintptrType, 0, false)), llvm.ConstInt(b.uintptrType, 1, false))
if elementSize > maxBufSize.ZExtValue() { if elementSize > maxBufSize.ZExtValue() {
b.addError(pos, fmt.Sprintf("channel element type is too big (%v bytes)", elementSize)) b.addError(pos, fmt.Sprintf("channel element type is too big (%v bytes)", elementSize))
return return
@@ -150,7 +150,7 @@ func (b *builder) createChanBoundsCheck(elementSize uint64, bufSize llvm.Value,
// Make sure maxBufSize has the same type as bufSize. // Make sure maxBufSize has the same type as bufSize.
if maxBufSize.Type() != bufSize.Type() { if maxBufSize.Type() != bufSize.Type() {
maxBufSize = b.CreateZExt(maxBufSize, bufSize.Type(), "") maxBufSize = llvm.ConstZExt(maxBufSize, bufSize.Type())
} }
// Do the check for a too large (or negative) buffer size. // Do the check for a too large (or negative) buffer size.
+5 -18
View File
@@ -53,10 +53,8 @@ type Config struct {
Scheduler string Scheduler string
AutomaticStackSize bool AutomaticStackSize bool
DefaultStackSize uint64 DefaultStackSize uint64
MaxStackAlloc uint64
NeedsStackObjects bool NeedsStackObjects bool
Debug bool // Whether to emit debug information in the LLVM module. Debug bool // Whether to emit debug information in the LLVM module.
PanicStrategy string
} }
// compilerContext contains function-independent data that should still be // compilerContext contains function-independent data that should still be
@@ -1856,13 +1854,6 @@ func (b *builder) createFunctionCall(instr *ssa.CallCommon) (llvm.Value, error)
supportsRecover = 1 supportsRecover = 1
} }
return llvm.ConstInt(b.ctx.Int1Type(), supportsRecover, false), nil return llvm.ConstInt(b.ctx.Int1Type(), supportsRecover, false), nil
case name == "runtime.panicStrategy":
// These constants are defined in src/runtime/panic.go.
panicStrategy := map[string]uint64{
"print": 1, // panicStrategyPrint
"trap": 2, // panicStrategyTrap
}[b.Config.PanicStrategy]
return llvm.ConstInt(b.ctx.Int8Type(), panicStrategy, false), nil
case name == "runtime/interrupt.New": case name == "runtime/interrupt.New":
return b.createInterruptGlobal(instr) return b.createInterruptGlobal(instr)
} }
@@ -2006,8 +1997,8 @@ func (b *builder) createExpr(expr ssa.Value) (llvm.Value, error) {
case *ssa.Alloc: case *ssa.Alloc:
typ := b.getLLVMType(expr.Type().Underlying().(*types.Pointer).Elem()) typ := b.getLLVMType(expr.Type().Underlying().(*types.Pointer).Elem())
size := b.targetData.TypeAllocSize(typ) size := b.targetData.TypeAllocSize(typ)
// Move all "large" allocations to the heap. // Move all "large" allocations to the heap. This value is also transform.maxStackAlloc.
if expr.Heap || size > b.MaxStackAlloc { if expr.Heap || size > 256 {
// Calculate ^uintptr(0) // Calculate ^uintptr(0)
maxSize := llvm.ConstNot(llvm.ConstInt(b.uintptrType, 0, false)).ZExtValue() maxSize := llvm.ConstNot(llvm.ConstInt(b.uintptrType, 0, false)).ZExtValue()
if size > maxSize { if size > maxSize {
@@ -2181,7 +2172,7 @@ func (b *builder) createExpr(expr ssa.Value) (llvm.Value, error) {
return llvm.Value{}, b.makeError(expr.Pos(), "todo: indexaddr: "+ptrTyp.String()) return llvm.Value{}, b.makeError(expr.Pos(), "todo: indexaddr: "+ptrTyp.String())
} }
// Make sure index is at least the size of uintptr because getelementptr // Make sure index is at least the size of uintptr becuase getelementptr
// assumes index is a signed integer. // assumes index is a signed integer.
index = b.extendInteger(index, expr.Index.Type(), b.uintptrType) index = b.extendInteger(index, expr.Index.Type(), b.uintptrType)
@@ -2557,7 +2548,7 @@ func (b *builder) createBinOp(op token.Token, typ, ytyp types.Type, x, y llvm.Va
sizeY := b.targetData.TypeAllocSize(y.Type()) sizeY := b.targetData.TypeAllocSize(y.Type())
// Check if the shift is bigger than the bit-width of the shifted value. // Check if the shift is bigger than the bit-width of the shifted value.
// This is UB in LLVM, so it needs to be handled separately. // This is UB in LLVM, so it needs to be handled seperately.
// The Go spec indirectly defines the result as 0. // The Go spec indirectly defines the result as 0.
// Negative shifts are handled earlier, so we can treat y as unsigned. // Negative shifts are handled earlier, so we can treat y as unsigned.
overshifted := b.CreateICmp(llvm.IntUGE, y, llvm.ConstInt(y.Type(), 8*sizeX, false), "shift.overflow") overshifted := b.CreateICmp(llvm.IntUGE, y, llvm.ConstInt(y.Type(), 8*sizeX, false), "shift.overflow")
@@ -3270,11 +3261,7 @@ func (b *builder) createUnOp(unop *ssa.UnOp) (llvm.Value, error) {
// Instead of a load from the global, create a bitcast of the // Instead of a load from the global, create a bitcast of the
// function pointer itself. // function pointer itself.
name := strings.TrimSuffix(unop.X.(*ssa.Global).Name(), "$funcaddr") name := strings.TrimSuffix(unop.X.(*ssa.Global).Name(), "$funcaddr")
pkg := b.fn.Pkg _, fn := b.getFunction(b.fn.Pkg.Members[name].(*ssa.Function))
if pkg == nil {
pkg = b.fn.Origin().Pkg
}
_, fn := b.getFunction(pkg.Members[name].(*ssa.Function))
if fn.IsNil() { if fn.IsNil() {
return llvm.Value{}, b.makeError(unop.Pos(), "cgo function not found: "+name) return llvm.Value{}, b.makeError(unop.Pos(), "cgo function not found: "+name)
} }
+18 -27
View File
@@ -124,19 +124,16 @@ func (c *compilerContext) pkgPathPtr(pkgpath string) llvm.Value {
func (c *compilerContext) getTypeCode(typ types.Type) llvm.Value { func (c *compilerContext) getTypeCode(typ types.Type) llvm.Value {
ms := c.program.MethodSets.MethodSet(typ) ms := c.program.MethodSets.MethodSet(typ)
hasMethodSet := ms.Len() != 0 hasMethodSet := ms.Len() != 0
_, isInterface := typ.Underlying().(*types.Interface) if _, ok := typ.Underlying().(*types.Interface); ok {
if isInterface {
hasMethodSet = false hasMethodSet = false
} }
// As defined in https://pkg.go.dev/reflect#Type:
// NumMethod returns the number of methods accessible using Method.
// For a non-interface type, it returns the number of exported methods.
// For an interface type, it returns the number of exported and unexported methods.
var numMethods int var numMethods int
for i := 0; i < ms.Len(); i++ { if hasMethodSet {
if isInterface || ms.At(i).Obj().Exported() { for i := 0; i < ms.Len(); i++ {
numMethods++ if ms.At(i).Obj().Exported() {
numMethods++
}
} }
} }
@@ -687,25 +684,19 @@ func (b *builder) createTypeAssert(expr *ssa.TypeAssert) llvm.Value {
actualTypeNum := b.CreateExtractValue(itf, 0, "interface.type") actualTypeNum := b.CreateExtractValue(itf, 0, "interface.type")
commaOk := llvm.Value{} commaOk := llvm.Value{}
if _, ok := expr.AssertedType.Underlying().(*types.Interface); ok {
// Type assert on interface type.
// This is a call to an interface type assert function.
// The interface lowering pass will define this function by filling it
// with a type switch over all concrete types that implement this
// interface, and returning whether it's one of the matched types.
// This is very different from how interface asserts are implemented in
// the main Go compiler, where the runtime checks whether the type
// implements each method of the interface. See:
// https://research.swtch.com/interfaces
fn := b.getInterfaceImplementsFunc(expr.AssertedType)
commaOk = b.CreateCall(fn.GlobalValueType(), fn, []llvm.Value{actualTypeNum}, "")
if intf, ok := expr.AssertedType.Underlying().(*types.Interface); ok {
if intf.Empty() {
// intf is the empty interface => no methods
// This type assertion always succeeds, so we can just set commaOk to true.
commaOk = llvm.ConstInt(b.ctx.Int1Type(), 1, true)
} else {
// Type assert on interface type with methods.
// This is a call to an interface type assert function.
// The interface lowering pass will define this function by filling it
// with a type switch over all concrete types that implement this
// interface, and returning whether it's one of the matched types.
// This is very different from how interface asserts are implemented in
// the main Go compiler, where the runtime checks whether the type
// implements each method of the interface. See:
// https://research.swtch.com/interfaces
fn := b.getInterfaceImplementsFunc(expr.AssertedType)
commaOk = b.CreateCall(fn.GlobalValueType(), fn, []llvm.Value{actualTypeNum}, "")
}
} else { } else {
name, _ := getTypeCodeName(expr.AssertedType) name, _ := getTypeCodeName(expr.AssertedType)
globalName := "reflect/types.typeid:" + name globalName := "reflect/types.typeid:" + name
-10
View File
@@ -23,8 +23,6 @@ func (b *builder) defineIntrinsicFunction() {
b.createMemoryCopyImpl() b.createMemoryCopyImpl()
case name == "runtime.memzero": case name == "runtime.memzero":
b.createMemoryZeroImpl() b.createMemoryZeroImpl()
case name == "runtime.stacksave":
b.createStackSaveImpl()
case name == "runtime.KeepAlive": case name == "runtime.KeepAlive":
b.createKeepAliveImpl() b.createKeepAliveImpl()
case strings.HasPrefix(name, "runtime/volatile.Load"): case strings.HasPrefix(name, "runtime/volatile.Load"):
@@ -79,14 +77,6 @@ func (b *builder) createMemoryZeroImpl() {
b.CreateRetVoid() b.CreateRetVoid()
} }
// createStackSaveImpl creates a call to llvm.stacksave.p0 to read the current
// stack pointer.
func (b *builder) createStackSaveImpl() {
b.createFunctionStart(true)
sp := b.readStackPointer()
b.CreateRet(sp)
}
// Return the llvm.memset.p0.i8 function declaration. // Return the llvm.memset.p0.i8 function declaration.
func (c *compilerContext) getMemsetFunc() llvm.Value { func (c *compilerContext) getMemsetFunc() llvm.Value {
fnName := "llvm.memset.p0.i" + strconv.Itoa(c.uintptrType.IntTypeWidth()) fnName := "llvm.memset.p0.i" + strconv.Itoa(c.uintptrType.IntTypeWidth())
+2 -6
View File
@@ -451,14 +451,10 @@ func (c *compilerContext) isThumb() bool {
// readStackPointer emits a LLVM intrinsic call that returns the current stack // readStackPointer emits a LLVM intrinsic call that returns the current stack
// pointer as an *i8. // pointer as an *i8.
func (b *builder) readStackPointer() llvm.Value { func (b *builder) readStackPointer() llvm.Value {
name := "llvm.stacksave.p0" stacksave := b.mod.NamedFunction("llvm.stacksave")
if llvmutil.Version() < 18 {
name = "llvm.stacksave" // backwards compatibility with LLVM 17 and below
}
stacksave := b.mod.NamedFunction(name)
if stacksave.IsNil() { if stacksave.IsNil() {
fnType := llvm.FunctionType(b.dataPtrType, nil, false) fnType := llvm.FunctionType(b.dataPtrType, nil, false)
stacksave = llvm.AddFunction(b.mod, name, fnType) stacksave = llvm.AddFunction(b.mod, "llvm.stacksave", fnType)
} }
return b.CreateCall(stacksave.GlobalValueType(), stacksave, nil, "") return b.CreateCall(stacksave.GlobalValueType(), stacksave, nil, "")
} }
+3 -16
View File
@@ -1,5 +1,5 @@
// Package llvmutil contains utility functions used across multiple compiler // Package llvmutil contains utility functions used across multiple compiler
// packages. For example, they may be used by both the compiler package and // packages. For example, they may be used by both the compiler pacakge and
// transformation packages. // transformation packages.
// //
// Normally, utility packages are avoided. However, in this case, the utility // Normally, utility packages are avoided. However, in this case, the utility
@@ -8,9 +8,6 @@
package llvmutil package llvmutil
import ( import (
"strconv"
"strings"
"tinygo.org/x/go-llvm" "tinygo.org/x/go-llvm"
) )
@@ -31,7 +28,7 @@ func CreateEntryBlockAlloca(builder llvm.Builder, t llvm.Type, name string) llvm
} }
// CreateTemporaryAlloca creates a new alloca in the entry block and adds // CreateTemporaryAlloca creates a new alloca in the entry block and adds
// lifetime start information in the IR signalling that the alloca won't be used // lifetime start infromation in the IR signalling that the alloca won't be used
// before this point. // before this point.
// //
// This is useful for creating temporary allocas for intrinsics. Don't forget to // This is useful for creating temporary allocas for intrinsics. Don't forget to
@@ -176,7 +173,7 @@ func SplitBasicBlock(builder llvm.Builder, afterInst llvm.Value, insertAfter llv
return newBlock return newBlock
} }
// AppendToGlobal appends the given values to a global array like llvm.used. The global might // Append the given values to a global array like llvm.used. The global might
// not exist yet. The values can be any pointer type, they will be cast to i8*. // not exist yet. The values can be any pointer type, they will be cast to i8*.
func AppendToGlobal(mod llvm.Module, globalName string, values ...llvm.Value) { func AppendToGlobal(mod llvm.Module, globalName string, values ...llvm.Value) {
// Read the existing values in the llvm.used array (if it exists). // Read the existing values in the llvm.used array (if it exists).
@@ -206,13 +203,3 @@ func AppendToGlobal(mod llvm.Module, globalName string, values ...llvm.Value) {
used.SetInitializer(usedInitializer) used.SetInitializer(usedInitializer)
used.SetLinkage(llvm.AppendingLinkage) used.SetLinkage(llvm.AppendingLinkage)
} }
// Return the LLVM major version.
func Version() int {
majorStr := strings.Split(llvm.Version, ".")[0]
major, err := strconv.Atoi(majorStr)
if err != nil {
panic("unexpected error while parsing LLVM version: " + err.Error()) // should not happen
}
return major
}
+2 -2
View File
@@ -81,11 +81,11 @@ entry:
%select.send.value = alloca i32, align 4 %select.send.value = alloca i32, align 4
store i32 1, ptr %select.send.value, align 4 store i32 1, ptr %select.send.value, align 4
call void @llvm.lifetime.start.p0(i64 16, ptr nonnull %select.states.alloca) call void @llvm.lifetime.start.p0(i64 16, ptr nonnull %select.states.alloca)
store ptr %ch1, ptr %select.states.alloca, align 4 store ptr %ch1, ptr %select.states.alloca, align 8
%select.states.alloca.repack1 = getelementptr inbounds %runtime.chanSelectState, ptr %select.states.alloca, i32 0, i32 1 %select.states.alloca.repack1 = getelementptr inbounds %runtime.chanSelectState, ptr %select.states.alloca, i32 0, i32 1
store ptr %select.send.value, ptr %select.states.alloca.repack1, align 4 store ptr %select.send.value, ptr %select.states.alloca.repack1, align 4
%0 = getelementptr inbounds [2 x %runtime.chanSelectState], ptr %select.states.alloca, i32 0, i32 1 %0 = getelementptr inbounds [2 x %runtime.chanSelectState], ptr %select.states.alloca, i32 0, i32 1
store ptr %ch2, ptr %0, align 4 store ptr %ch2, ptr %0, align 8
%.repack3 = getelementptr inbounds [2 x %runtime.chanSelectState], ptr %select.states.alloca, i32 0, i32 1, i32 1 %.repack3 = getelementptr inbounds [2 x %runtime.chanSelectState], ptr %select.states.alloca, i32 0, i32 1, i32 1
store ptr null, ptr %.repack3, align 4 store ptr null, ptr %.repack3, align 4
%select.result = call { i32, i1 } @runtime.tryChanSelect(ptr undef, ptr nonnull %select.states.alloca, i32 2, i32 2, ptr undef) #4 %select.result = call { i32, i1 } @runtime.tryChanSelect(ptr undef, ptr nonnull %select.states.alloca, i32 2, i32 2, ptr undef) #4
+3 -3
View File
@@ -25,7 +25,7 @@ entry:
%deferPtr = alloca ptr, align 4 %deferPtr = alloca ptr, align 4
store ptr null, ptr %deferPtr, align 4 store ptr null, ptr %deferPtr, align 4
%deferframe.buf = alloca %runtime.deferFrame, align 4 %deferframe.buf = alloca %runtime.deferFrame, align 4
%0 = call ptr @llvm.stacksave.p0() %0 = call ptr @llvm.stacksave()
call void @runtime.setupDeferFrame(ptr nonnull %deferframe.buf, ptr %0, ptr undef) #4 call void @runtime.setupDeferFrame(ptr nonnull %deferframe.buf, ptr %0, ptr undef) #4
store i32 0, ptr %defer.alloca, align 4 store i32 0, ptr %defer.alloca, align 4
%defer.alloca.repack15 = getelementptr inbounds { i32, ptr }, ptr %defer.alloca, i32 0, i32 1 %defer.alloca.repack15 = getelementptr inbounds { i32, ptr }, ptr %defer.alloca, i32 0, i32 1
@@ -113,7 +113,7 @@ rundefers.end3: ; preds = %rundefers.loophead6
} }
; Function Attrs: nocallback nofree nosync nounwind willreturn ; Function Attrs: nocallback nofree nosync nounwind willreturn
declare ptr @llvm.stacksave.p0() #3 declare ptr @llvm.stacksave() #3
declare void @runtime.setupDeferFrame(ptr dereferenceable_or_null(24), ptr, ptr) #2 declare void @runtime.setupDeferFrame(ptr dereferenceable_or_null(24), ptr, ptr) #2
@@ -136,7 +136,7 @@ entry:
%deferPtr = alloca ptr, align 4 %deferPtr = alloca ptr, align 4
store ptr null, ptr %deferPtr, align 4 store ptr null, ptr %deferPtr, align 4
%deferframe.buf = alloca %runtime.deferFrame, align 4 %deferframe.buf = alloca %runtime.deferFrame, align 4
%0 = call ptr @llvm.stacksave.p0() %0 = call ptr @llvm.stacksave()
call void @runtime.setupDeferFrame(ptr nonnull %deferframe.buf, ptr %0, ptr undef) #4 call void @runtime.setupDeferFrame(ptr nonnull %deferframe.buf, ptr %0, ptr undef) #4
store i32 0, ptr %defer.alloca, align 4 store i32 0, ptr %defer.alloca, align 4
%defer.alloca.repack22 = getelementptr inbounds { i32, ptr }, ptr %defer.alloca, i32 0, i32 1 %defer.alloca.repack22 = getelementptr inbounds { i32, ptr }, ptr %defer.alloca, i32 0, i32 1
+9 -9
View File
@@ -16,9 +16,9 @@ target triple = "wasm32-unknown-wasi"
@main.struct2 = hidden global ptr null, align 4 @main.struct2 = hidden global ptr null, align 4
@main.struct3 = hidden global ptr null, align 4 @main.struct3 = hidden global ptr null, align 4
@main.struct4 = hidden global ptr null, align 4 @main.struct4 = hidden global ptr null, align 4
@main.slice1 = hidden global { ptr, i32, i32 } zeroinitializer, align 4 @main.slice1 = hidden global { ptr, i32, i32 } zeroinitializer, align 8
@main.slice2 = hidden global { ptr, i32, i32 } zeroinitializer, align 4 @main.slice2 = hidden global { ptr, i32, i32 } zeroinitializer, align 8
@main.slice3 = hidden global { ptr, i32, i32 } zeroinitializer, align 4 @main.slice3 = hidden global { ptr, i32, i32 } zeroinitializer, align 8
@"runtime/gc.layout:62-2000000000000001" = linkonce_odr unnamed_addr constant { i32, [8 x i8] } { i32 62, [8 x i8] c"\01\00\00\00\00\00\00 " } @"runtime/gc.layout:62-2000000000000001" = linkonce_odr unnamed_addr constant { i32, [8 x i8] } { i32 62, [8 x i8] c"\01\00\00\00\00\00\00 " }
@"runtime/gc.layout:62-0001" = linkonce_odr unnamed_addr constant { i32, [8 x i8] } { i32 62, [8 x i8] c"\01\00\00\00\00\00\00\00" } @"runtime/gc.layout:62-0001" = linkonce_odr unnamed_addr constant { i32, [8 x i8] } { i32 62, [8 x i8] c"\01\00\00\00\00\00\00\00" }
@"reflect/types.type:basic:complex128" = linkonce_odr constant { i8, ptr } { i8 80, ptr @"reflect/types.type:pointer:basic:complex128" }, align 4 @"reflect/types.type:basic:complex128" = linkonce_odr constant { i8, ptr } { i8 80, ptr @"reflect/types.type:pointer:basic:complex128" }, align 4
@@ -104,19 +104,19 @@ entry:
%stackalloc = alloca i8, align 1 %stackalloc = alloca i8, align 1
%makeslice = call dereferenceable(5) ptr @runtime.alloc(i32 5, ptr nonnull inttoptr (i32 3 to ptr), ptr undef) #3 %makeslice = call dereferenceable(5) ptr @runtime.alloc(i32 5, ptr nonnull inttoptr (i32 3 to ptr), ptr undef) #3
call void @runtime.trackPointer(ptr nonnull %makeslice, ptr nonnull %stackalloc, ptr undef) #3 call void @runtime.trackPointer(ptr nonnull %makeslice, ptr nonnull %stackalloc, ptr undef) #3
store ptr %makeslice, ptr @main.slice1, align 4 store ptr %makeslice, ptr @main.slice1, align 8
store i32 5, ptr getelementptr inbounds ({ ptr, i32, i32 }, ptr @main.slice1, i32 0, i32 1), align 4 store i32 5, ptr getelementptr inbounds ({ ptr, i32, i32 }, ptr @main.slice1, i32 0, i32 1), align 4
store i32 5, ptr getelementptr inbounds ({ ptr, i32, i32 }, ptr @main.slice1, i32 0, i32 2), align 4 store i32 5, ptr getelementptr inbounds ({ ptr, i32, i32 }, ptr @main.slice1, i32 0, i32 2), align 8
%makeslice1 = call dereferenceable(20) ptr @runtime.alloc(i32 20, ptr nonnull inttoptr (i32 67 to ptr), ptr undef) #3 %makeslice1 = call dereferenceable(20) ptr @runtime.alloc(i32 20, ptr nonnull inttoptr (i32 67 to ptr), ptr undef) #3
call void @runtime.trackPointer(ptr nonnull %makeslice1, ptr nonnull %stackalloc, ptr undef) #3 call void @runtime.trackPointer(ptr nonnull %makeslice1, ptr nonnull %stackalloc, ptr undef) #3
store ptr %makeslice1, ptr @main.slice2, align 4 store ptr %makeslice1, ptr @main.slice2, align 8
store i32 5, ptr getelementptr inbounds ({ ptr, i32, i32 }, ptr @main.slice2, i32 0, i32 1), align 4 store i32 5, ptr getelementptr inbounds ({ ptr, i32, i32 }, ptr @main.slice2, i32 0, i32 1), align 4
store i32 5, ptr getelementptr inbounds ({ ptr, i32, i32 }, ptr @main.slice2, i32 0, i32 2), align 4 store i32 5, ptr getelementptr inbounds ({ ptr, i32, i32 }, ptr @main.slice2, i32 0, i32 2), align 8
%makeslice3 = call dereferenceable(60) ptr @runtime.alloc(i32 60, ptr nonnull inttoptr (i32 71 to ptr), ptr undef) #3 %makeslice3 = call dereferenceable(60) ptr @runtime.alloc(i32 60, ptr nonnull inttoptr (i32 71 to ptr), ptr undef) #3
call void @runtime.trackPointer(ptr nonnull %makeslice3, ptr nonnull %stackalloc, ptr undef) #3 call void @runtime.trackPointer(ptr nonnull %makeslice3, ptr nonnull %stackalloc, ptr undef) #3
store ptr %makeslice3, ptr @main.slice3, align 4 store ptr %makeslice3, ptr @main.slice3, align 8
store i32 5, ptr getelementptr inbounds ({ ptr, i32, i32 }, ptr @main.slice3, i32 0, i32 1), align 4 store i32 5, ptr getelementptr inbounds ({ ptr, i32, i32 }, ptr @main.slice3, i32 0, i32 1), align 4
store i32 5, ptr getelementptr inbounds ({ ptr, i32, i32 }, ptr @main.slice3, i32 0, i32 2), align 4 store i32 5, ptr getelementptr inbounds ({ ptr, i32, i32 }, ptr @main.slice3, i32 0, i32 2), align 8
ret void ret void
} }
+1 -1
View File
@@ -9,7 +9,7 @@ target triple = "wasm32-unknown-wasi"
@"reflect/types.type:basic:int" = linkonce_odr constant { i8, ptr } { i8 -62, ptr @"reflect/types.type:pointer:basic:int" }, align 4 @"reflect/types.type:basic:int" = linkonce_odr constant { i8, ptr } { i8 -62, ptr @"reflect/types.type:pointer:basic:int" }, align 4
@"reflect/types.type:pointer:basic:int" = linkonce_odr constant { i8, i16, ptr } { i8 -43, i16 0, ptr @"reflect/types.type:basic:int" }, align 4 @"reflect/types.type:pointer:basic:int" = linkonce_odr constant { i8, i16, ptr } { i8 -43, i16 0, ptr @"reflect/types.type:basic:int" }, align 4
@"reflect/types.type:pointer:named:error" = linkonce_odr constant { i8, i16, ptr } { i8 -43, i16 0, ptr @"reflect/types.type:named:error" }, align 4 @"reflect/types.type:pointer:named:error" = linkonce_odr constant { i8, i16, ptr } { i8 -43, i16 0, ptr @"reflect/types.type:named:error" }, align 4
@"reflect/types.type:named:error" = linkonce_odr constant { i8, i16, ptr, ptr, ptr, [7 x i8] } { i8 116, i16 1, ptr @"reflect/types.type:pointer:named:error", ptr @"reflect/types.type:interface:{Error:func:{}{basic:string}}", ptr @"reflect/types.type.pkgpath.empty", [7 x i8] c".error\00" }, align 4 @"reflect/types.type:named:error" = linkonce_odr constant { i8, i16, ptr, ptr, ptr, [7 x i8] } { i8 116, i16 0, ptr @"reflect/types.type:pointer:named:error", ptr @"reflect/types.type:interface:{Error:func:{}{basic:string}}", ptr @"reflect/types.type.pkgpath.empty", [7 x i8] c".error\00" }, align 4
@"reflect/types.type.pkgpath.empty" = linkonce_odr unnamed_addr constant [1 x i8] zeroinitializer, align 1 @"reflect/types.type.pkgpath.empty" = linkonce_odr unnamed_addr constant [1 x i8] zeroinitializer, align 1
@"reflect/types.type:interface:{Error:func:{}{basic:string}}" = linkonce_odr constant { i8, ptr } { i8 84, ptr @"reflect/types.type:pointer:interface:{Error:func:{}{basic:string}}" }, align 4 @"reflect/types.type:interface:{Error:func:{}{basic:string}}" = linkonce_odr constant { i8, ptr } { i8 84, ptr @"reflect/types.type:pointer:interface:{Error:func:{}{basic:string}}" }, align 4
@"reflect/types.type:pointer:interface:{Error:func:{}{basic:string}}" = linkonce_odr constant { i8, i16, ptr } { i8 -43, i16 0, ptr @"reflect/types.type:interface:{Error:func:{}{basic:string}}" }, align 4 @"reflect/types.type:pointer:interface:{Error:func:{}{basic:string}}" = linkonce_odr constant { i8, i16, ptr } { i8 -43, i16 0, ptr @"reflect/types.type:interface:{Error:func:{}{basic:string}}" }, align 4
+2 -2
View File
@@ -122,7 +122,7 @@ entry:
br i1 %slice.maxcap, label %slice.throw, label %slice.next br i1 %slice.maxcap, label %slice.throw, label %slice.next
slice.next: ; preds = %entry slice.next: ; preds = %entry
%makeslice.cap = shl nuw i32 %len, 1 %makeslice.cap = shl i32 %len, 1
%makeslice.buf = call ptr @runtime.alloc(i32 %makeslice.cap, ptr nonnull inttoptr (i32 3 to ptr), ptr undef) #3 %makeslice.buf = call ptr @runtime.alloc(i32 %makeslice.cap, ptr nonnull inttoptr (i32 3 to ptr), ptr undef) #3
%0 = insertvalue { ptr, i32, i32 } undef, ptr %makeslice.buf, 0 %0 = insertvalue { ptr, i32, i32 } undef, ptr %makeslice.buf, 0
%1 = insertvalue { ptr, i32, i32 } %0, i32 %len, 1 %1 = insertvalue { ptr, i32, i32 } %0, i32 %len, 1
@@ -164,7 +164,7 @@ entry:
br i1 %slice.maxcap, label %slice.throw, label %slice.next br i1 %slice.maxcap, label %slice.throw, label %slice.next
slice.next: ; preds = %entry slice.next: ; preds = %entry
%makeslice.cap = shl nuw i32 %len, 2 %makeslice.cap = shl i32 %len, 2
%makeslice.buf = call ptr @runtime.alloc(i32 %makeslice.cap, ptr nonnull inttoptr (i32 3 to ptr), ptr undef) #3 %makeslice.buf = call ptr @runtime.alloc(i32 %makeslice.cap, ptr nonnull inttoptr (i32 3 to ptr), ptr undef) #3
%0 = insertvalue { ptr, i32, i32 } undef, ptr %makeslice.buf, 0 %0 = insertvalue { ptr, i32, i32 } undef, ptr %makeslice.buf, 0
%1 = insertvalue { ptr, i32, i32 } %0, i32 %len, 1 %1 = insertvalue { ptr, i32, i32 } %0, i32 %len, 1
+4 -4
View File
@@ -26,7 +26,7 @@ entry:
%2 = insertvalue %main.hasPadding %1, i1 %s.b2, 2 %2 = insertvalue %main.hasPadding %1, i1 %s.b2, 2
call void @llvm.lifetime.start.p0(i64 4, ptr nonnull %hashmap.value) call void @llvm.lifetime.start.p0(i64 4, ptr nonnull %hashmap.value)
call void @llvm.lifetime.start.p0(i64 12, ptr nonnull %hashmap.key) call void @llvm.lifetime.start.p0(i64 12, ptr nonnull %hashmap.key)
store %main.hasPadding %2, ptr %hashmap.key, align 4 store %main.hasPadding %2, ptr %hashmap.key, align 8
%3 = getelementptr inbounds i8, ptr %hashmap.key, i32 1 %3 = getelementptr inbounds i8, ptr %hashmap.key, i32 1
call void @runtime.memzero(ptr nonnull %3, i32 3, ptr undef) #5 call void @runtime.memzero(ptr nonnull %3, i32 3, ptr undef) #5
%4 = getelementptr inbounds i8, ptr %hashmap.key, i32 9 %4 = getelementptr inbounds i8, ptr %hashmap.key, i32 9
@@ -59,7 +59,7 @@ entry:
call void @llvm.lifetime.start.p0(i64 4, ptr nonnull %hashmap.value) call void @llvm.lifetime.start.p0(i64 4, ptr nonnull %hashmap.value)
store i32 5, ptr %hashmap.value, align 4 store i32 5, ptr %hashmap.value, align 4
call void @llvm.lifetime.start.p0(i64 12, ptr nonnull %hashmap.key) call void @llvm.lifetime.start.p0(i64 12, ptr nonnull %hashmap.key)
store %main.hasPadding %2, ptr %hashmap.key, align 4 store %main.hasPadding %2, ptr %hashmap.key, align 8
%3 = getelementptr inbounds i8, ptr %hashmap.key, i32 1 %3 = getelementptr inbounds i8, ptr %hashmap.key, i32 1
call void @runtime.memzero(ptr nonnull %3, i32 3, ptr undef) #5 call void @runtime.memzero(ptr nonnull %3, i32 3, ptr undef) #5
%4 = getelementptr inbounds i8, ptr %hashmap.key, i32 9 %4 = getelementptr inbounds i8, ptr %hashmap.key, i32 9
@@ -80,7 +80,7 @@ entry:
call void @llvm.lifetime.start.p0(i64 4, ptr nonnull %hashmap.value) call void @llvm.lifetime.start.p0(i64 4, ptr nonnull %hashmap.value)
call void @llvm.lifetime.start.p0(i64 24, ptr nonnull %hashmap.key) call void @llvm.lifetime.start.p0(i64 24, ptr nonnull %hashmap.key)
%s.elt = extractvalue [2 x %main.hasPadding] %s, 0 %s.elt = extractvalue [2 x %main.hasPadding] %s, 0
store %main.hasPadding %s.elt, ptr %hashmap.key, align 4 store %main.hasPadding %s.elt, ptr %hashmap.key, align 8
%hashmap.key.repack1 = getelementptr inbounds [2 x %main.hasPadding], ptr %hashmap.key, i32 0, i32 1 %hashmap.key.repack1 = getelementptr inbounds [2 x %main.hasPadding], ptr %hashmap.key, i32 0, i32 1
%s.elt2 = extractvalue [2 x %main.hasPadding] %s, 1 %s.elt2 = extractvalue [2 x %main.hasPadding] %s, 1
store %main.hasPadding %s.elt2, ptr %hashmap.key.repack1, align 4 store %main.hasPadding %s.elt2, ptr %hashmap.key.repack1, align 4
@@ -108,7 +108,7 @@ entry:
store i32 5, ptr %hashmap.value, align 4 store i32 5, ptr %hashmap.value, align 4
call void @llvm.lifetime.start.p0(i64 24, ptr nonnull %hashmap.key) call void @llvm.lifetime.start.p0(i64 24, ptr nonnull %hashmap.key)
%s.elt = extractvalue [2 x %main.hasPadding] %s, 0 %s.elt = extractvalue [2 x %main.hasPadding] %s, 0
store %main.hasPadding %s.elt, ptr %hashmap.key, align 4 store %main.hasPadding %s.elt, ptr %hashmap.key, align 8
%hashmap.key.repack1 = getelementptr inbounds [2 x %main.hasPadding], ptr %hashmap.key, i32 0, i32 1 %hashmap.key.repack1 = getelementptr inbounds [2 x %main.hasPadding], ptr %hashmap.key, i32 0, i32 1
%s.elt2 = extractvalue [2 x %main.hasPadding] %s, 1 %s.elt2 = extractvalue [2 x %main.hasPadding] %s, 1
store %main.hasPadding %s.elt2, ptr %hashmap.key.repack1, align 4 store %main.hasPadding %s.elt2, ptr %hashmap.key.repack1, align 4
+2 -3
View File
@@ -51,7 +51,6 @@ func TestCorpus(t *testing.T) {
if *testTarget != "" { if *testTarget != "" {
target = *testTarget target = *testTarget
} }
isWASI := strings.HasPrefix(target, "wasi")
repos, err := loadRepos(*corpus) repos, err := loadRepos(*corpus)
if err != nil { if err != nil {
@@ -70,7 +69,7 @@ func TestCorpus(t *testing.T) {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
t.Parallel() t.Parallel()
if isWASI && repo.SkipWASI { if target == "wasi" && repo.SkipWASI {
t.Skip("skip wasi") t.Skip("skip wasi")
} }
if repo.Slow && testing.Short() { if repo.Slow && testing.Short() {
@@ -136,7 +135,7 @@ func TestCorpus(t *testing.T) {
t.Run(dir.Pkg, func(t *testing.T) { t.Run(dir.Pkg, func(t *testing.T) {
t.Parallel() t.Parallel()
if isWASI && dir.SkipWASI { if target == "wasi" && dir.SkipWASI {
t.Skip("skip wasi") t.Skip("skip wasi")
} }
if dir.Slow && testing.Short() { if dir.Slow && testing.Short() {
Generated
+4 -4
View File
@@ -20,16 +20,16 @@
}, },
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1703068421, "lastModified": 1696983906,
"narHash": "sha256-WSw5Faqlw75McIflnl5v7qVD/B3S2sLh+968bpOGrWA=", "narHash": "sha256-L7GyeErguS7Pg4h8nK0wGlcUTbfUMDu+HMf1UcyP72k=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "d65bceaee0fb1e64363f7871bc43dc1c6ecad99f", "rev": "bd1cde45c77891214131cbbea5b1203e485a9d51",
"type": "github" "type": "github"
}, },
"original": { "original": {
"id": "nixpkgs", "id": "nixpkgs",
"ref": "nixos-23.11", "ref": "nixos-23.05",
"type": "indirect" "type": "indirect"
} }
}, },
+10 -10
View File
@@ -18,10 +18,10 @@
# #
# But you'll need a bit more to make TinyGo actually able to compile code: # But you'll need a bit more to make TinyGo actually able to compile code:
# #
# make llvm-source # fetch compiler-rt # make llvm-source # fetch compiler-rt
# git submodule update --init # fetch lots of other libraries and SVD files # git submodule update --init --recursive # fetch lots of other libraries and SVD files
# make gen-device -j4 # build src/device/*/*.go files # make gen-device -j4 # build src/device/*/*.go files
# make wasi-libc # build support for wasi/wasm # make wasi-libc # build support for wasi/wasm
# #
# With this, you should have an environment that can compile anything - except # With this, you should have an environment that can compile anything - except
# for the Xtensa architecture (ESP8266/ESP32) because support for that lives in # for the Xtensa architecture (ESP8266/ESP32) because support for that lives in
@@ -35,7 +35,7 @@
inputs = { inputs = {
# Use a recent stable release, but fix the version to make it reproducible. # Use a recent stable release, but fix the version to make it reproducible.
# This version should be updated from time to time. # This version should be updated from time to time.
nixpkgs.url = "nixpkgs/nixos-23.11"; nixpkgs.url = "nixpkgs/nixos-23.05";
flake-utils.url = "github:numtide/flake-utils"; flake-utils.url = "github:numtide/flake-utils";
}; };
outputs = { self, nixpkgs, flake-utils }: outputs = { self, nixpkgs, flake-utils }:
@@ -49,11 +49,11 @@
buildInputs = [ buildInputs = [
# These dependencies are required for building tinygo (go install). # These dependencies are required for building tinygo (go install).
go go
llvmPackages_17.llvm llvmPackages_16.llvm
llvmPackages_17.libclang llvmPackages_16.libclang
# Additional dependencies needed at runtime, for building and/or # Additional dependencies needed at runtime, for building and/or
# flashing. # flashing.
llvmPackages_17.lld llvmPackages_16.lld
avrdude avrdude
binaryen binaryen
# Additional dependencies needed for on-chip debugging. # Additional dependencies needed for on-chip debugging.
@@ -68,7 +68,7 @@
# Without setting these explicitly, Homebrew versions might be used # Without setting these explicitly, Homebrew versions might be used
# or the default `ar` and `nm` tools might be used (which don't # or the default `ar` and `nm` tools might be used (which don't
# support wasi). # support wasi).
export CLANG="clang-17 -resource-dir ${llvmPackages_17.clang.cc.lib}/lib/clang/17" export CLANG="clang-16 -resource-dir ${llvmPackages_16.clang.cc.lib}/lib/clang/16"
export LLVM_AR=llvm-ar export LLVM_AR=llvm-ar
export LLVM_NM=llvm-nm export LLVM_NM=llvm-nm
@@ -77,7 +77,7 @@
export MD5SUM=md5sum export MD5SUM=md5sum
# Ugly hack to make the Clang resources directory available. # Ugly hack to make the Clang resources directory available.
export GOFLAGS="\"-ldflags=-X github.com/tinygo-org/tinygo/goenv.clangResourceDir=${llvmPackages_17.clang.cc.lib}/lib/clang/17\" -tags=llvm17" export GOFLAGS="\"-ldflags=-X github.com/tinygo-org/tinygo/goenv.clangResourceDir=${llvmPackages_16.clang.cc.lib}/lib/clang/16"\"
''; '';
}; };
} }
+6 -20
View File
@@ -3,45 +3,31 @@ module github.com/tinygo-org/tinygo
go 1.18 go 1.18
require ( require (
github.com/aykevl/go-wasm v0.0.2-0.20240312204833-50275154210c github.com/aykevl/go-wasm v0.0.2-0.20220616010729-4a0a888aebdc
github.com/blakesmith/ar v0.0.0-20150311145944-8bd4349a67f2 github.com/blakesmith/ar v0.0.0-20150311145944-8bd4349a67f2
github.com/chromedp/cdproto v0.0.0-20220113222801-0725d94bb6ee github.com/chromedp/cdproto v0.0.0-20220113222801-0725d94bb6ee
github.com/chromedp/chromedp v0.7.6 github.com/chromedp/chromedp v0.7.6
github.com/client9/misspell v0.3.4
github.com/gofrs/flock v0.8.1 github.com/gofrs/flock v0.8.1
github.com/google/shlex v0.0.0-20181106134648-c34317bd91bf github.com/google/shlex v0.0.0-20181106134648-c34317bd91bf
github.com/inhies/go-bytesize v0.0.0-20220417184213-4913239db9cf github.com/inhies/go-bytesize v0.0.0-20220417184213-4913239db9cf
github.com/marcinbor85/gohex v0.0.0-20200531091804-343a4b548892 github.com/marcinbor85/gohex v0.0.0-20200531091804-343a4b548892
github.com/mattn/go-colorable v0.1.13 github.com/mattn/go-colorable v0.1.8
github.com/mattn/go-tty v0.0.4 github.com/mattn/go-tty v0.0.4
github.com/mgechev/revive v1.3.7
github.com/sigurn/crc16 v0.0.0-20211026045750-20ab5afb07e3 github.com/sigurn/crc16 v0.0.0-20211026045750-20ab5afb07e3
go.bug.st/serial v1.6.0 go.bug.st/serial v1.6.0
golang.org/x/net v0.20.0 golang.org/x/sys v0.11.0
golang.org/x/sys v0.16.0 golang.org/x/tools v0.12.0
golang.org/x/tools v0.17.0
gopkg.in/yaml.v2 v2.4.0 gopkg.in/yaml.v2 v2.4.0
tinygo.org/x/go-llvm v0.0.0-20240518103902-697964f2a9dc tinygo.org/x/go-llvm v0.0.0-20231014233752-75a8a9fe6f74
) )
require ( require (
github.com/BurntSushi/toml v1.3.2 // indirect
github.com/chavacava/garif v0.1.0 // indirect
github.com/chromedp/sysutil v1.0.0 // indirect github.com/chromedp/sysutil v1.0.0 // indirect
github.com/creack/goselect v0.1.2 // indirect github.com/creack/goselect v0.1.2 // indirect
github.com/fatih/color v1.16.0 // indirect
github.com/fatih/structtag v1.2.0 // indirect
github.com/gobwas/httphead v0.1.0 // indirect github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect github.com/gobwas/pool v0.2.1 // indirect
github.com/gobwas/ws v1.1.0 // indirect github.com/gobwas/ws v1.1.0 // indirect
github.com/josharian/intern v1.0.0 // indirect github.com/josharian/intern v1.0.0 // indirect
github.com/mailru/easyjson v0.7.7 // indirect github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-isatty v0.0.12 // indirect
github.com/mattn/go-runewidth v0.0.9 // indirect
github.com/mgechev/dots v0.0.0-20210922191527-e955255bf517 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/spf13/afero v1.11.0 // indirect
golang.org/x/text v0.14.0 // indirect
) )
+18 -58
View File
@@ -1,11 +1,7 @@
github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8= github.com/aykevl/go-wasm v0.0.2-0.20220616010729-4a0a888aebdc h1:Yp49g+qqgQRPk/gcRSmAsXgnT16XPJ6Y5JM1poc6gYM=
github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/aykevl/go-wasm v0.0.2-0.20220616010729-4a0a888aebdc/go.mod h1:7sXyiaA0WtSogCu67R2252fQpVmJMh9JWJ9ddtGkpWw=
github.com/aykevl/go-wasm v0.0.2-0.20240312204833-50275154210c h1:4T0Vj1UkGgcpkRrmn7SbokebnlfxJcMZPgWtOYACAAA=
github.com/aykevl/go-wasm v0.0.2-0.20240312204833-50275154210c/go.mod h1:7sXyiaA0WtSogCu67R2252fQpVmJMh9JWJ9ddtGkpWw=
github.com/blakesmith/ar v0.0.0-20150311145944-8bd4349a67f2 h1:oMCHnXa6CCCafdPDbMh/lWRhRByN0VFLvv+g+ayx1SI= github.com/blakesmith/ar v0.0.0-20150311145944-8bd4349a67f2 h1:oMCHnXa6CCCafdPDbMh/lWRhRByN0VFLvv+g+ayx1SI=
github.com/blakesmith/ar v0.0.0-20150311145944-8bd4349a67f2/go.mod h1:PkYb9DJNAwrSvRx5DYA+gUcOIgTGVMNkfSCbZM8cWpI= github.com/blakesmith/ar v0.0.0-20150311145944-8bd4349a67f2/go.mod h1:PkYb9DJNAwrSvRx5DYA+gUcOIgTGVMNkfSCbZM8cWpI=
github.com/chavacava/garif v0.1.0 h1:2JHa3hbYf5D9dsgseMKAmc/MZ109otzgNFk5s87H9Pc=
github.com/chavacava/garif v0.1.0/go.mod h1:XMyYCkEL58DF0oyW4qDjjnPWONs2HBqYKI+UIPD+Gww=
github.com/chromedp/cdproto v0.0.0-20211126220118-81fa0469ad77/go.mod h1:At5TxYYdxkbQL0TSefRjhLE3Q0lgvqKKMSFUglJ7i1U= github.com/chromedp/cdproto v0.0.0-20211126220118-81fa0469ad77/go.mod h1:At5TxYYdxkbQL0TSefRjhLE3Q0lgvqKKMSFUglJ7i1U=
github.com/chromedp/cdproto v0.0.0-20220113222801-0725d94bb6ee h1:+SFdIVfQpG0s0DHYzou0kgfE0n0ZjKPwbiRJsXrZegU= github.com/chromedp/cdproto v0.0.0-20220113222801-0725d94bb6ee h1:+SFdIVfQpG0s0DHYzou0kgfE0n0ZjKPwbiRJsXrZegU=
github.com/chromedp/cdproto v0.0.0-20220113222801-0725d94bb6ee/go.mod h1:At5TxYYdxkbQL0TSefRjhLE3Q0lgvqKKMSFUglJ7i1U= github.com/chromedp/cdproto v0.0.0-20220113222801-0725d94bb6ee/go.mod h1:At5TxYYdxkbQL0TSefRjhLE3Q0lgvqKKMSFUglJ7i1U=
@@ -13,17 +9,9 @@ github.com/chromedp/chromedp v0.7.6 h1:2juGaktzjwULlsn+DnvIZXFUckEp5xs+GOBroaea+
github.com/chromedp/chromedp v0.7.6/go.mod h1:ayT4YU/MGAALNfOg9gNrpGSAdnU51PMx+FCeuT1iXzo= github.com/chromedp/chromedp v0.7.6/go.mod h1:ayT4YU/MGAALNfOg9gNrpGSAdnU51PMx+FCeuT1iXzo=
github.com/chromedp/sysutil v1.0.0 h1:+ZxhTpfpZlmchB58ih/LBHX52ky7w2VhQVKQMucy3Ic= github.com/chromedp/sysutil v1.0.0 h1:+ZxhTpfpZlmchB58ih/LBHX52ky7w2VhQVKQMucy3Ic=
github.com/chromedp/sysutil v1.0.0/go.mod h1:kgWmDdq8fTzXYcKIBqIYvRRTnYb9aNS9moAV0xufSww= github.com/chromedp/sysutil v1.0.0/go.mod h1:kgWmDdq8fTzXYcKIBqIYvRRTnYb9aNS9moAV0xufSww=
github.com/client9/misspell v0.3.4 h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0= github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0=
github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY= github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM=
github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE=
github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4=
github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94=
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU= github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM= github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og= github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
@@ -43,67 +31,39 @@ github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJ
github.com/marcinbor85/gohex v0.0.0-20200531091804-343a4b548892 h1:6J+qramlHVLmiBOgRiBOnQkno8uprqG6YFFQTt6uYIw= github.com/marcinbor85/gohex v0.0.0-20200531091804-343a4b548892 h1:6J+qramlHVLmiBOgRiBOnQkno8uprqG6YFFQTt6uYIw=
github.com/marcinbor85/gohex v0.0.0-20200531091804-343a4b548892/go.mod h1:Pb6XcsXyropB9LNHhnqaknG/vEwYztLkQzVCHv8sQ3M= github.com/marcinbor85/gohex v0.0.0-20200531091804-343a4b548892/go.mod h1:Pb6XcsXyropB9LNHhnqaknG/vEwYztLkQzVCHv8sQ3M=
github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-tty v0.0.4 h1:NVikla9X8MN0SQAqCYzpGyXv0jY7MNl3HOWD2dkle7E= github.com/mattn/go-tty v0.0.4 h1:NVikla9X8MN0SQAqCYzpGyXv0jY7MNl3HOWD2dkle7E=
github.com/mattn/go-tty v0.0.4/go.mod h1:u5GGXBtZU6RQoKV8gY5W6UhMudbR5vXnUe7j3pxse28= github.com/mattn/go-tty v0.0.4/go.mod h1:u5GGXBtZU6RQoKV8gY5W6UhMudbR5vXnUe7j3pxse28=
github.com/mgechev/dots v0.0.0-20210922191527-e955255bf517 h1:zpIH83+oKzcpryru8ceC6BxnoG8TBrhgAvRg8obzup0=
github.com/mgechev/dots v0.0.0-20210922191527-e955255bf517/go.mod h1:KQ7+USdGKfpPjXk4Ga+5XxQM4Lm4e3gAogrreFAYpOg=
github.com/mgechev/revive v1.3.7 h1:502QY0vQGe9KtYJ9FpxMz9rL+Fc/P13CI5POL4uHCcE=
github.com/mgechev/revive v1.3.7/go.mod h1:RJ16jUbF0OWC3co/+XTxmFNgEpUPwnnA0BRllX2aDNA=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
github.com/orisano/pixelmatch v0.0.0-20210112091706-4fa4c7ba91d5 h1:1SoBaSPudixRecmlHXb/GxmaD3fLMtHIDN13QujwQuc= github.com/orisano/pixelmatch v0.0.0-20210112091706-4fa4c7ba91d5 h1:1SoBaSPudixRecmlHXb/GxmaD3fLMtHIDN13QujwQuc=
github.com/orisano/pixelmatch v0.0.0-20210112091706-4fa4c7ba91d5/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0= github.com/orisano/pixelmatch v0.0.0-20210112091706-4fa4c7ba91d5/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sigurn/crc16 v0.0.0-20211026045750-20ab5afb07e3 h1:aQKxg3+2p+IFXXg97McgDGT5zcMrQoi0EICZs8Pgchs= github.com/sigurn/crc16 v0.0.0-20211026045750-20ab5afb07e3 h1:aQKxg3+2p+IFXXg97McgDGT5zcMrQoi0EICZs8Pgchs=
github.com/sigurn/crc16 v0.0.0-20211026045750-20ab5afb07e3/go.mod h1:9/etS5gpQq9BJsJMWg1wpLbfuSnkm8dPF6FdW2JXVhA= github.com/sigurn/crc16 v0.0.0-20211026045750-20ab5afb07e3/go.mod h1:9/etS5gpQq9BJsJMWg1wpLbfuSnkm8dPF6FdW2JXVhA=
github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
go.bug.st/serial v1.6.0 h1:mAbRGN4cKE2J5gMwsMHC2KQisdLRQssO9WSM+rbZJ8A= go.bug.st/serial v1.6.0 h1:mAbRGN4cKE2J5gMwsMHC2KQisdLRQssO9WSM+rbZJ8A=
go.bug.st/serial v1.6.0/go.mod h1:UABfsluHAiaNI+La2iESysd9Vetq7VRdpxvjx7CmmOE= go.bug.st/serial v1.6.0/go.mod h1:UABfsluHAiaNI+La2iESysd9Vetq7VRdpxvjx7CmmOE=
golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0= golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc=
golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo=
golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201207223542-d4d67f95c62d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201207223542-d4d67f95c62d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU= golang.org/x/tools v0.12.0 h1:YW6HUoUmYBpwSgyaGaZq1fHjrBjX1rlpZ54T6mu2kss=
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/tools v0.12.0/go.mod h1:Sc0INKfu04TlqNoRA1hgpFZbhYXHPr4V5DzpSBTPqQM=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.17.0 h1:FvmRgNOcs3kOa+T20R1uhfP9F6HgG2mfxDv1vrx1Htc=
golang.org/x/tools v0.17.0/go.mod h1:xsh6VxdV005rRVaS6SSAf9oiAqljS7UZUacMZ8Bnsps=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= tinygo.org/x/go-llvm v0.0.0-20231014233752-75a8a9fe6f74 h1:tW8XhLI9gUZLL+2pG0HYb5dc6bpMj1aqtESpizXPnMY=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= tinygo.org/x/go-llvm v0.0.0-20231014233752-75a8a9fe6f74/go.mod h1:GFbusT2VTA4I+l4j80b17KFK+6whv69Wtny5U+T8RR0=
tinygo.org/x/go-llvm v0.0.0-20240518103902-697964f2a9dc h1:TCzibFa4oLu+njEP3fnRUmZ+QQeb8BjtOwctgcjzL0k=
tinygo.org/x/go-llvm v0.0.0-20240518103902-697964f2a9dc/go.mod h1:GFbusT2VTA4I+l4j80b17KFK+6whv69Wtny5U+T8RR0=
+5 -2
View File
@@ -142,8 +142,11 @@ func Get(name string) string {
} }
return filepath.Join(dir, "tinygo") return filepath.Join(dir, "tinygo")
case "CGO_ENABLED": case "CGO_ENABLED":
// Always enable CGo. It is required by a number of targets, including val := os.Getenv("CGO_ENABLED")
// macOS and the rp2040. if val == "1" || val == "0" {
return val
}
// Default to enabling CGo.
return "1" return "1"
case "TINYGOROOT": case "TINYGOROOT":
return sourceDir() return sourceDir()
+1 -1
View File
@@ -9,7 +9,7 @@ import (
// Version of TinyGo. // Version of TinyGo.
// Update this value before release of new version of software. // Update this value before release of new version of software.
const version = "0.32.0-dev" const version = "0.31.0-dev"
var ( var (
// This variable is set at build time using -ldflags parameters. // This variable is set at build time using -ldflags parameters.
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash #!/bin/bash
# Docker hub does a recursive clone, then checks the branch out, # Docker hub does a recursive clone, then checks the branch out,
# so when a PR adds a submodule (or updates it), it fails. # so when a PR adds a submodule (or updates it), it fails.
git submodule update --init git submodule update --init --recursive
-10
View File
@@ -1,10 +0,0 @@
//go:build tools
// Install linter versions specified in go.mod
// See https://marcofranssen.nl/manage-go-tools-via-go-modules for idom
package tools
import (
_ "github.com/client9/misspell"
_ "github.com/mgechev/revive"
)
+10 -38
View File
@@ -239,8 +239,7 @@ func (r *runner) run(fn *function, params []value, parentMem *memoryView, indent
// already be emitted in initAll. // already be emitted in initAll.
continue continue
case strings.HasPrefix(callFn.name, "runtime.print") || callFn.name == "runtime._panic" || callFn.name == "runtime.hashmapGet" || callFn.name == "runtime.hashmapInterfaceHash" || case strings.HasPrefix(callFn.name, "runtime.print") || callFn.name == "runtime._panic" || callFn.name == "runtime.hashmapGet" || callFn.name == "runtime.hashmapInterfaceHash" ||
callFn.name == "os.runtime_args" || callFn.name == "internal/task.start" || callFn.name == "internal/task.Current" || callFn.name == "os.runtime_args" || callFn.name == "internal/task.start" || callFn.name == "internal/task.Current":
callFn.name == "time.startTimer" || callFn.name == "time.stopTimer" || callFn.name == "time.resetTimer":
// These functions should be run at runtime. Specifically: // These functions should be run at runtime. Specifically:
// * Print and panic functions are best emitted directly without // * Print and panic functions are best emitted directly without
// interpreting them, otherwise we get a ton of putchar (etc.) // interpreting them, otherwise we get a ton of putchar (etc.)
@@ -253,8 +252,6 @@ func (r *runner) run(fn *function, params []value, parentMem *memoryView, indent
// at runtime. // at runtime.
// * internal/task.start, internal/task.Current: start and read shcheduler state, // * internal/task.start, internal/task.Current: start and read shcheduler state,
// which is modified elsewhere. // which is modified elsewhere.
// * Timer functions access runtime internal state which may
// not be initialized.
err := r.runAtRuntime(fn, inst, locals, &mem, indent) err := r.runAtRuntime(fn, inst, locals, &mem, indent)
if err != nil { if err != nil {
return nil, mem, err return nil, mem, err
@@ -427,22 +424,7 @@ func (r *runner) run(fn *function, params []value, parentMem *memoryView, indent
if err != nil { if err != nil {
return nil, mem, r.errorAt(inst, err) return nil, mem, r.errorAt(inst, err)
} }
// typecodePtr always point to the numMethod field in the type methodSetPtr, err := mem.load(typecodePtr.addOffset(-int64(r.pointerSize)), r.pointerSize).asPointer(r)
// description struct. The methodSet, when present, comes right
// before the numMethod field (the compiler doesn't generate
// method sets for concrete types without methods).
// Considering that the compiler doesn't emit interface type
// asserts for interfaces with no methods (as the always succeed)
// then if the offset is zero, this assert must always fail.
if typecodePtr.offset() == 0 {
locals[inst.localIndex] = literalValue{uint8(0)}
break
}
typecodePtrOffset, err := typecodePtr.addOffset(-int64(r.pointerSize))
if err != nil {
return nil, mem, r.errorAt(inst, err)
}
methodSetPtr, err := mem.load(typecodePtrOffset, r.pointerSize).asPointer(r)
if err != nil { if err != nil {
return nil, mem, r.errorAt(inst, err) return nil, mem, r.errorAt(inst, err)
} }
@@ -488,11 +470,7 @@ func (r *runner) run(fn *function, params []value, parentMem *memoryView, indent
if err != nil { if err != nil {
return nil, mem, r.errorAt(inst, err) return nil, mem, r.errorAt(inst, err)
} }
typecodePtrOffset, err := typecodePtr.addOffset(-int64(r.pointerSize)) methodSetPtr, err := mem.load(typecodePtr.addOffset(-int64(r.pointerSize)), r.pointerSize).asPointer(r)
if err != nil {
return nil, mem, r.errorAt(inst, err)
}
methodSetPtr, err := mem.load(typecodePtrOffset, r.pointerSize).asPointer(r)
if err != nil { if err != nil {
return nil, mem, r.errorAt(inst, err) return nil, mem, r.errorAt(inst, err)
} }
@@ -655,11 +633,11 @@ func (r *runner) run(fn *function, params []value, parentMem *memoryView, indent
case llvm.GetElementPtr: case llvm.GetElementPtr:
// GetElementPtr does pointer arithmetic, changing the offset of the // GetElementPtr does pointer arithmetic, changing the offset of the
// pointer into the underlying object. // pointer into the underlying object.
var offset int64 var offset uint64
for i := 1; i < len(operands); i += 2 { for i := 1; i < len(operands); i += 2 {
index := operands[i].Int() index := operands[i].Uint()
elementSize := operands[i+1].Int() elementSize := operands[i+1].Uint()
if elementSize < 0 { if int64(elementSize) < 0 {
// This is a struct field. // This is a struct field.
offset += index offset += index
} else { } else {
@@ -673,14 +651,11 @@ func (r *runner) run(fn *function, params []value, parentMem *memoryView, indent
return nil, mem, r.errorAt(inst, err) return nil, mem, r.errorAt(inst, err)
} }
// GEP on fixed pointer value (for example, memory-mapped I/O). // GEP on fixed pointer value (for example, memory-mapped I/O).
ptrValue := operands[0].Uint() + uint64(offset) ptrValue := operands[0].Uint() + offset
locals[inst.localIndex] = makeLiteralInt(ptrValue, int(operands[0].len(r)*8)) locals[inst.localIndex] = makeLiteralInt(ptrValue, int(operands[0].len(r)*8))
continue continue
} }
ptr, err = ptr.addOffset(int64(offset)) ptr = ptr.addOffset(int64(offset))
if err != nil {
return nil, mem, r.errorAt(inst, err)
}
locals[inst.localIndex] = ptr locals[inst.localIndex] = ptr
if r.debug { if r.debug {
fmt.Fprintln(os.Stderr, indent+"gep:", operands, "->", ptr) fmt.Fprintln(os.Stderr, indent+"gep:", operands, "->", ptr)
@@ -778,10 +753,7 @@ func (r *runner) run(fn *function, params []value, parentMem *memoryView, indent
if inst.opcode == llvm.Add { if inst.opcode == llvm.Add {
// This likely means this is part of a // This likely means this is part of a
// unsafe.Pointer(uintptr(ptr) + offset) pattern. // unsafe.Pointer(uintptr(ptr) + offset) pattern.
lhsPtr, err = lhsPtr.addOffset(int64(rhs.Uint())) lhsPtr = lhsPtr.addOffset(int64(rhs.Uint()))
if err != nil {
return nil, mem, r.errorAt(inst, err)
}
locals[inst.localIndex] = lhsPtr locals[inst.localIndex] = lhsPtr
} else if inst.opcode == llvm.Xor && rhs.Uint() == 0 { } else if inst.opcode == llvm.Xor && rhs.Uint() == 0 {
// Special workaround for strings.noescape, see // Special workaround for strings.noescape, see
+3 -3
View File
@@ -517,12 +517,12 @@ func (v pointerValue) offset() uint32 {
// addOffset essentially does a GEP operation (pointer arithmetic): it adds the // addOffset essentially does a GEP operation (pointer arithmetic): it adds the
// offset to the pointer. It also checks that the offset doesn't overflow the // offset to the pointer. It also checks that the offset doesn't overflow the
// maximum offset size (which is 4GB). // maximum offset size (which is 4GB).
func (v pointerValue) addOffset(offset int64) (pointerValue, error) { func (v pointerValue) addOffset(offset int64) pointerValue {
result := pointerValue{v.pointer + uint64(offset)} result := pointerValue{v.pointer + uint64(offset)}
if checks && v.index() != result.index() { if checks && v.index() != result.index() {
return result, fmt.Errorf("interp: offset %d out of range for object %v", offset, v) panic("interp: offset out of range")
} }
return result, nil return result
} }
func (v pointerValue) len(r *runner) uint32 { func (v pointerValue) len(r *runner) uint32 {
-7
View File
@@ -10,8 +10,6 @@ target triple = "x86_64--linux"
@main.exposedValue1 = global i16 0 @main.exposedValue1 = global i16 0
@main.exposedValue2 = global i16 0 @main.exposedValue2 = global i16 0
@main.insertedValue = global {i8, i32, {float, {i64, i16}}} zeroinitializer @main.insertedValue = global {i8, i32, {float, {i64, i16}}} zeroinitializer
@main.gepArray = global [8 x i8] zeroinitializer
@main.negativeGEP = global ptr null
declare void @runtime.printint64(i64) unnamed_addr declare void @runtime.printint64(i64) unnamed_addr
@@ -90,11 +88,6 @@ entry:
%agg2 = insertvalue {i8, i32, {float, {i64, i16}}} %agg, i64 5, 2, 1, 0 %agg2 = insertvalue {i8, i32, {float, {i64, i16}}} %agg, i64 5, 2, 1, 0
store {i8, i32, {float, {i64, i16}}} %agg2, ptr @main.insertedValue store {i8, i32, {float, {i64, i16}}} %agg2, ptr @main.insertedValue
; negative GEP instruction
%ngep1 = getelementptr [8 x i8], ptr @main.negativeGEP, i32 0, i32 5
%ngep2 = getelementptr [8 x i8], ptr %ngep1, i32 0, i32 -3
store ptr %ngep2, ptr @main.negativeGEP
ret void ret void
} }
-2
View File
@@ -9,8 +9,6 @@ target triple = "x86_64--linux"
@main.exposedValue1 = global i16 0 @main.exposedValue1 = global i16 0
@main.exposedValue2 = local_unnamed_addr global i16 0 @main.exposedValue2 = local_unnamed_addr global i16 0
@main.insertedValue = local_unnamed_addr global { i8, i32, { float, { i64, i16 } } } zeroinitializer @main.insertedValue = local_unnamed_addr global { i8, i32, { float, { i64, i16 } } } zeroinitializer
@main.gepArray = local_unnamed_addr global [8 x i8] zeroinitializer
@main.negativeGEP = global ptr getelementptr inbounds (i8, ptr @main.negativeGEP, i64 2)
declare void @runtime.printint64(i64) unnamed_addr declare void @runtime.printint64(i64) unnamed_addr
+1 -4
View File
@@ -214,7 +214,7 @@ func listGorootMergeLinks(goroot, tinygoroot string, overrides map[string]bool)
return merges, nil return merges, nil
} }
// needsSyscallPackage returns whether the syscall package should be overridden // needsSyscallPackage returns whether the syscall package should be overriden
// with the TinyGo version. This is the case on some targets. // with the TinyGo version. This is the case on some targets.
func needsSyscallPackage(buildTags []string) bool { func needsSyscallPackage(buildTags []string) bool {
for _, tag := range buildTags { for _, tag := range buildTags {
@@ -232,7 +232,6 @@ func pathsToOverride(goMinor int, needsSyscallPackage bool) map[string]bool {
"": true, "": true,
"crypto/": true, "crypto/": true,
"crypto/rand/": false, "crypto/rand/": false,
"crypto/tls/": false,
"device/": false, "device/": false,
"examples/": false, "examples/": false,
"internal/": true, "internal/": true,
@@ -242,9 +241,7 @@ func pathsToOverride(goMinor int, needsSyscallPackage bool) map[string]bool {
"internal/task/": false, "internal/task/": false,
"machine/": false, "machine/": false,
"net/": true, "net/": true,
"net/http/": false,
"os/": true, "os/": true,
"os/user/": false,
"reflect/": false, "reflect/": false,
"runtime/": false, "runtime/": false,
"sync/": true, "sync/": true,
+5 -1
View File
@@ -22,8 +22,12 @@ func List(config *compileopts.Config, extraArgs, pkgs []string) (*exec.Cmd, erro
args = append(args, "-tags", strings.Join(config.BuildTags(), " ")) args = append(args, "-tags", strings.Join(config.BuildTags(), " "))
} }
args = append(args, pkgs...) args = append(args, pkgs...)
cgoEnabled := "0"
if config.CgoEnabled() {
cgoEnabled = "1"
}
cmd := exec.Command(filepath.Join(goenv.Get("GOROOT"), "bin", "go"), args...) cmd := exec.Command(filepath.Join(goenv.Get("GOROOT"), "bin", "go"), args...)
cmd.Env = append(os.Environ(), "GOROOT="+goroot, "GOOS="+config.GOOS(), "GOARCH="+config.GOARCH(), "CGO_ENABLED=1") cmd.Env = append(os.Environ(), "GOROOT="+goroot, "GOOS="+config.GOOS(), "GOARCH="+config.GOARCH(), "CGO_ENABLED="+cgoEnabled)
if config.Options.Directory != "" { if config.Options.Directory != "" {
cmd.Dir = config.Options.Directory cmd.Dir = config.Options.Directory
} }
+2 -22
View File
@@ -27,8 +27,6 @@ import (
"github.com/tinygo-org/tinygo/goenv" "github.com/tinygo-org/tinygo/goenv"
) )
var initFileVersions = func(info *types.Info) {}
// Program holds all packages and some metadata about the program as a whole. // Program holds all packages and some metadata about the program as a whole.
type Program struct { type Program struct {
config *compileopts.Config config *compileopts.Config
@@ -380,24 +378,6 @@ func (p *Package) Check() error {
typeErrors = append(typeErrors, err) typeErrors = append(typeErrors, err)
} }
checker.Importer = p checker.Importer = p
if p.Module.GoVersion != "" {
// Setting the Go version for a module makes sure the type checker
// errors out on language features not supported in that particular
// version.
checker.GoVersion = "go" + p.Module.GoVersion
} else {
// Version is not known, so use the currently installed Go version.
// This is needed for `tinygo run` for example.
// Normally we'd use goenv.GorootVersionString(), but for compatibility
// with Go 1.20 and below we need a version in the form of "go1.12" (no
// patch version).
major, minor, err := goenv.GetGorootVersion()
if err != nil {
return err
}
checker.GoVersion = fmt.Sprintf("go%d.%d", major, minor)
}
initFileVersions(&p.info)
// Do typechecking of the package. // Do typechecking of the package.
packageName := p.ImportPath packageName := p.ImportPath
@@ -430,7 +410,7 @@ func (p *Package) parseFiles() ([]*ast.File, error) {
var files []*ast.File var files []*ast.File
var fileErrs []error var fileErrs []error
// Parse all files (including CgoFiles). // Parse all files (incuding CgoFiles).
parseFile := func(file string) { parseFile := func(file string) {
if !filepath.IsAbs(file) { if !filepath.IsAbs(file) {
file = filepath.Join(p.Dir, file) file = filepath.Join(p.Dir, file)
@@ -467,7 +447,7 @@ func (p *Package) parseFiles() ([]*ast.File, error) {
if errs != nil { if errs != nil {
fileErrs = append(fileErrs, errs...) fileErrs = append(fileErrs, errs...)
} }
files = append(files, generated...) files = append(files, generated)
p.program.LDFlags = append(p.program.LDFlags, ldflags...) p.program.LDFlags = append(p.program.LDFlags, ldflags...)
} }
-17
View File
@@ -1,17 +0,0 @@
//go:build go1.22
// types.Info.FileVersions was added in Go 1.22, so we can only initialize it
// when built with Go 1.22.
package loader
import (
"go/ast"
"go/types"
)
func init() {
initFileVersions = func(info *types.Info) {
info.FileVersions = make(map[*ast.File]string)
}
}
+15 -20
View File
@@ -285,7 +285,7 @@ func Test(pkgName string, stdout, stderr io.Writer, options *compileopts.Options
// Tests are always run in the package directory. // Tests are always run in the package directory.
cmd.Dir = result.MainDir cmd.Dir = result.MainDir
// wasmtime is the default emulator used for `-target=wasip1`. wasmtime // wasmtime is the default emulator used for `-target=wasi`. wasmtime
// is a WebAssembly runtime CLI with WASI enabled by default. However, // is a WebAssembly runtime CLI with WASI enabled by default. However,
// only stdio are allowed by default. For example, while STDOUT routes // only stdio are allowed by default. For example, while STDOUT routes
// to the host, other files don't. It also does not inherit environment // to the host, other files don't. It also does not inherit environment
@@ -532,7 +532,7 @@ func Flash(pkgName, port string, options *compileopts.Options) error {
return fmt.Errorf("unknown flash method: %s", flashMethod) return fmt.Errorf("unknown flash method: %s", flashMethod)
} }
if options.Monitor { if options.Monitor {
return Monitor(result.Executable, "", config) return Monitor(result.Executable, "", options)
} }
return nil return nil
} }
@@ -1033,10 +1033,9 @@ func findFATMounts(options *compileopts.Options) ([]mountPoint, error) {
if fstype != "vfat" { if fstype != "vfat" {
continue continue
} }
fspath := strings.ReplaceAll(fields[1], "\\040", " ")
points = append(points, mountPoint{ points = append(points, mountPoint{
name: filepath.Base(fspath), name: filepath.Base(fields[1]),
path: fspath, path: fields[1],
}) })
} }
return points, nil return points, nil
@@ -1226,7 +1225,6 @@ func usage(command string) {
fmt.Fprintln(os.Stderr, " gdb: run/flash and immediately enter GDB") fmt.Fprintln(os.Stderr, " gdb: run/flash and immediately enter GDB")
fmt.Fprintln(os.Stderr, " lldb: run/flash and immediately enter LLDB") fmt.Fprintln(os.Stderr, " lldb: run/flash and immediately enter LLDB")
fmt.Fprintln(os.Stderr, " monitor: open communication port") fmt.Fprintln(os.Stderr, " monitor: open communication port")
fmt.Fprintln(os.Stderr, " ports: list available serial ports")
fmt.Fprintln(os.Stderr, " env: list environment variables used during build") fmt.Fprintln(os.Stderr, " env: list environment variables used during build")
fmt.Fprintln(os.Stderr, " list: run go list using the TinyGo root") fmt.Fprintln(os.Stderr, " list: run go list using the TinyGo root")
fmt.Fprintln(os.Stderr, " clean: empty cache directory ("+goenv.Get("GOCACHE")+")") fmt.Fprintln(os.Stderr, " clean: empty cache directory ("+goenv.Get("GOCACHE")+")")
@@ -1412,7 +1410,7 @@ func main() {
gc := flag.String("gc", "", "garbage collector to use (none, leaking, conservative)") gc := flag.String("gc", "", "garbage collector to use (none, leaking, conservative)")
panicStrategy := flag.String("panic", "print", "panic strategy (print, trap)") panicStrategy := flag.String("panic", "print", "panic strategy (print, trap)")
scheduler := flag.String("scheduler", "", "which scheduler to use (none, tasks, asyncify)") scheduler := flag.String("scheduler", "", "which scheduler to use (none, tasks, asyncify)")
serial := flag.String("serial", "", "which serial output to use (none, uart, usb, rtt)") serial := flag.String("serial", "", "which serial output to use (none, uart, usb)")
work := flag.Bool("work", false, "print the name of the temporary build directory and do not delete this directory on exit") work := flag.Bool("work", false, "print the name of the temporary build directory and do not delete this directory on exit")
interpTimeout := flag.Duration("interp-timeout", 180*time.Second, "interp optimization pass timeout") interpTimeout := flag.Duration("interp-timeout", 180*time.Second, "interp optimization pass timeout")
var tags buildutil.TagsFlag var tags buildutil.TagsFlag
@@ -1439,6 +1437,7 @@ func main() {
llvmFeatures := flag.String("llvm-features", "", "comma separated LLVM features to enable") llvmFeatures := flag.String("llvm-features", "", "comma separated LLVM features to enable")
cpuprofile := flag.String("cpuprofile", "", "cpuprofile output") cpuprofile := flag.String("cpuprofile", "", "cpuprofile output")
monitor := flag.Bool("monitor", false, "enable serial monitor") monitor := flag.Bool("monitor", false, "enable serial monitor")
info := flag.Bool("info", false, "print information")
baudrate := flag.Int("baudrate", 115200, "baudrate of serial monitor") baudrate := flag.Int("baudrate", 115200, "baudrate of serial monitor")
// Internal flags, that are only intended for TinyGo development. // Internal flags, that are only intended for TinyGo development.
@@ -1734,19 +1733,15 @@ func main() {
os.Exit(1) os.Exit(1)
} }
case "monitor": case "monitor":
config, err := builder.NewConfig(options) if *info {
handleCompilerError(err) serialPortInfo, err := ListSerialPorts()
err = Monitor("", *port, config) handleCompilerError(err)
handleCompilerError(err) for _, s := range serialPortInfo {
case "ports": fmt.Printf("%s %4s %4s %s\n", s.Name, s.VID, s.PID, s.Target)
serialPortInfo, err := ListSerialPorts() }
handleCompilerError(err) } else {
if len(serialPortInfo) == 0 { err := Monitor("", *port, options)
fmt.Println("No serial ports found.") handleCompilerError(err)
}
fmt.Printf("%-20s %-9s %s\n", "Port", "ID", "Boards")
for _, s := range serialPortInfo {
fmt.Printf("%-20s %4s:%4s %s\n", s.Name, s.VID, s.PID, s.Target)
} }
case "targets": case "targets":
specs, err := compileopts.GetTargetSpecs() specs, err := compileopts.GetTargetSpecs()
+6 -76
View File
@@ -15,13 +15,11 @@ import (
"reflect" "reflect"
"regexp" "regexp"
"runtime" "runtime"
"slices"
"strings" "strings"
"sync" "sync"
"testing" "testing"
"time" "time"
"github.com/aykevl/go-wasm"
"github.com/tinygo-org/tinygo/builder" "github.com/tinygo-org/tinygo/builder"
"github.com/tinygo-org/tinygo/compileopts" "github.com/tinygo-org/tinygo/compileopts"
"github.com/tinygo-org/tinygo/goenv" "github.com/tinygo-org/tinygo/goenv"
@@ -71,7 +69,6 @@ func TestBuild(t *testing.T) {
"json.go", "json.go",
"map.go", "map.go",
"math.go", "math.go",
"oldgo/",
"print.go", "print.go",
"reflect.go", "reflect.go",
"slice.go", "slice.go",
@@ -93,9 +90,6 @@ func TestBuild(t *testing.T) {
if minor >= 21 { if minor >= 21 {
tests = append(tests, "go1.21.go") tests = append(tests, "go1.21.go")
} }
if minor >= 22 {
tests = append(tests, "go1.22/")
}
if *testTarget != "" { if *testTarget != "" {
// This makes it possible to run one specific test (instead of all), // This makes it possible to run one specific test (instead of all),
@@ -179,7 +173,7 @@ func TestBuild(t *testing.T) {
}) })
t.Run("WASI", func(t *testing.T) { t.Run("WASI", func(t *testing.T) {
t.Parallel() t.Parallel()
runPlatTests(optionsFromTarget("wasip1", sema), tests, t) runPlatTests(optionsFromTarget("wasi", sema), tests, t)
}) })
} }
} }
@@ -192,10 +186,7 @@ func runPlatTests(options compileopts.Options, tests []string, t *testing.T) {
t.Fatal("failed to load target spec:", err) t.Fatal("failed to load target spec:", err)
} }
// FIXME: this should really be: isWebAssembly := options.Target == "wasi" || options.Target == "wasm" || (options.Target == "" && options.GOARCH == "wasm")
// isWebAssembly := strings.HasPrefix(spec.Triple, "wasm")
isWASI := strings.HasPrefix(options.Target, "wasi")
isWebAssembly := isWASI || strings.HasPrefix(options.Target, "wasm") || (options.Target == "" && strings.HasPrefix(options.GOARCH, "wasm"))
for _, name := range tests { for _, name := range tests {
if options.GOOS == "linux" && (options.GOARCH == "arm" || options.GOARCH == "386") { if options.GOOS == "linux" && (options.GOARCH == "arm" || options.GOARCH == "386") {
@@ -255,13 +246,13 @@ func runPlatTests(options compileopts.Options, tests []string, t *testing.T) {
runTest("alias.go", options, t, nil, nil) runTest("alias.go", options, t, nil, nil)
}) })
} }
if options.Target == "" || isWASI { if options.Target == "" || options.Target == "wasi" {
t.Run("filesystem.go", func(t *testing.T) { t.Run("filesystem.go", func(t *testing.T) {
t.Parallel() t.Parallel()
runTest("filesystem.go", options, t, nil, nil) runTest("filesystem.go", options, t, nil, nil)
}) })
} }
if options.Target == "" || options.Target == "wasm" || isWASI { if options.Target == "" || options.Target == "wasi" || options.Target == "wasm" {
t.Run("rand.go", func(t *testing.T) { t.Run("rand.go", func(t *testing.T) {
t.Parallel() t.Parallel()
runTest("rand.go", options, t, nil, nil) runTest("rand.go", options, t, nil, nil)
@@ -342,11 +333,8 @@ func runTestWithConfig(name string, t *testing.T, options compileopts.Options, c
path := TESTDATA + "/" + name path := TESTDATA + "/" + name
// Get the expected output for this test. // Get the expected output for this test.
txtpath := path[:len(path)-3] + ".txt" txtpath := path[:len(path)-3] + ".txt"
pkgName := "./" + path
if path[len(path)-1] == '/' { if path[len(path)-1] == '/' {
txtpath = path + "out.txt" txtpath = path + "out.txt"
options.Directory = path
pkgName = "."
} }
expected, err := os.ReadFile(txtpath) expected, err := os.ReadFile(txtpath)
if err != nil { if err != nil {
@@ -360,7 +348,7 @@ func runTestWithConfig(name string, t *testing.T, options compileopts.Options, c
// Build the test binary. // Build the test binary.
stdout := &bytes.Buffer{} stdout := &bytes.Buffer{}
_, err = buildAndRun(pkgName, config, stdout, cmdArgs, environmentVars, time.Minute, func(cmd *exec.Cmd, result builder.BuildResult) error { _, err = buildAndRun("./"+path, config, stdout, cmdArgs, environmentVars, time.Minute, func(cmd *exec.Cmd, result builder.BuildResult) error {
return cmd.Run() return cmd.Run()
}) })
if err != nil { if err != nil {
@@ -409,64 +397,6 @@ func runTestWithConfig(name string, t *testing.T, options compileopts.Options, c
} }
} }
// Test WebAssembly files for certain properties.
func TestWebAssembly(t *testing.T) {
t.Parallel()
type testCase struct {
name string
panicStrategy string
imports []string
}
for _, tc := range []testCase{
// Test whether there really are no imports when using -panic=trap. This
// tests the bugfix for https://github.com/tinygo-org/tinygo/issues/4161.
{name: "panic-default", imports: []string{"wasi_snapshot_preview1.fd_write"}},
{name: "panic-trap", panicStrategy: "trap", imports: []string{}},
} {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
tmpdir := t.TempDir()
options := optionsFromTarget("wasi", sema)
options.PanicStrategy = tc.panicStrategy
config, err := builder.NewConfig(&options)
if err != nil {
t.Fatal(err)
}
result, err := builder.Build("testdata/trivialpanic.go", ".wasm", tmpdir, config)
if err != nil {
t.Fatal("failed to build binary:", err)
}
f, err := os.Open(result.Binary)
if err != nil {
t.Fatal("could not open output binary:", err)
}
defer f.Close()
module, err := wasm.Parse(f)
if err != nil {
t.Fatal("could not parse output binary:", err)
}
// Test the list of imports.
if tc.imports != nil {
var imports []string
for _, section := range module.Sections {
switch section := section.(type) {
case *wasm.SectionImport:
for _, symbol := range section.Entries {
imports = append(imports, symbol.Module+"."+symbol.Field)
}
}
}
if !slices.Equal(imports, tc.imports) {
t.Errorf("import list not as expected!\nexpected: %v\nactual: %v", tc.imports, imports)
}
}
})
}
}
func TestTest(t *testing.T) { func TestTest(t *testing.T) {
t.Parallel() t.Parallel()
@@ -495,7 +425,7 @@ func TestTest(t *testing.T) {
// Node/Wasmtime // Node/Wasmtime
targ{"WASM", optionsFromTarget("wasm", sema)}, targ{"WASM", optionsFromTarget("wasm", sema)},
targ{"WASI", optionsFromTarget("wasip1", sema)}, targ{"WASI", optionsFromTarget("wasi", sema)},
) )
} }
for _, targ := range targs { for _, targ := range targs {
+40 -151
View File
@@ -1,7 +1,6 @@
package main package main
import ( import (
"bufio"
"debug/dwarf" "debug/dwarf"
"debug/elf" "debug/elf"
"debug/macho" "debug/macho"
@@ -10,7 +9,6 @@ import (
"fmt" "fmt"
"go/token" "go/token"
"io" "io"
"net"
"os" "os"
"os/signal" "os/signal"
"regexp" "regexp"
@@ -19,6 +17,7 @@ import (
"time" "time"
"github.com/mattn/go-tty" "github.com/mattn/go-tty"
"github.com/tinygo-org/tinygo/builder"
"github.com/tinygo-org/tinygo/compileopts" "github.com/tinygo-org/tinygo/compileopts"
"go.bug.st/serial" "go.bug.st/serial"
@@ -26,152 +25,45 @@ import (
) )
// Monitor connects to the given port and reads/writes the serial port. // Monitor connects to the given port and reads/writes the serial port.
func Monitor(executable, port string, config *compileopts.Config) error { func Monitor(executable, port string, options *compileopts.Options) error {
const timeout = time.Second * 3 config, err := builder.NewConfig(options)
var exit func() // function to be called before exiting if err != nil {
var serialConn io.ReadWriter return err
if config.Options.Serial == "rtt" {
// Use the RTT interface, which is documented (in part) here:
// https://wiki.segger.com/RTT
// Try to find the "machine.rttSerialInstance" symbol, which is the RTT
// control block.
file, err := elf.Open(executable)
if err != nil {
return fmt.Errorf("could not open ELF file to determine RTT control block: %w", err)
}
defer file.Close()
symbols, err := file.Symbols()
if err != nil {
return fmt.Errorf("could not read ELF symbol table to determine RTT control block: %w", err)
}
var address uint64
for _, symbol := range symbols {
if symbol.Name == "machine.rttSerialInstance" {
address = symbol.Value
break
}
}
if address == 0 {
return fmt.Errorf("could not find RTT control block in ELF file")
}
// Start an openocd process in the background.
args, err := config.OpenOCDConfiguration()
if err != nil {
return err
}
args = append(args,
"-c", fmt.Sprintf("rtt setup 0x%x 16 \"SEGGER RTT\"", address),
"-c", "init",
"-c", "rtt server start 0 0")
cmd := executeCommand(config.Options, "openocd", args...)
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
cmd.Stdout = os.Stdout
err = cmd.Start()
if err != nil {
return err
}
defer cmd.Process.Kill()
exit = func() {
// Make sure the openocd process is terminated at exit.
// This does not happen through the defer above when exiting through
// os.Exit.
cmd.Process.Kill()
}
// Read the stderr, which logs various important messages we need.
r := bufio.NewReader(stderr)
var telnet net.Conn
var timeoutAt time.Time
for {
// Read the next line from the openocd process.
lineBytes, err := r.ReadBytes('\n')
if err != nil {
return err
}
line := string(lineBytes)
if line == "Info : rtt: No control block found\n" {
// Message that is sent back when OpenOCD can't find the control
// block after a 'rtt start' message.
if time.Now().After(timeoutAt) {
return fmt.Errorf("RTT timeout (could not locate RTT control block at 0x%08x)", address)
}
time.Sleep(time.Millisecond * 100)
telnet.Write([]byte("rtt start\r\n"))
} else if strings.HasPrefix(line, "Info : Listening on port") {
// We need two different ports for controlling OpenOCD
// (typically port 4444) and the RTT channel 0 socket (arbitrary
// port).
var port int
var protocol string
fmt.Sscanf(line, "Info : Listening on port %d for %s connections\n", &port, &protocol)
if protocol == "telnet" && telnet == nil {
// Connect to the "telnet" command line interface.
telnet, err = net.Dial("tcp4", fmt.Sprintf("localhost:%d", port))
if err != nil {
return err
}
// Tell OpenOCD to start scanning for the RTT control block.
telnet.Write([]byte("rtt start\r\n"))
// Also make sure we will time out if the control block just
// can't be found.
timeoutAt = time.Now().Add(timeout)
} else if protocol == "rtt" {
// Connect to the RTT channel, for both stdin and stdout.
conn, err := net.Dial("tcp4", fmt.Sprintf("localhost:%d", port))
if err != nil {
return err
}
serialConn = conn
}
} else if strings.HasPrefix(line, "Info : rtt: Control block found at") {
// Connection established!
break
}
}
} else { // -serial=uart or -serial=usb
var err error
wait := 300
for i := 0; i <= wait; i++ {
port, err = getDefaultPort(port, config.Target.SerialPort)
if err != nil {
if i < wait {
time.Sleep(10 * time.Millisecond)
continue
}
return err
}
break
}
br := config.Options.BaudRate
if br <= 0 {
br = 115200
}
wait = 300
var p serial.Port
for i := 0; i <= wait; i++ {
p, err = serial.Open(port, &serial.Mode{BaudRate: br})
if err != nil {
if i < wait {
time.Sleep(10 * time.Millisecond)
continue
}
return err
}
serialConn = p
break
}
defer p.Close()
} }
wait := 300
for i := 0; i <= wait; i++ {
port, err = getDefaultPort(port, config.Target.SerialPort)
if err != nil {
if i < wait {
time.Sleep(10 * time.Millisecond)
continue
}
return err
}
break
}
br := options.BaudRate
if br <= 0 {
br = 115200
}
wait = 300
var p serial.Port
for i := 0; i <= wait; i++ {
p, err = serial.Open(port, &serial.Mode{BaudRate: br})
if err != nil {
if i < wait {
time.Sleep(10 * time.Millisecond)
continue
}
return err
}
break
}
defer p.Close()
tty, err := tty.Open() tty, err := tty.Open()
if err != nil { if err != nil {
return err return err
@@ -185,9 +77,6 @@ func Monitor(executable, port string, config *compileopts.Config) error {
go func() { go func() {
<-sig <-sig
tty.Close() tty.Close()
if exit != nil {
exit()
}
os.Exit(0) os.Exit(0)
}() }()
@@ -199,7 +88,7 @@ func Monitor(executable, port string, config *compileopts.Config) error {
buf := make([]byte, 100*1024) buf := make([]byte, 100*1024)
var line []byte var line []byte
for { for {
n, err := serialConn.Read(buf) n, err := p.Read(buf)
if err != nil { if err != nil {
errCh <- fmt.Errorf("read error: %w", err) errCh <- fmt.Errorf("read error: %w", err)
return return
@@ -235,7 +124,7 @@ func Monitor(executable, port string, config *compileopts.Config) error {
if r == 0 { if r == 0 {
continue continue
} }
serialConn.Write([]byte(string(r))) p.Write([]byte(string(r)))
} }
}() }()
-35
View File
@@ -1,35 +0,0 @@
ignoreGeneratedHeader = false
severity = "warning"
confidence = 0.8
errorCode = 0
warningCode = 0
# Enable these as we fix them
[rule.blank-imports]
Exclude=["src/os/file_other.go"]
[rule.context-as-argument]
[rule.context-keys-type]
[rule.dot-imports]
Exclude=["**/*_test.go"]
[rule.error-return]
[rule.error-strings]
[rule.error-naming]
[rule.exported]
Exclude=["src/reflect/*.go"]
[rule.increment-decrement]
[rule.var-naming]
Exclude=["src/os/*.go"]
[rule.var-declaration]
#[rule.package-comments]
[rule.range]
[rule.receiver-naming]
[rule.time-naming]
[rule.unexported-return]
#[rule.indent-error-flow]
[rule.errorf]
#[rule.empty-block]
[rule.superfluous-else]
#[rule.unused-parameter]
[rule.unreachable-code]
Exclude=["src/reflect/visiblefields_test.go", "src/reflect/all_test.go"]
#[rule.redefines-builtin-id]
+1 -4
View File
@@ -1,7 +1,4 @@
//go:build nrf || (stm32 && !(stm32f103 || stm32l0x1)) || (sam && atsamd51) || (sam && atsame5x) || esp32c3 //go:build nrf || stm32 || (sam && atsamd51) || (sam && atsame5x)
// If you update the above build constraint, you'll probably also need to update
// src/runtime/rand_hwrng.go.
package rand package rand
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build linux && !baremetal && !wasip1 //go:build linux && !baremetal && !wasi
// This implementation of crypto/rand uses the /dev/urandom pseudo-file to // This implementation of crypto/rand uses the /dev/urandom pseudo-file to
// generate random numbers. // generate random numbers.
-447
View File
@@ -1,447 +0,0 @@
// TINYGO: The following is copied and modified from Go 1.19.3 official implementation.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tls
import (
"context"
"crypto"
"crypto/x509"
"io"
"net"
"sync"
"time"
)
// CurveID is the type of a TLS identifier for an elliptic curve. See
// https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
//
// In TLS 1.3, this type is called NamedGroup, but at this time this library
// only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.
type CurveID uint16
// ConnectionState records basic TLS details about the connection.
type ConnectionState struct {
// TINYGO: empty; TLS connection offloaded to device
}
// ClientAuthType declares the policy the server will follow for
// TLS Client Authentication.
type ClientAuthType int
// ClientSessionCache is a cache of ClientSessionState objects that can be used
// by a client to resume a TLS session with a given server. ClientSessionCache
// implementations should expect to be called concurrently from different
// goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
// SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
// are supported via this interface.
type ClientSessionCache interface {
// Get searches for a ClientSessionState associated with the given key.
// On return, ok is true if one was found.
Get(sessionKey string) (session *ClientSessionState, ok bool)
// Put adds the ClientSessionState to the cache with the given key. It might
// get called multiple times in a connection if a TLS 1.3 server provides
// more than one session ticket. If called with a nil *ClientSessionState,
// it should remove the cache entry.
Put(sessionKey string, cs *ClientSessionState)
}
//go:generate stringer -type=SignatureScheme,CurveID,ClientAuthType -output=common_string.go
// SignatureScheme identifies a signature algorithm supported by TLS. See
// RFC 8446, Section 4.2.3.
type SignatureScheme uint16
// ClientHelloInfo contains information from a ClientHello message in order to
// guide application logic in the GetCertificate and GetConfigForClient callbacks.
type ClientHelloInfo struct {
// CipherSuites lists the CipherSuites supported by the client (e.g.
// TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
CipherSuites []uint16
// ServerName indicates the name of the server requested by the client
// in order to support virtual hosting. ServerName is only set if the
// client is using SNI (see RFC 4366, Section 3.1).
ServerName string
// SupportedCurves lists the elliptic curves supported by the client.
// SupportedCurves is set only if the Supported Elliptic Curves
// Extension is being used (see RFC 4492, Section 5.1.1).
SupportedCurves []CurveID
// SupportedPoints lists the point formats supported by the client.
// SupportedPoints is set only if the Supported Point Formats Extension
// is being used (see RFC 4492, Section 5.1.2).
SupportedPoints []uint8
// SignatureSchemes lists the signature and hash schemes that the client
// is willing to verify. SignatureSchemes is set only if the Signature
// Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
SignatureSchemes []SignatureScheme
// SupportedProtos lists the application protocols supported by the client.
// SupportedProtos is set only if the Application-Layer Protocol
// Negotiation Extension is being used (see RFC 7301, Section 3.1).
//
// Servers can select a protocol by setting Config.NextProtos in a
// GetConfigForClient return value.
SupportedProtos []string
// SupportedVersions lists the TLS versions supported by the client.
// For TLS versions less than 1.3, this is extrapolated from the max
// version advertised by the client, so values other than the greatest
// might be rejected if used.
SupportedVersions []uint16
// Conn is the underlying net.Conn for the connection. Do not read
// from, or write to, this connection; that will cause the TLS
// connection to fail.
Conn net.Conn
// config is embedded by the GetCertificate or GetConfigForClient caller,
// for use with SupportsCertificate.
config *Config
// ctx is the context of the handshake that is in progress.
ctx context.Context
}
// CertificateRequestInfo contains information from a server's
// CertificateRequest message, which is used to demand a certificate and proof
// of control from a client.
type CertificateRequestInfo struct {
// AcceptableCAs contains zero or more, DER-encoded, X.501
// Distinguished Names. These are the names of root or intermediate CAs
// that the server wishes the returned certificate to be signed by. An
// empty slice indicates that the server has no preference.
AcceptableCAs [][]byte
// SignatureSchemes lists the signature schemes that the server is
// willing to verify.
SignatureSchemes []SignatureScheme
// Version is the TLS version that was negotiated for this connection.
Version uint16
// ctx is the context of the handshake that is in progress.
ctx context.Context
}
// RenegotiationSupport enumerates the different levels of support for TLS
// renegotiation. TLS renegotiation is the act of performing subsequent
// handshakes on a connection after the first. This significantly complicates
// the state machine and has been the source of numerous, subtle security
// issues. Initiating a renegotiation is not supported, but support for
// accepting renegotiation requests may be enabled.
//
// Even when enabled, the server may not change its identity between handshakes
// (i.e. the leaf certificate must be the same). Additionally, concurrent
// handshake and application data flow is not permitted so renegotiation can
// only be used with protocols that synchronise with the renegotiation, such as
// HTTPS.
//
// Renegotiation is not defined in TLS 1.3.
type RenegotiationSupport int
// A Config structure is used to configure a TLS client or server.
// After one has been passed to a TLS function it must not be
// modified. A Config may be reused; the tls package will also not
// modify it.
type Config struct {
// Rand provides the source of entropy for nonces and RSA blinding.
// If Rand is nil, TLS uses the cryptographic random reader in package
// crypto/rand.
// The Reader must be safe for use by multiple goroutines.
Rand io.Reader
// Time returns the current time as the number of seconds since the epoch.
// If Time is nil, TLS uses time.Now.
Time func() time.Time
// Certificates contains one or more certificate chains to present to the
// other side of the connection. The first certificate compatible with the
// peer's requirements is selected automatically.
//
// Server configurations must set one of Certificates, GetCertificate or
// GetConfigForClient. Clients doing client-authentication may set either
// Certificates or GetClientCertificate.
//
// Note: if there are multiple Certificates, and they don't have the
// optional field Leaf set, certificate selection will incur a significant
// per-handshake performance cost.
Certificates []Certificate
// NameToCertificate maps from a certificate name to an element of
// Certificates. Note that a certificate name can be of the form
// '*.example.com' and so doesn't have to be a domain name as such.
//
// Deprecated: NameToCertificate only allows associating a single
// certificate with a given name. Leave this field nil to let the library
// select the first compatible chain from Certificates.
NameToCertificate map[string]*Certificate
// GetCertificate returns a Certificate based on the given
// ClientHelloInfo. It will only be called if the client supplies SNI
// information or if Certificates is empty.
//
// If GetCertificate is nil or returns nil, then the certificate is
// retrieved from NameToCertificate. If NameToCertificate is nil, the
// best element of Certificates will be used.
//
// Once a Certificate is returned it should not be modified.
GetCertificate func(*ClientHelloInfo) (*Certificate, error)
// GetClientCertificate, if not nil, is called when a server requests a
// certificate from a client. If set, the contents of Certificates will
// be ignored.
//
// If GetClientCertificate returns an error, the handshake will be
// aborted and that error will be returned. Otherwise
// GetClientCertificate must return a non-nil Certificate. If
// Certificate.Certificate is empty then no certificate will be sent to
// the server. If this is unacceptable to the server then it may abort
// the handshake.
//
// GetClientCertificate may be called multiple times for the same
// connection if renegotiation occurs or if TLS 1.3 is in use.
//
// Once a Certificate is returned it should not be modified.
GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
// GetConfigForClient, if not nil, is called after a ClientHello is
// received from a client. It may return a non-nil Config in order to
// change the Config that will be used to handle this connection. If
// the returned Config is nil, the original Config will be used. The
// Config returned by this callback may not be subsequently modified.
//
// If GetConfigForClient is nil, the Config passed to Server() will be
// used for all connections.
//
// If SessionTicketKey was explicitly set on the returned Config, or if
// SetSessionTicketKeys was called on the returned Config, those keys will
// be used. Otherwise, the original Config keys will be used (and possibly
// rotated if they are automatically managed).
GetConfigForClient func(*ClientHelloInfo) (*Config, error)
// VerifyPeerCertificate, if not nil, is called after normal
// certificate verification by either a TLS client or server. It
// receives the raw ASN.1 certificates provided by the peer and also
// any verified chains that normal processing found. If it returns a
// non-nil error, the handshake is aborted and that error results.
//
// If normal verification fails then the handshake will abort before
// considering this callback. If normal verification is disabled (on the
// client when InsecureSkipVerify is set, or on a server when ClientAuth is
// RequestClientCert or RequireAnyClientCert), then this callback will be
// considered but the verifiedChains argument will always be nil. When
// ClientAuth is NoClientCert, this callback is not called on the server.
// rawCerts may be empty on the server if ClientAuth is RequestClientCert or
// VerifyClientCertIfGiven.
//
// This callback is not invoked on resumed connections, as certificates are
// not re-verified on resumption.
//
// verifiedChains and its contents should not be modified.
VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
// VerifyConnection, if not nil, is called after normal certificate
// verification and after VerifyPeerCertificate by either a TLS client
// or server. If it returns a non-nil error, the handshake is aborted
// and that error results.
//
// If normal verification fails then the handshake will abort before
// considering this callback. This callback will run for all connections,
// including resumptions, regardless of InsecureSkipVerify or ClientAuth
// settings.
VerifyConnection func(ConnectionState) error
// RootCAs defines the set of root certificate authorities
// that clients use when verifying server certificates.
// If RootCAs is nil, TLS uses the host's root CA set.
RootCAs *x509.CertPool
// NextProtos is a list of supported application level protocols, in
// order of preference. If both peers support ALPN, the selected
// protocol will be one from this list, and the connection will fail
// if there is no mutually supported protocol. If NextProtos is empty
// or the peer doesn't support ALPN, the connection will succeed and
// ConnectionState.NegotiatedProtocol will be empty.
NextProtos []string
// ServerName is used to verify the hostname on the returned
// certificates unless InsecureSkipVerify is given. It is also included
// in the client's handshake to support virtual hosting unless it is
// an IP address.
ServerName string
// ClientAuth determines the server's policy for
// TLS Client Authentication. The default is NoClientCert.
ClientAuth ClientAuthType
// ClientCAs defines the set of root certificate authorities
// that servers use if required to verify a client certificate
// by the policy in ClientAuth.
ClientCAs *x509.CertPool
// InsecureSkipVerify controls whether a client verifies the server's
// certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
// accepts any certificate presented by the server and any host name in that
// certificate. In this mode, TLS is susceptible to machine-in-the-middle
// attacks unless custom verification is used. This should be used only for
// testing or in combination with VerifyConnection or VerifyPeerCertificate.
InsecureSkipVerify bool
// CipherSuites is a list of enabled TLS 1.01.2 cipher suites. The order of
// the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.
//
// If CipherSuites is nil, a safe default list is used. The default cipher
// suites might change over time.
CipherSuites []uint16
// PreferServerCipherSuites is a legacy field and has no effect.
//
// It used to control whether the server would follow the client's or the
// server's preference. Servers now select the best mutually supported
// cipher suite based on logic that takes into account inferred client
// hardware, server hardware, and security.
//
// Deprecated: PreferServerCipherSuites is ignored.
PreferServerCipherSuites bool
// SessionTicketsDisabled may be set to true to disable session ticket and
// PSK (resumption) support. Note that on clients, session ticket support is
// also disabled if ClientSessionCache is nil.
SessionTicketsDisabled bool
// SessionTicketKey is used by TLS servers to provide session resumption.
// See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
// with random data before the first server handshake.
//
// Deprecated: if this field is left at zero, session ticket keys will be
// automatically rotated every day and dropped after seven days. For
// customizing the rotation schedule or synchronizing servers that are
// terminating connections for the same host, use SetSessionTicketKeys.
SessionTicketKey [32]byte
// ClientSessionCache is a cache of ClientSessionState entries for TLS
// session resumption. It is only used by clients.
ClientSessionCache ClientSessionCache
// UnwrapSession is called on the server to turn a ticket/identity
// previously produced by [WrapSession] into a usable session.
//
// UnwrapSession will usually either decrypt a session state in the ticket
// (for example with [Config.EncryptTicket]), or use the ticket as a handle
// to recover a previously stored state. It must use [ParseSessionState] to
// deserialize the session state.
//
// If UnwrapSession returns an error, the connection is terminated. If it
// returns (nil, nil), the session is ignored. crypto/tls may still choose
// not to resume the returned session.
UnwrapSession func(identity []byte, cs ConnectionState) (*SessionState, error)
// WrapSession is called on the server to produce a session ticket/identity.
//
// WrapSession must serialize the session state with [SessionState.Bytes].
// It may then encrypt the serialized state (for example with
// [Config.DecryptTicket]) and use it as the ticket, or store the state and
// return a handle for it.
//
// If WrapSession returns an error, the connection is terminated.
//
// Warning: the return value will be exposed on the wire and to clients in
// plaintext. The application is in charge of encrypting and authenticating
// it (and rotating keys) or returning high-entropy identifiers. Failing to
// do so correctly can compromise current, previous, and future connections
// depending on the protocol version.
WrapSession func(ConnectionState, *SessionState) ([]byte, error)
// MinVersion contains the minimum TLS version that is acceptable.
//
// By default, TLS 1.2 is currently used as the minimum when acting as a
// client, and TLS 1.0 when acting as a server. TLS 1.0 is the minimum
// supported by this package, both as a client and as a server.
//
// The client-side default can temporarily be reverted to TLS 1.0 by
// including the value "x509sha1=1" in the GODEBUG environment variable.
// Note that this option will be removed in Go 1.19 (but it will still be
// possible to set this field to VersionTLS10 explicitly).
MinVersion uint16
// MaxVersion contains the maximum TLS version that is acceptable.
//
// By default, the maximum version supported by this package is used,
// which is currently TLS 1.3.
MaxVersion uint16
// CurvePreferences contains the elliptic curves that will be used in
// an ECDHE handshake, in preference order. If empty, the default will
// be used. The client will use the first preference as the type for
// its key share in TLS 1.3. This may change in the future.
CurvePreferences []CurveID
// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
// When true, the largest possible TLS record size is always used. When
// false, the size of TLS records may be adjusted in an attempt to
// improve latency.
DynamicRecordSizingDisabled bool
// Renegotiation controls what types of renegotiation are supported.
// The default, none, is correct for the vast majority of applications.
Renegotiation RenegotiationSupport
// KeyLogWriter optionally specifies a destination for TLS master secrets
// in NSS key log format that can be used to allow external programs
// such as Wireshark to decrypt TLS connections.
// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
// Use of KeyLogWriter compromises security and should only be
// used for debugging.
KeyLogWriter io.Writer
// mutex protects sessionTicketKeys and autoSessionTicketKeys.
mutex sync.RWMutex
// sessionTicketKeys contains zero or more ticket keys. If set, it means
// the keys were set with SessionTicketKey or SetSessionTicketKeys. The
// first key is used for new tickets and any subsequent keys can be used to
// decrypt old tickets. The slice contents are not protected by the mutex
// and are immutable.
sessionTicketKeys []ticketKey
// autoSessionTicketKeys is like sessionTicketKeys but is owned by the
// auto-rotation logic. See Config.ticketKeys.
autoSessionTicketKeys []ticketKey
}
// ticketKey is the internal representation of a session ticket key.
type ticketKey struct {
aesKey [16]byte
hmacKey [16]byte
// created is the time at which this ticket key was created. See Config.ticketKeys.
created time.Time
}
// A Certificate is a chain of one or more certificates, leaf first.
type Certificate struct {
Certificate [][]byte
// PrivateKey contains the private key corresponding to the public key in
// Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
// For a server up to TLS 1.2, it can also implement crypto.Decrypter with
// an RSA PublicKey.
PrivateKey crypto.PrivateKey
// SupportedSignatureAlgorithms is an optional list restricting what
// signature algorithms the PrivateKey can be used for.
SupportedSignatureAlgorithms []SignatureScheme
// OCSPStaple contains an optional OCSP response which will be served
// to clients that request it.
OCSPStaple []byte
// SignedCertificateTimestamps contains an optional list of Signed
// Certificate Timestamps which will be served to clients that request it.
SignedCertificateTimestamps [][]byte
// Leaf is the parsed form of the leaf certificate, which may be initialized
// using x509.ParseCertificate to reduce per-handshake processing. If nil,
// the leaf certificate will be parsed as needed.
Leaf *x509.Certificate
}
-16
View File
@@ -1,16 +0,0 @@
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tls
// A SessionState is a resumable session.
type SessionState struct {
}
// ClientSessionState contains the state needed by a client to
// resume a previous TLS session.
type ClientSessionState struct {
ticket []byte
session *SessionState
}
-114
View File
@@ -1,114 +0,0 @@
// TINYGO: The following is copied and modified from Go 1.21.4 official implementation.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package tls partially implements TLS 1.2, as specified in RFC 5246,
// and TLS 1.3, as specified in RFC 8446.
package tls
// BUG(agl): The crypto/tls package only implements some countermeasures
// against Lucky13 attacks on CBC-mode encryption, and only on SHA1
// variants. See http://www.isg.rhul.ac.uk/tls/TLStiming.pdf and
// https://www.imperialviolet.org/2013/02/04/luckythirteen.html.
import (
"context"
"errors"
"fmt"
"net"
)
// Client returns a new TLS client side connection
// using conn as the underlying transport.
// The config cannot be nil: users must set either ServerName or
// InsecureSkipVerify in the config.
func Client(conn net.Conn, config *Config) *net.TLSConn {
panic("tls.Client() not implemented")
return nil
}
// A listener implements a network listener (net.Listener) for TLS connections.
type listener struct {
net.Listener
config *Config
}
// NewListener creates a Listener which accepts connections from an inner
// Listener and wraps each connection with Server.
// The configuration config must be non-nil and must include
// at least one certificate or else set GetCertificate.
func NewListener(inner net.Listener, config *Config) net.Listener {
l := new(listener)
l.Listener = inner
l.config = config
return l
}
// DialWithDialer connects to the given network address using dialer.Dial and
// then initiates a TLS handshake, returning the resulting TLS connection. Any
// timeout or deadline given in the dialer apply to connection and TLS
// handshake as a whole.
//
// DialWithDialer interprets a nil configuration as equivalent to the zero
// configuration; see the documentation of Config for the defaults.
//
// DialWithDialer uses context.Background internally; to specify the context,
// use Dialer.DialContext with NetDialer set to the desired dialer.
func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*net.TLSConn, error) {
switch network {
case "tcp", "tcp4":
default:
return nil, fmt.Errorf("Network %s not supported", network)
}
return net.DialTLS(addr)
}
// Dial connects to the given network address using net.Dial
// and then initiates a TLS handshake, returning the resulting
// TLS connection.
// Dial interprets a nil configuration as equivalent to
// the zero configuration; see the documentation of Config
// for the defaults.
func Dial(network, addr string, config *Config) (*net.TLSConn, error) {
return DialWithDialer(new(net.Dialer), network, addr, config)
}
// Dialer dials TLS connections given a configuration and a Dialer for the
// underlying connection.
type Dialer struct {
// NetDialer is the optional dialer to use for the TLS connections'
// underlying TCP connections.
// A nil NetDialer is equivalent to the net.Dialer zero value.
NetDialer *net.Dialer
// Config is the TLS configuration to use for new connections.
// A nil configuration is equivalent to the zero
// configuration; see the documentation of Config for the
// defaults.
Config *Config
}
// DialContext connects to the given network address and initiates a TLS
// handshake, returning the resulting TLS connection.
//
// The provided Context must be non-nil. If the context expires before
// the connection is complete, an error is returned. Once successfully
// connected, any expiration of the context will not affect the
// connection.
//
// The returned Conn, if any, will always be of type *Conn.
func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
return nil, errors.New("tls:DialContext not implmented")
}
// LoadX509KeyPair reads and parses a public/private key pair from a pair
// of files. The files must contain PEM encoded data. The certificate file
// may contain intermediate certificates following the leaf certificate to
// form a certificate chain. On successful return, Certificate.Leaf will
// be nil because the parsed form of the certificate is not retained.
func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
return Certificate{}, errors.New("tls:LoadX509KeyPair not implemented")
}
-18
View File
@@ -1,18 +0,0 @@
// this is intended to be used as wasm32-unknown-unknown module.
// to compile it, run:
// tinygo build -size short -o hello-unknown.wasm -target wasm-unknown -gc=leaking -no-debug ./src/examples/hello-wasm-unknown/
package main
var x int32
//go:wasmimport hosted echo_i32
func echo(x int32)
//go:export update
func update() {
x++
echo(x)
}
func main() {
}
+2 -6
View File
@@ -1,6 +1,6 @@
// to override the USB Manufacturer or Product names: // to override the USB Manufacturer or Product names:
// //
// tinygo flash -target circuitplay-express -ldflags="-X main.usbManufacturer='TinyGopher Labs' -X main.usbProduct='GopherKeyboard' -X main.usbSerial='XXXXX'" examples/hid-keyboard // tinygo flash -target circuitplay-express -ldflags="-X main.usbManufacturer='TinyGopher Labs' -X main.usbProduct='GopherKeyboard'" examples/hid-keyboard
// //
// you can also override the VID/PID. however, only set this if you know what you are doing, // you can also override the VID/PID. however, only set this if you know what you are doing,
// since changing it can make it difficult to reflash some devices. // since changing it can make it difficult to reflash some devices.
@@ -15,7 +15,7 @@ import (
) )
var usbVID, usbPID string var usbVID, usbPID string
var usbManufacturer, usbProduct, usbSerial string var usbManufacturer, usbProduct string
func main() { func main() {
button := machine.BUTTON button := machine.BUTTON
@@ -49,8 +49,4 @@ func init() {
if usbProduct != "" { if usbProduct != "" {
usb.Product = usbProduct usb.Product = usbProduct
} }
if usbSerial != "" {
usb.Serial = usbSerial
}
} }
+14 -78
View File
@@ -1,14 +1,5 @@
package bytealg package bytealg
// Some code in this file has been copied from the Go source code, and has
// copyright of their original authors:
//
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// This is indicated specifically in the file.
const ( const (
// Index can search any valid length of string. // Index can search any valid length of string.
@@ -57,7 +48,7 @@ func Count(b []byte, c byte) int {
// Count the number of instances of a byte in a string. // Count the number of instances of a byte in a string.
func CountString(s string, c byte) int { func CountString(s string, c byte) int {
// Use a simple implementation, as there is no intrinsic that does this like we want. // Use a simple implementation, as there is no intrinsic that does this like we want.
// Currently, the compiler does not generate zero-copy byte-string conversions, so this needs to be separate from Count. // Currently, the compiler does not generate zero-copy byte-string conversions, so this needs to be seperate from Count.
n := 0 n := 0
for i := 0; i < len(s); i++ { for i := 0; i < len(s); i++ {
if s[i] == c { if s[i] == c {
@@ -134,6 +125,10 @@ func IndexString(str, sub string) int {
return -1 return -1
} }
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The following code has been copied from the Go 1.15 release tree. // The following code has been copied from the Go 1.15 release tree.
// PrimeRK is the prime base used in Rabin-Karp algorithm. // PrimeRK is the prime base used in Rabin-Karp algorithm.
@@ -141,8 +136,6 @@ const PrimeRK = 16777619
// HashStrBytes returns the hash and the appropriate multiplicative // HashStrBytes returns the hash and the appropriate multiplicative
// factor for use in Rabin-Karp algorithm. // factor for use in Rabin-Karp algorithm.
//
// This function was removed in Go 1.22.
func HashStrBytes(sep []byte) (uint32, uint32) { func HashStrBytes(sep []byte) (uint32, uint32) {
hash := uint32(0) hash := uint32(0)
for i := 0; i < len(sep); i++ { for i := 0; i < len(sep); i++ {
@@ -160,9 +153,7 @@ func HashStrBytes(sep []byte) (uint32, uint32) {
// HashStr returns the hash and the appropriate multiplicative // HashStr returns the hash and the appropriate multiplicative
// factor for use in Rabin-Karp algorithm. // factor for use in Rabin-Karp algorithm.
// func HashStr(sep string) (uint32, uint32) {
// This function was removed in Go 1.22.
func HashStr[T string | []byte](sep T) (uint32, uint32) {
hash := uint32(0) hash := uint32(0)
for i := 0; i < len(sep); i++ { for i := 0; i < len(sep); i++ {
hash = hash*PrimeRK + uint32(sep[i]) hash = hash*PrimeRK + uint32(sep[i])
@@ -179,8 +170,6 @@ func HashStr[T string | []byte](sep T) (uint32, uint32) {
// HashStrRevBytes returns the hash of the reverse of sep and the // HashStrRevBytes returns the hash of the reverse of sep and the
// appropriate multiplicative factor for use in Rabin-Karp algorithm. // appropriate multiplicative factor for use in Rabin-Karp algorithm.
//
// This function was removed in Go 1.22.
func HashStrRevBytes(sep []byte) (uint32, uint32) { func HashStrRevBytes(sep []byte) (uint32, uint32) {
hash := uint32(0) hash := uint32(0)
for i := len(sep) - 1; i >= 0; i-- { for i := len(sep) - 1; i >= 0; i-- {
@@ -198,9 +187,7 @@ func HashStrRevBytes(sep []byte) (uint32, uint32) {
// HashStrRev returns the hash of the reverse of sep and the // HashStrRev returns the hash of the reverse of sep and the
// appropriate multiplicative factor for use in Rabin-Karp algorithm. // appropriate multiplicative factor for use in Rabin-Karp algorithm.
// func HashStrRev(sep string) (uint32, uint32) {
// Copied from the Go 1.22rc1 source tree.
func HashStrRev[T string | []byte](sep T) (uint32, uint32) {
hash := uint32(0) hash := uint32(0)
for i := len(sep) - 1; i >= 0; i-- { for i := len(sep) - 1; i >= 0; i-- {
hash = hash*PrimeRK + uint32(sep[i]) hash = hash*PrimeRK + uint32(sep[i])
@@ -216,9 +203,7 @@ func HashStrRev[T string | []byte](sep T) (uint32, uint32) {
} }
// IndexRabinKarpBytes uses the Rabin-Karp search algorithm to return the index of the // IndexRabinKarpBytes uses the Rabin-Karp search algorithm to return the index of the
// first occurrence of substr in s, or -1 if not present. // first occurence of substr in s, or -1 if not present.
//
// This function was removed in Go 1.22.
func IndexRabinKarpBytes(s, sep []byte) int { func IndexRabinKarpBytes(s, sep []byte) int {
// Rabin-Karp search // Rabin-Karp search
hashsep, pow := HashStrBytes(sep) hashsep, pow := HashStrBytes(sep)
@@ -243,18 +228,16 @@ func IndexRabinKarpBytes(s, sep []byte) int {
} }
// IndexRabinKarp uses the Rabin-Karp search algorithm to return the index of the // IndexRabinKarp uses the Rabin-Karp search algorithm to return the index of the
// first occurrence of sep in s, or -1 if not present. // first occurence of substr in s, or -1 if not present.
// func IndexRabinKarp(s, substr string) int {
// Copied from the Go 1.22rc1 source tree.
func IndexRabinKarp[T string | []byte](s, sep T) int {
// Rabin-Karp search // Rabin-Karp search
hashss, pow := HashStr(sep) hashss, pow := HashStr(substr)
n := len(sep) n := len(substr)
var h uint32 var h uint32
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
h = h*PrimeRK + uint32(s[i]) h = h*PrimeRK + uint32(s[i])
} }
if h == hashss && string(s[:n]) == string(sep) { if h == hashss && s[:n] == substr {
return 0 return 0
} }
for i := n; i < len(s); { for i := n; i < len(s); {
@@ -262,7 +245,7 @@ func IndexRabinKarp[T string | []byte](s, sep T) int {
h += uint32(s[i]) h += uint32(s[i])
h -= pow * uint32(s[i-n]) h -= pow * uint32(s[i-n])
i++ i++
if h == hashss && string(s[i-n:i]) == string(sep) { if h == hashss && s[i-n:i] == substr {
return i - n return i - n
} }
} }
@@ -278,50 +261,3 @@ func MakeNoZero(n int) []byte {
// malloc function implemented in the runtime). // malloc function implemented in the runtime).
return make([]byte, n) return make([]byte, n)
} }
// Copied from the Go 1.22rc1 source tree.
func LastIndexByte(s []byte, c byte) int {
for i := len(s) - 1; i >= 0; i-- {
if s[i] == c {
return i
}
}
return -1
}
// Copied from the Go 1.22rc1 source tree.
func LastIndexByteString(s string, c byte) int {
for i := len(s) - 1; i >= 0; i-- {
if s[i] == c {
return i
}
}
return -1
}
// LastIndexRabinKarp uses the Rabin-Karp search algorithm to return the last index of the
// occurrence of sep in s, or -1 if not present.
//
// Copied from the Go 1.22rc1 source tree.
func LastIndexRabinKarp[T string | []byte](s, sep T) int {
// Rabin-Karp search from the end of the string
hashss, pow := HashStrRev(sep)
n := len(sep)
last := len(s) - n
var h uint32
for i := len(s) - 1; i >= last; i-- {
h = h*PrimeRK + uint32(s[i])
}
if h == hashss && string(s[last:]) == string(sep) {
return last
}
for i := last - 1; i >= 0; i-- {
h *= PrimeRK
h += uint32(s[i])
h -= pow * uint32(s[i+n])
if h == hashss && string(s[i:i+n]) == string(sep) {
return i
}
}
return -1
}
+1 -1
View File
@@ -44,7 +44,7 @@ func Current() *Task {
// This function may only be called when running on a goroutine stack, not when running on the system stack or in an interrupt. // This function may only be called when running on a goroutine stack, not when running on the system stack or in an interrupt.
func Pause() { func Pause() {
// Check whether the canary (the lowest address of the stack) is still // Check whether the canary (the lowest address of the stack) is still
// valid. If it is not, a stack overflow has occurred. // valid. If it is not, a stack overflow has occured.
if *currentTask.state.canaryPtr != stackCanary { if *currentTask.state.canaryPtr != stackCanary {
runtimePanic("goroutine stack overflow") runtimePanic("goroutine stack overflow")
} }
-2
View File
@@ -1,5 +1,3 @@
//go:build tinygo
// Only generate .debug_frame, don't generate .eh_frame. // Only generate .debug_frame, don't generate .eh_frame.
.cfi_sections .debug_frame .cfi_sections .debug_frame
+1 -3
View File
@@ -1,5 +1,3 @@
//go:build tinygo
.section .bss.tinygo_systemStack .section .bss.tinygo_systemStack
.global tinygo_systemStack .global tinygo_systemStack
.type tinygo_systemStack, %object .type tinygo_systemStack, %object
@@ -28,7 +26,7 @@ tinygo_startTask:
// After return, exit this goroutine. This is a tail call. // After return, exit this goroutine. This is a tail call.
#if __AVR_ARCH__ == 2 || __AVR_ARCH__ == 25 #if __AVR_ARCH__ == 2 || __AVR_ARCH__ == 25
// Small memory devices (8kB flash) that do not have the long call // Small memory devices (8kB flash) that do not have the long call
// instruction available will need to use rcall instead. // instruction availble will need to use rcall instead.
// Note that they will probably not be able to run more than the main // Note that they will probably not be able to run more than the main
// goroutine anyway, but this file is compiled for all AVRs so it needs to // goroutine anyway, but this file is compiled for all AVRs so it needs to
// compile at least. // compile at least.
-2
View File
@@ -1,5 +1,3 @@
//go:build tinygo
// Only generate .debug_frame, don't generate .eh_frame. // Only generate .debug_frame, don't generate .eh_frame.
.cfi_sections .debug_frame .cfi_sections .debug_frame
+4 -4
View File
@@ -52,17 +52,17 @@ func (s *state) archInit(r *calleeSavedRegs, fn uintptr, args unsafe.Pointer) {
} }
func (s *state) resume() { func (s *state) resume() {
tinygo_switchToTask(s.sp) switchToTask(s.sp)
} }
//export tinygo_switchToTask //export tinygo_switchToTask
func tinygo_switchToTask(uintptr) func switchToTask(uintptr)
//export tinygo_switchToScheduler //export tinygo_switchToScheduler
func tinygo_switchToScheduler(*uintptr) func switchToScheduler(*uintptr)
func (s *state) pause() { func (s *state) pause() {
tinygo_switchToScheduler(&s.sp) switchToScheduler(&s.sp)
} }
// SystemStack returns the system stack pointer. On Cortex-M, it is always // SystemStack returns the system stack pointer. On Cortex-M, it is always
+1 -3
View File
@@ -1,5 +1,3 @@
//go:build tinygo
.section .text.tinygo_startTask,"ax",@progbits .section .text.tinygo_startTask,"ax",@progbits
.global tinygo_startTask .global tinygo_startTask
.type tinygo_startTask, %function .type tinygo_startTask, %function
@@ -78,7 +76,7 @@ tinygo_swapTask:
// Switch to the new stack pointer (newStack). // Switch to the new stack pointer (newStack).
mov.n sp, a2 mov.n sp, a2
// Load a0, which is the previous return address from before the previous // Load a0, which is the previous return addres from before the previous
// switch or the constructed return address to tinygo_startTask. This // switch or the constructed return address to tinygo_startTask. This
// register also stores the parent register window. // register also stores the parent register window.
l32i.n a0, sp, 0 l32i.n a0, sp, 0
-2
View File
@@ -1,5 +1,3 @@
//go:build tinygo
.section .text.tinygo_startTask,"ax",@progbits .section .text.tinygo_startTask,"ax",@progbits
.global tinygo_startTask .global tinygo_startTask
.type tinygo_startTask, %function .type tinygo_startTask, %function
@@ -1,5 +1,3 @@
//go:build tinygo
.section .text.tinygo_startTask .section .text.tinygo_startTask
.global tinygo_startTask .global tinygo_startTask
.type tinygo_startTask, %function .type tinygo_startTask, %function
@@ -1,125 +0,0 @@
//go:build adafruit_esp32_feather_v2
package machine
const GPIO20 Pin = 20
const (
IO0 = GPIO0
IO2 = GPIO2
IO4 = GPIO4
IO5 = GPIO5
IO7 = GPIO7
IO8 = GPIO8
IO12 = GPIO12
IO13 = GPIO13
IO14 = GPIO14
IO15 = GPIO15
IO19 = GPIO19
IO20 = GPIO20
IO21 = GPIO21
IO22 = GPIO22
IO25 = GPIO25
IO26 = GPIO26
IO27 = GPIO27
IO32 = GPIO32
IO33 = GPIO33
IO34 = GPIO34
IO35 = GPIO35
IO36 = GPIO36
IO37 = GPIO37
IO38 = GPIO38
IO39 = GPIO39
)
// Digital pins
const (
D12 = IO12
D13 = IO13
D14 = IO14
D15 = IO15
D27 = IO27
D32 = IO32
D33 = IO33
D37 = IO37
)
// Analog pins
const (
A0 = IO26
A1 = IO25
A2 = IO34
A3 = IO39
A4 = IO36
A5 = IO4
)
// Built-in LEDs and Button
const (
WS2812 = IO0
NEOPIXEL = WS2812
NEOPIXEL_I2C_POWER = IO2
LED = IO13
BUTTON = IO38
)
// SPI pins
const (
SPI_SCK_PIN = IO5
SPI_MOSI_PIN = IO19
SPI_MISO_PIN = IO21
SPI_SDO_PIN = SPI_MOSI_PIN
SPI_SDI_PIN = SPI_MISO_PIN
// Silk labels
SCK = SPI_SCK_PIN
MO = SPI_MOSI_PIN
MI = SPI_MISO_PIN
)
// I2C pins
const (
I2C_SCL_PIN = IO20
I2C_SDA_PIN = IO22
// Silk labels
SCL = I2C_SCL_PIN
SDA = I2C_SDA_PIN
)
// ADC pins
const (
ADC1_0 = IO36
ADC1_1 = IO37
ADC1_2 = IO38
ADC1_3 = IO39
ADC1_4 = IO32
ADC1_5 = IO33
ADC1_6 = IO34
ADC1_7 = IO35
ADC2_0 = IO4
ADC2_1 = IO0
ADC2_2 = IO2
ADC2_3 = IO15
ADC2_4 = IO13
ADC2_5 = IO12
ADC2_6 = IO14
ADC2_7 = IO27
ADC2_8 = IO25
ADC2_9 = IO26
)
// UART pins
const (
UART_TX_PIN = IO19
UART_RX_PIN = IO22
UART2_TX_PIN = IO8
UART2_RX_PIN = IO7
// Silk labels
RX = UART2_RX_PIN
TX = UART2_TX_PIN
)
+25
View File
@@ -2,6 +2,11 @@
package machine package machine
import (
"device/rp"
"runtime/interrupt"
)
// GPIO pins // GPIO pins
const ( const (
GP0 Pin = GPIO0 GP0 Pin = GPIO0
@@ -72,8 +77,28 @@ const (
UART_RX_PIN = UART0_RX_PIN UART_RX_PIN = UART0_RX_PIN
) )
// UART on the RP2040
var (
UART0 = &_UART0
_UART0 = UART{
Buffer: NewRingBuffer(),
Bus: rp.UART0,
}
UART1 = &_UART1
_UART1 = UART{
Buffer: NewRingBuffer(),
Bus: rp.UART1,
}
)
var DefaultUART = UART0 var DefaultUART = UART0
func init() {
UART0.Interrupt = interrupt.New(rp.IRQ_UART0_IRQ, _UART0.handleInterrupt)
UART1.Interrupt = interrupt.New(rp.IRQ_UART1_IRQ, _UART1.handleInterrupt)
}
// USB identifiers // USB identifiers
const ( const (
usb_STRING_PRODUCT = "AE-RP2040" usb_STRING_PRODUCT = "AE-RP2040"
+5
View File
@@ -2,6 +2,11 @@
package machine package machine
// Return the current CPU frequency in hertz.
func CPUFrequency() uint32 {
return 16000000
}
// Digital pins, marked as plain numbers on the board. // Digital pins, marked as plain numbers on the board.
const ( const (
D0 = PD0 // RX D0 = PD0 // RX
+5
View File
@@ -2,6 +2,11 @@
package machine package machine
// Return the current CPU frequency in hertz.
func CPUFrequency() uint32 {
return 16000000
}
// Digital pins. // Digital pins.
const ( const (
D0 = PD0 // RX0 D0 = PD0 // RX0
+2 -14
View File
@@ -63,9 +63,6 @@ var UART1 = &sercomUSART3
// UART2 on the Arduino Nano 33 connects to the normal TX/RX pins. // UART2 on the Arduino Nano 33 connects to the normal TX/RX pins.
var UART2 = &sercomUSART5 var UART2 = &sercomUSART5
// UART_NINA on the Arduino Nano 33 connects to the NINA HCI.
var UART_NINA = &sercomUSART2
// I2C pins // I2C pins
const ( const (
SDA_PIN Pin = A4 // SDA: SERCOM4/PAD[1] SDA_PIN Pin = A4 // SDA: SERCOM4/PAD[1]
@@ -102,17 +99,8 @@ const (
NINA_GPIO0 Pin = PA27 NINA_GPIO0 Pin = PA27
NINA_RESETN Pin = PA08 NINA_RESETN Pin = PA08
NINA_ACK Pin = PA28 NINA_ACK Pin = PA28
NINA_TX Pin = PA12 NINA_TX Pin = PA22
NINA_RX Pin = PA13 NINA_RX Pin = PA23
NINA_RTS Pin = PA14
NINA_CTS Pin = PA15
)
// NINA-W102 settings
const (
NINA_BAUDRATE = 912600
NINA_RESET_INVERTED = true
NINA_SOFT_FLOWCONTROL = false
) )
// I2S pins // I2S pins
-5
View File
@@ -2,11 +2,6 @@
package machine package machine
// Return the current CPU frequency in hertz.
func CPUFrequency() uint32 {
return 16000000
}
const ( const (
// Note: start at port B because there is no port A. // Note: start at port B because there is no port A.
portB Pin = iota * 8 portB Pin = iota * 8
-51
View File
@@ -1,51 +0,0 @@
//go:build avr && atmega328pb
package machine
// Return the current CPU frequency in hertz.
func CPUFrequency() uint32 {
return 16000000
}
const (
// Note: start at port B because there is no port A.
portB Pin = iota * 8
portC
portD
portE
)
const (
PB0 = portB + 0
PB1 = portB + 1 // peripherals: Timer1 channel A
PB2 = portB + 2 // peripherals: Timer1 channel B
PB3 = portB + 3 // peripherals: Timer2 channel A
PB4 = portB + 4
PB5 = portB + 5
PB6 = portB + 6
PB7 = portB + 7
PC0 = portC + 0
PC1 = portC + 1
PC2 = portC + 2
PC3 = portC + 3
PC4 = portC + 4
PC5 = portC + 5
PC6 = portC + 6
PC7 = portC + 7
PD0 = portD + 0
PD1 = portD + 1
PD2 = portD + 2
PD3 = portD + 3 // peripherals: Timer2 channel B
PD4 = portD + 4
PD5 = portD + 5 // peripherals: Timer0 channel B
PD6 = portD + 6 // peripherals: Timer0 channel A
PD7 = portD + 7
PE0 = portE + 0
PE1 = portE + 1
PE2 = portE + 2
PE3 = portE + 3
PE4 = portE + 4
PE5 = portE + 5
PE6 = portE + 6
PE7 = portE + 7
)
-95
View File
@@ -1,95 +0,0 @@
//go:build badger2040_w
// This contains the pin mappings for the Badger 2040 W board.
//
// For more information, see: https://shop.pimoroni.com/products/badger-2040-w
// Also
// - Badger 2040 W schematic: https://cdn.shopify.com/s/files/1/0174/1800/files/badger_w_schematic.pdf?v=1675859004
package machine
const (
LED Pin = GPIO22
BUTTON_A Pin = GPIO12
BUTTON_B Pin = GPIO13
BUTTON_C Pin = GPIO14
BUTTON_UP Pin = GPIO15
BUTTON_DOWN Pin = GPIO11
BUTTON_USER Pin = NoPin // Not available on Badger 2040 W
EPD_BUSY_PIN Pin = GPIO26
EPD_RESET_PIN Pin = GPIO21
EPD_DC_PIN Pin = GPIO20
EPD_CS_PIN Pin = GPIO17
EPD_SCK_PIN Pin = GPIO18
EPD_SDO_PIN Pin = GPIO19
VBUS_DETECT Pin = GPIO24
VREF_POWER Pin = GPIO27
VREF_1V24 Pin = GPIO28
VBAT_SENSE Pin = GPIO29
ENABLE_3V3 Pin = GPIO10
BATTERY = VBAT_SENSE
RTC_ALARM = GPIO8
)
// I2C pins
const (
I2C0_SDA_PIN Pin = GPIO4
I2C0_SCL_PIN Pin = GPIO5
I2C1_SDA_PIN Pin = NoPin
I2C1_SCL_PIN Pin = NoPin
)
// SPI pins.
const (
SPI0_SCK_PIN Pin = GPIO18
SPI0_SDO_PIN Pin = GPIO19
SPI0_SDI_PIN Pin = GPIO16
SPI1_SCK_PIN Pin = NoPin
SPI1_SDO_PIN Pin = NoPin
SPI1_SDI_PIN Pin = NoPin
)
// QSPI pins¿?
const (
/*
TODO
SPI0_SD0_PIN Pin = QSPI_SD0
SPI0_SD1_PIN Pin = QSPI_SD1
SPI0_SD2_PIN Pin = QSPI_SD2
SPI0_SD3_PIN Pin = QSPI_SD3
SPI0_SCK_PIN Pin = QSPI_SCLKGPIO6
SPI0_CS_PIN Pin = QSPI_CS
*/
)
// Onboard crystal oscillator frequency, in MHz.
const (
xoscFreq = 12 // MHz
)
// USB CDC identifiers
const (
usb_STRING_PRODUCT = "Badger 2040 W"
usb_STRING_MANUFACTURER = "Pimoroni"
)
var (
usb_VID uint16 = 0x2e8a
usb_PID uint16 = 0x0003
)
// UART pins
const (
UART0_TX_PIN = GPIO0
UART0_RX_PIN = GPIO1
UART_TX_PIN = UART0_TX_PIN
UART_RX_PIN = UART0_RX_PIN
)
var DefaultUART = UART0
+20 -6
View File
@@ -1,12 +1,17 @@
//go:build badger2040 //go:build badger2040
// This contains the pin mappings for the Badger 2040 board. // This contains the pin mappings for the Badger 2040 Connect board.
// //
// For more information, see: https://shop.pimoroni.com/products/badger-2040 // For more information, see: https://shop.pimoroni.com/products/badger-2040
// Also // Also
// - Badger 2040 schematic: https://cdn.shopify.com/s/files/1/0174/1800/files/badger_2040_schematic.pdf?v=1645702148 // - Badger 2040 schematic: https://cdn.shopify.com/s/files/1/0174/1800/files/badger_2040_schematic.pdf?v=1645702148
package machine package machine
import (
"device/rp"
"runtime/interrupt"
)
const ( const (
LED Pin = GPIO25 LED Pin = GPIO25
@@ -25,12 +30,8 @@ const (
EPD_SDO_PIN Pin = GPIO19 EPD_SDO_PIN Pin = GPIO19
VBUS_DETECT Pin = GPIO24 VBUS_DETECT Pin = GPIO24
VREF_POWER Pin = GPIO27 BATTERY Pin = GPIO29
VREF_1V24 Pin = GPIO28
VBAT_SENSE Pin = GPIO29
ENABLE_3V3 Pin = GPIO10 ENABLE_3V3 Pin = GPIO10
BATTERY = VBAT_SENSE
) )
// I2C pins // I2C pins
@@ -91,4 +92,17 @@ const (
UART_RX_PIN = UART0_RX_PIN UART_RX_PIN = UART0_RX_PIN
) )
// UART on the RP2040
var (
UART0 = &_UART0
_UART0 = UART{
Buffer: NewRingBuffer(),
Bus: rp.UART0,
}
)
var DefaultUART = UART0 var DefaultUART = UART0
func init() {
UART0.Interrupt = interrupt.New(rp.IRQ_UART0_IRQ, _UART0.handleInterrupt)
}
+25
View File
@@ -2,6 +2,11 @@
package machine package machine
import (
"device/rp"
"runtime/interrupt"
)
const ( const (
LED = GPIO24 LED = GPIO24
@@ -79,8 +84,28 @@ const (
UART_RX_PIN = UART0_RX_PIN UART_RX_PIN = UART0_RX_PIN
) )
// UART on the RP2040
var (
UART0 = &_UART0
_UART0 = UART{
Buffer: NewRingBuffer(),
Bus: rp.UART0,
}
UART1 = &_UART1
_UART1 = UART{
Buffer: NewRingBuffer(),
Bus: rp.UART1,
}
)
var DefaultUART = UART0 var DefaultUART = UART0
func init() {
UART0.Interrupt = interrupt.New(rp.IRQ_UART0_IRQ, _UART0.handleInterrupt)
UART1.Interrupt = interrupt.New(rp.IRQ_UART1_IRQ, _UART1.handleInterrupt)
}
// USB identifiers // USB identifiers
const ( const (
usb_STRING_PRODUCT = "Challenger 2040 LoRa" usb_STRING_PRODUCT = "Challenger 2040 LoRa"

Some files were not shown because too many files have changed in this diff Show More