インストール
https://docs.microsoft.com/ja-jp/dotnet/core/install/linux-package-manager-centos7
には、 centos8 は書いてないが、
https://packages.microsoft.com/config/centos/8/packages-microsoft-prod.rpm
を使えば、同じ手順でできる。
2020/8 追記。
https://docs.microsoft.com/ja-jp/dotnet/core/install/linux-centos
前記ページがなくなって、Centos8 は、標準のリポジトリ AppStream から落とせる、になった。
まずは、コンソールアプリケーション
https://docs.microsoft.com/ja-jp/dotnet/core/tutorials/with-visual-studio-code
に従う。
[kanda@localhost console]$ dotnet new console
The template "Console Application" was created successfully.
Processing post-creation actions...
Running 'dotnet restore' on /home/kanda/csharp/console/console.csproj...
[kanda@localhost console]$ dotnet build
.NET Core 向け Microsoft (R) Build Engine バージョン 16.4.0+e901037fe
Copyright (C) Microsoft Corporation.All rights reserved.
console -> /home/kanda/csharp/console/bin/Debug/netcoreapp3.1/console.dll
ビルドに成功しました。
なんだこれは。
[kanda@localhost netcoreapp3.1]$ ldd console
linux-vdso.so.1 (0x00007fff0b793000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007fd0e9b14000)
libdl.so.2 => /lib64/libdl.so.2 (0x00007fd0e9910000)
libstdc++.so.6 => /lib64/libstdc++.so.6 (0x00007fd0e957b000)
libm.so.6 => /lib64/libm.so.6 (0x00007fd0e91f9000)
libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007fd0e8fe1000)
libc.so.6 => /lib64/libc.so.6 (0x00007fd0e8c1e000)
/lib64/ld-linux-x86-64.so.2 (0x00007fd0e9d34000)
[kanda@localhost netcoreapp3.1]$ ldd console.dll
ldd: 警告: 実行パーミッションがありません: `./console.dll'
動的実行ファイルではありません
これは、 elf 実行形式ファイルだ。
[kanda@localhost netcoreapp3.1]$ file console
console: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=5b7bc4e1ec868672a1cf889bc66d7c604dbb1177, stripped
これが、 .net アセンブリというやつか。
[kanda@localhost netcoreapp3.1]$ file console.dll
console.dll: PE32 executable (console) Intel 80386 Mono/.Net assembly, for MS Windows
[kanda@localhost netcoreapp3.1]$ ./console
Hello World!
[kanda@localhost console]$ dotnet run
Hello World!
[kanda@localhost console]$ cat obj/project.assets.json
{
"version": 3,
"targets": {
".NETCoreApp,Version=v3.1": {}
},
"libraries": {},
"projectFileDependencyGroups": {
".NETCoreApp,Version=v3.1": []
},
"packageFolders": {
"/home/kanda/.nuget/packages/": {}
},
"project": {
"version": "1.0.0",
..
nuget restore で、ここに、大量のバイナリを落としてくる。
[kanda@localhost packages]$ pwd
/home/kanda/.nuget/packages
これが、 .NET クラスの実体か。
[kanda@localhost packages]$ ls -lR microsoft.netcore.app.runtime.linux-x64/
microsoft.netcore.app.runtime.linux-x64/:
..
microsoft.netcore.app.runtime.linux-x64/3.1.2/runtimes/linux-x64/lib/netcoreapp3.1:
合計 41596
-rwxrw-r--. 1 kanda kanda 810360 1月 17 20:57 Microsoft.CSharp.dll
-rwxrw-r--. 1 kanda kanda 20352 1月 17 20:57 Microsoft.Win32.Primitives.dll
-rwxrw-r--. 1 kanda kanda 188800 1月 17 20:57 System.Console.dll
。。
https://www.nuget.org/packages/dotnet-ildasm/
[kanda@localhost ~]$ dotnet tool install --global dotnet-ildasm --version 0.12.2
次のコマンドを使用してツールを呼び出せます。dotnet-ildasm
ツール 'dotnet-ildasm' (バージョン '0.12.2') が正常にインストールされました。
[kanda@localhost netcoreapp3.1]$ dotnet-ildasm console.dll
.assembly extern System.Runtime
{
.publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) // .._.....
.ver 4:2:0:2
}
長いので編集してあります。
.assembly 'console'
{
.custom instance void class [System.Runtime]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) // ........
}
.module 'console.dll'
.subsystem 0x0003 // WindowsCui
.corflags 0x00000001 // ILOnly
.class private auto ansi beforefieldinit Program extends [System.Runtime]System.Object
{
.method private hidebysig static default void Main(string[] args) cil managed
{
// Method begins at Relative Virtual Address (RVA) 0x2050
.entrypoint
// Code size 13 (0xD)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "Hello World!"
IL_0006: call void class [System.Console]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ret
} // End of method System.Void Program::Main(System.String[])
System.Console.dll を見る。
[kanda@localhost netcoreapp3.1]$ pwd
/home/kanda/.nuget/packages/microsoft.netcore.app.runtime.linux-x64/3.1.2/runtimes/linux-x64/lib/netcoreapp3.1
[kanda@localhost netcoreapp3.1]$ dotnet-ildasm System.Console.dll
なあんだ。
.method public hidebysig static default void WriteLine() cil managed
{
.maxstack 8
IL_0000: call [System.Runtime.Extensions]System.IO.TextWriter class System.Console::get_Out()
IL_0005: callvirt instance void class [System.Runtime.Extensions]System.IO.TextWriter::WriteLine()
IL_000a: ret
} // End of method System.Void System.Console::WriteLine()
[kanda@localhost classlib]$ dotnet new classlib
ライブラリは、 dll になる。
[kanda@localhost classlib]$ dotnet build
classlib -> /home/kanda/csharp/classlib/bin/Debug/netstandard2.0/classlib.dll
それを参照するように、コンソールアプリケーションをなおしてビルドするが、引けない。
[kanda@localhost console]$ dotnet build
Program.cs(11,26): error CS0246: 型または名前空間の名前 'YourClass' が見つかりませんでした (using ディレクティブまたはアセンブリ参照が指定されていることを確認してください)。 [/home/kanda/csharp/console/console.csproj]
アセンブリ参照は、dotnet add reference で行う。
[kanda@localhost console]$ dotnet add reference ../classlib/classlib.csproj
参照 `..\classlib\classlib.csproj` がプロジェクトに追加されました。
プロジェクトファイルに入る。
[kanda@localhost console]$ cat console.csproj
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\classlib\classlib.csproj" />
</ItemGroup>
今度は、ビルドできた。
[kanda@localhost console]$ dotnet build
classlib -> /home/kanda/csharp/classlib/bin/Debug/netstandard2.0/classlib.dll
console -> /home/kanda/csharp/console/bin/Debug/netcoreapp3.1/console.dll
ビルドに成功しました。
パブリッシュすると、依存 dll も、そのディレクトリに複写されて、含まれる。
[kanda@localhost console]$ dotnet publish
[kanda@localhost publish]$ ls
classlib.dll classlib.pdb console console.deps.json console.dll console.pdb console.runtimeconfig.json
[kanda@localhost wpf]$ dotnet new wpf
The template "WPF Application" was created successfully.
Running 'dotnet restore' on /home/kanda/csharp/wpf/wpf.csproj...
/home/kanda/.dotnet/sdk/5.0.100-preview.1.20155.7/Sdks/Microsoft.NET.Sdk/targets/Microsoft.NET.Sdk.FrameworkReferenceResolution.targets(59,5): error NETSDK1100: Windows デスクトップ アプリケーションを構築するには Windows が必要です。
あ、やっぱり。
[kanda@localhost winforms]$ dotnet new winforms
The template "Windows Forms (WinForms) Application" was created successfully.
これもだめだ。
PowerShell バイナリ モジュールを記述する方法
に、従う。
[kanda@localhost pwsh]$ dotnet new psmodule
Couldn't find an installed template that matches the input, searching online for one that does...
Matches from template source: NuGet
-----------------------------------
Template name "PowerShell Standard Module" (psmodule) from author "Microsoft Corporation" in pack Microsoft.PowerShell.Standard.Module.Template
To use this template, run the following command and try again:
dotnet new -i "Microsoft.PowerShell.Standard.Module.Template::0.1.3"
テンプレートを、インストールせよ、とのこと。
[kanda@localhost pwsh]$ dotnet new -i "Microsoft.PowerShell.Standard.Module.Template::0.1.3"
できた。
[kanda@localhost pwsh]$ dotnet new psmodule
The template "PowerShell Standard Module" was created successfully.
[kanda@localhost pwsh]$ ls
TestSampleCmdletCommand.cs obj pwsh.csproj
[kanda@localhost pwsh]$ dotnet build
pwsh -> /home/kanda/csharp/pwsh/bin/Debug/netstandard2.0/pwsh.dll
powershell から呼んでみよう。
PS /home/kanda/csharp/pwsh/bin/Debug/netstandard2.0> import-module ./pwsh.dll
PS /home/kanda/csharp/pwsh/bin/Debug/netstandard2.0> get-module
ModuleType Version PreRelease Name ExportedCo
mmands
---------- ------- ---------- ---- ----------
Manifest 7.0.0.0 Microsoft.PowerShell.Management {Add-Cont…
Binary 7.0.0.0 pwsh
PS /home/kanda/csharp/pwsh/bin/Debug/netstandard2.0> Test-SampleCmdlet 7 "Cat"
Test-SampleCmdlet: The term 'Test-SampleCmdlet' is not recognized as the name of a cmdlet, function, script file, or operable program.
だめだ。
マニフェストを書かないといけないのだろうか。
PS /home/kanda/csharp/pwsh/bin/Debug/netstandard2.0> New-ModuleManifest -path pwsh.psd1
デバッグオプションというのは、たいして何も出ないな。
PS /home/kanda/csharp/pwsh/bin/Debug/netstandard2.0/publish> Import-Module -verbose -debug ./pwsh.psd1
VERBOSE: Loading module from path '/home/kanda/csharp/pwsh/bin/Debug/netstandard2.0/publish/pwsh.psd1'.
VERBOSE: Loading module from path '/home/kanda/csharp/pwsh/bin/Debug/netstandard2.0/publish/pwsh.dll'.
PS /home/kanda/csharp/pwsh/bin/Debug/netstandard2.0/publish> get-module -name pwsh | select *
マニフェストに書いたことは反映されているが、ExportedCmdlets が、 * を指定しても、Test-SampleCmdlet を明示的に指定しても、あらわれない。
dll を直に import-module してもだめ。
C:\Users\kanda_000> dotnet new -i "Microsoft.PowerShell.Standard.Module.Template::0.1.3"
C:\Users\kanda_000\MyCmdlet>dotnet new psmodule
C:\Users\kanda_000\MyCmdlet>dotnet publish
MyCmdlet -> C:\Users\kanda_000\MyCmdlet\bin\Debug\netstandard2.0\MyCmdlet.dll
PS C:\Users\kanda_000\MyCmdlet\bin\Debug\netstandard2.0\publish> import-module .\MyCmdlet.dll
PS C:\Users\kanda_000\MyCmdlet\bin\Debug\netstandard2.0\publish> get-module
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Binary 1.0.0.0 MyCmdlet Test-SampleCmdlet
PS C:\Users\kanda_000\MyCmdlet\bin\Debug\netstandard2.0\publish> $psversiontable
Name Value
---- -----
PSVersion 5.1.18362.628
PS C:\Users\kanda_000\MyCmdlet\bin\Debug\netstandard2.0\publish> Test-SampleCmdlet 7 Cat
FavoriteNumber FavoritePet
-------------- -----------
7 Cat
powershell v7 でも動く。
C:\Users\kanda_000\MyCmdlet\bin\Debug\netstandard2.0>pwsh
PowerShell 7.0.0
PS C:\Users\kanda_000\MyCmdlet\bin\Debug\netstandard2.0> Import-Module .\MyCmdlet.dll
PS C:\Users\kanda_000\MyCmdlet\bin\Debug\netstandard2.0> Test-SampleCmdlet 5 Dog
FavoriteNumber FavoritePet
-------------- -----------
5 Dog
最小限の Cmdlet
C:\Users\kanda_000\MyCmdlet>type a.cs
using System;
using System.Management.Automation;
[Cmdlet("Get","Hoe")]
public class c : PSCmdlet
{
protected override void ProcessRecord()
{
WriteVerbose("ProcessRecord:");
Console.WriteLine("Hello ");
WriteObject("Hoe");
}
}
PS C:\Users\kanda_000\MyCmdlet\bin\Debug\netstandard2.0> $out = Get-Hoe
Hello
PS C:\Users\kanda_000\MyCmdlet\bin\Debug\netstandard2.0> $out
Hoe
C# ソースコードのファイル名、名前空間、クラス名、何も、 powershell には関係ない。属性 [Cmdlet(動詞, 名詞)] で決まる。
この環境変数が、モジュールの検索パス。
PS C:\Users\kanda_000> $env:PSModulePath
C:\Users\kanda_000\Documents\PowerShell\Modules;C:\Program Files\PowerShell\Modules;c:\program files\powershell\7\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\;C:\Program Files\WindowsPowerShell\Modules\
ディレクトリ名が、モジュール名でないといけない。
C:\Users\kanda_000\Documents>mkdir PowerShell\Modules\MyCmdlet
C:\Users\kanda_000\Documents\PowerShell\Modules\MyCmdlet>dir
2020/04/10 11:02 4,096 MyCmdlet.dll
あれ?置いただけでは、コマンドレット検索の対象に入らないのだろうか。
PS C:\Users\kanda_000> get-hoe
get-hoe: The term 'get-hoe' is not recognized as the name of a cmdlet
インポートは、dll の絶対パスを与えなくても成功する。
PS C:\Users\kanda_000> import-module MyCmdlet
PS C:\Users\kanda_000> get-hoe
Hello
Hoe
動いた。
WriteVerbose の結果って、どこに出るのだ。
PS /home/kanda/csharp/MyCmdlet/bin/Debug/netstandard2.0> Import-Module ./MyCmdlet.dll
PS /home/kanda/csharp/MyCmdlet/bin/Debug/netstandard2.0> get-module
ModuleType Version PreRelease Name ExportedCommands
---------- ------- ---------- ---- ----------
Binary 1.0.0.0 MyCmdlet Get-Hoe
PS /home/kanda/csharp/MyCmdlet/bin/Debug/netstandard2.0> $out = Get-Hoe
Hello
PS /home/kanda/csharp/MyCmdlet/bin/Debug/netstandard2.0> $out
Hoe
[kanda@localhost YourCmdlet]$ dotnet new psmodule
[kanda@localhost YourCmdlet]$ dotnet add reference ../classlib/
[kanda@localhost YourCmdlet]$ cat YourCmdlet.cs
using System;
using System.Management.Automation;
[Cmdlet("Get","Hoe")]
public class a : PSCmdlet
{
protected override void ProcessRecord()
{
Console.WriteLine("Hello ");
WriteObject("Hoe");
}
}
[Cmdlet("Get","Fue")]
public class b : PSCmdlet
{
protected override void ProcessRecord()
{
var c = new console.YourClass();
WriteObject(c.Greeting());
}
}
[kanda@localhost YourCmdlet]$ cat YourCmdlet.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<AssemblyName>YourCmdlet</AssemblyName>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="PowerShellStandard.Library" Version="5.1.0-preview-06">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\classlib\classlib.csproj" />
</ItemGroup>
</Project>
[kanda@localhost YourCmdlet]$ dotnet publish
[kanda@localhost publish]$ ls
YourCmdlet.deps.json YourCmdlet.pdb classlib.pdb
YourCmdlet.dll classlib.dll
[kanda@localhost publish]$ pwsh
PS /home/kanda/csharp/YourCmdlet/bin/Debug/netstandard2.0/publish> import-module ./YourCmdlet.dll
依存アセンブリは、勝手にロードしてくれるらしい。
PS /home/kanda/csharp/YourCmdlet/bin/Debug/netstandard2.0/publish> get-module -name YourCmdlet | select *
Path : /home/kanda/csharp/YourCmdlet/bin/Debug/netstandard2.0/publish/YourCmdlet.dll
ExportedCmdlets : {[Get-Hoe, Get-Hoe], [Get-Fue, Get-Fue]}
PS /home/kanda/csharp/YourCmdlet/bin/Debug/netstandard2.0/publish> Get-Hoe
Hello
Hoe
PS /home/kanda/csharp/YourCmdlet/bin/Debug/netstandard2.0/publish> Get-Fue
Hi
依存アセンブリを消すと、
[kanda@localhost publish]$ mv classlib.dll /tmp
[kanda@localhost publish]$ pwsh
インポートはできるが、
PS /home/kanda/csharp/YourCmdlet/bin/Debug/netstandard2.0/publish> import-module ./YourCmdlet.dll
そのアセンブリを使うコマンドを打つと、失敗する。
PS /home/kanda/csharp/YourCmdlet/bin/Debug/netstandard2.0/publish> get-fue
Get-Fue: Could not load file or assembly 'classlib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
使わない部分は、動く。
PS /home/kanda/csharp/YourCmdlet/bin/Debug/netstandard2.0/publish> get-hoe
Hello
Hoe
マニフェストを書いて、モジュールパスに置く。
PS /home/kanda> $env:PSModulePath
/home/kanda/.local/share/powershell/Modules:/usr/local/share/powershell/Modules:/opt/microsoft/powershell/7/Modules
[kanda@localhost YourCmdlet]$ pwd
/home/kanda/.local/share/powershell/Modules/YourCmdlet
[kanda@localhost YourCmdlet]$ ls
YourCmdlet.dll YourCmdlet.psd1 classlib.dll
これがモジュールマニフェスト。同じディレクトリにある依存アセンブリは書く必要ないみたい。
[kanda@localhost YourCmdlet]$ cat YourCmdlet.psd1
@{
RootModule = 'YourCmdlet.dll'
ModuleVersion = '0.0.2'
GUID = '7ca06d5c-a182-4fdd-8f66-6657ed7af398'
CmdletsToExport = @("Get-Hoe", "Get-Fue")
}
[kanda@localhost ~]$ pwsh
PS /home/kanda> Get-Fue
Hi
インポートしないでも動いた。なるほど。
https://docs.microsoft.com/ja-jp/aspnet/core/tutorials/razor-pages/?view=aspnetcore-3.1
に従う。
[kanda@localhost webapp]$ dotnet new webapp -o RazorPagesMovie
The template "ASP.NET Core Web App" was created successfully.
code から、 Run したらブラウザが開いてびっくりした。 web サーバの設定とか、何もいらないのだ。
[kanda@localhost ~]$ lsof -P -i
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
dotnet 26508 kanda 261u IPv4 246903 0t0 TCP localhost:5001 (LISTEN)
dotnet 26508 kanda 262u IPv6 246906 0t0 TCP localhost:5001 (LISTEN)
[kanda@localhost ~]$ curl -v -k https://localhost:5001
> GET / HTTP/2
> Host: localhost:5001
< HTTP/2 200
< server: Kestrel
<
<!DOCTYPE html>
データベースは、 SQLite だそうな。ウェブサーバは、dotnet 組込みの Kestrel で、本番では nginx などをリバースプロキシにして使うらしい。
[kanda@localhost RazorPagesMovie]$ dotnet tool install --global dotnet-ef
次のコマンドを使用してツールを呼び出せます。dotnet-ef
ツール 'dotnet-ef' (バージョン '3.1.3') が正常にインストールされました。
[kanda@localhost RazorPagesMovie]$ dotnet tool install --global dotnet-aspnet-codegenerator
次のコマンドを使用してツールを呼び出せます。dotnet-aspnet-codegenerator
ツール 'dotnet-aspnet-codegenerator' (バージョン '3.1.2') が正常にインストールされました。
[kanda@localhost RazorPagesMovie]$ dotnet add package Microsoft.EntityFrameworkCore.SQLite
info : Adding PackageReference for package 'Microsoft.EntityFrameworkCore.SQLite' into project '/home/kanda/csharp/webapp/RazorPagesMovie/RazorPagesMovie.csproj'.
info : Restoring packages for /home/kanda/csharp/webapp/RazorPagesMovie/RazorPagesMovie.csproj...
info : GET https://api.nuget.org/v3-flatcontainer/microsoft.entityframeworkcore.sqlite/index.json
info : OK https://api.nuget.org/v3-flatcontainer/microsoft.entityframeworkcore.sqlite/index.json 818ms
info : GET https://api.nuget.org/v3-flatcontainer/microsoft.entityframeworkcore.sqlite/3.1.3/microsoft.entityframeworkcore.sqlite.3.1.3.nupkg
なんだその、index.json というのは。
{
"versions": [
"1.0.0",
[kanda@localhost RazorPagesMovie]$ dotnet aspnet-codegenerator razorpage -m Movie -dc RazorPagesMovieContext -udl -outDir Pages/Movies --referenceScriptLibraries
Added Razor Page : /Pages/Movies/Create.cshtml
Added PageModel : /Pages/Movies/Create.cshtml.cs
[kanda@localhost RazorPagesMovie]$ dotnet ef migrations add InitialCreate
Build started...
Build succeeded.
Done. To undo this action, use 'ef migrations remove'
[kanda@localhost RazorPagesMovie]$ dotnet ef database update
あっさり動いた。これはすごい。似たチュートリアルを、以前、 Windows + IIS + SQLServer Express でやったが、これは、 post Java, Jboss の標準になるのでないか。
sqlite データベースを見る。
[kanda@localhost RazorPagesMovie]$ sqlite3 MvcMovie.db
sqlite> select * from Movie;
1|Violet EverGarden|2020-04-24 00:00:00|animation|1500.0
https://docs.microsoft.com/ja-jp/dotnet/core/deploying/
に従う。
ランタイム依存のクロスプラットホームバイナリ
[kanda@localhost console]$ dotnet publish
[kanda@localhost publish]$ dotnet console.dll
Hello World!
Windows 10 に転送して、実行する。あれ?
C:\Users\kanda_000>dotnet console.dll
A fatal error was encountered. The library 'hostpolicy.dll' required to execute
the application was not found in 'C:\Users\kanda_000\'.
Failed to run as a self-contained app.
自己完結型の実行可能ファイル
[kanda@localhost console]$ dotnet publish -r linux-x64
[kanda@localhost publish]$ pwd
/home/kanda/csharp/console/bin/Debug/netcoreapp3.1/linux-x64/publish
[kanda@localhost publish]$ du -h .
75M .
[kanda@localhost publish]$ ls
Microsoft.CSharp.dll
..
これはでかい。
nuget パッケージを作る。
[kanda@localhost console]$ dotnet pack
Successfully created package '/home/kanda/csharp/console/bin/Debug/console.1.0.0.nupkg'.
[kanda@localhost Debug]$ ls -l console.1.0.0.nupkg
-rw-rw-r-- 1 kanda kanda 3801 4月 11 12:35 console.1.0.0.nupkg
zip ファイルなんだ。
[kanda@localhost Debug]$ unzip -l console.1.0.0.nupkg
Archive: console.1.0.0.nupkg
Length Date Time Name
--------- ---------- ----- ----
497 04-11-2020 12:35 _rels/.rels
467 04-11-2020 12:35 console.nuspec
146 04-11-2020 03:35 lib/netcoreapp3.1/console.runtimeconfig.json
4608 04-11-2020 03:35 lib/netcoreapp3.1/console.dll
522 04-11-2020 12:35 [Content_Types].xml
594 04-11-2020 12:35 package/services/metadata/core-properties/f581230e568449ceb0f264eb9edbeac1.psmdcp
--------- -------
6834 6 files
[kanda@localhost Debug]$ cat console.nuspec
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
<metadata>
<id>console</id>
<version>1.0.0</version>
<authors>console</authors>
<owners>console</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>Package Description</description>
<dependencies>
<group targetFramework=".NETCoreApp3.1" />
</dependencies>
</metadata>
本日のまとめ。
nuget は、 .net アセンブリを配布するためのパッケージングシステム。依存アセンブリは、それらの名前だけが入っている。 nuget restore というのは、実体を落として展開すること。save してないのに、なんで、 restore が必要なのだろう、と以前から思っていた。
PS /home/kanda> Invoke-WebRequest https://www.powershellgallery.com/api/v2
StatusCode : 200
StatusDescription : OK
リポジトリ
https://github.com/PowerShell/PowerShell
[kanda@localhost src]$ git branch
* (HEAD detached at v7.0.0)
このファイルだ。
[kanda@localhost src]$ ag --csharp WebRequest | grep Invoke
Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs:15: [Cmdlet(VerbsLifecycle.Invoke, "WebRequest", HelpUri = 。。
実体は、ほとんどない。
namespace Microsoft.PowerShell.Commands
{
[Cmdlet(VerbsLifecycle.Invoke, "WebRequest", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097126", DefaultParameterSetName = "StandardMethod")]
public class InvokeWebRequestCommand : WebRequestPSCmdlet
親クラス
Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs
public abstract partial class WebRequestPSCmdlet : PSCmdlet
{
protected override void ProcessRecord()
{
using (HttpClient client = GetHttpClient(keepAuthorization))
{
do
{
using (HttpRequestMessage request = GetRequest(uri))
{
FillRequestStream(request);
try
{
HttpResponseMessage response = GetResponse(client, request, keepAuthorization);
実体は、.NET の関数をすなおに使っているだけ。まあ、そうだわね。
リポジトリ
https://github.com/dotnet/runtime らしい。
https://github.com/microsoft/referencesource は、一部のソース、と書いてある。
このファイルらしい。
src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs
namespace System.Net.Http
{
public class HttpClient : HttpMessageInvoker
public static IWebProxy DefaultProxy
{
get => LazyInitializer.EnsureInitialized(ref s_defaultProxy, () => SystemProxyInfo.Proxy);
実は、 powershell on linux で、 http proxy をどこから引いてくるのか知りたい。
src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SystemProxyInfo.cs
7: internal static partial class SystemProxyInfo
internal static partial class SystemProxyInfo
{
public static IWebProxy Proxy => s_proxy.Value;
private static readonly Lazy<IWebProxy> s_proxy = new Lazy<IWebProxy>(ConstructSystemProxy);
}
src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SystemProxyInfo.Unix.cs
7: internal static partial class SystemProxyInfo
internal static partial class SystemProxyInfo
{
// On Unix (except for OSX) we get default proxy configuration from environment variables. If the
// environment variables are not defined, we return an IWebProxy object that effectively is
// the "no proxy" object.
public static IWebProxy ConstructSystemProxy()
{
return HttpEnvironmentProxy.TryCreate(out IWebProxy? proxy) ? proxy : new HttpNoProxy();
}
}
http_proxy などの環境変数からだった。まあ、それ以外にないわな。
HttpEnvironmentProxy.Unix.cs
internal sealed partial class HttpEnvironmentProxy : IWebProxy
{
private const string EnvAllProxyLC = "all_proxy";
private const string EnvHttpProxyLC = "http_proxy";
private const string EnvHttpsProxyLC = "https_proxy";
private const string EnvNoProxyLC = "no_proxy";
public static bool TryCreate([NotNullWhen(true)] out IWebProxy? proxy)
{
// Get environment variables. Protocol specific take precedence over
// general all_*, lower case variable has precedence over upper case.
// Note that curl uses HTTPS_PROXY but not HTTP_PROXY.
Uri? httpProxy = GetUriFromString(Environment.GetEnvironmentVariable(EnvHttpProxyLC));
ちなみに、 Windows では。
src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SystemProxyInfo.Windows.cs
7: internal static partial class SystemProxyInfo
internal static partial class SystemProxyInfo
{
// On Windows we get default proxy configuration from either environment variables or the Windows system proxy.
public static IWebProxy ConstructSystemProxy()
{
if (!HttpEnvironmentProxy.TryCreate(out IWebProxy? proxy))
{
HttpWindowsProxy.TryCreate(out proxy);
}
return proxy ?? new HttpNoProxy();
}
}
HttpWindowsProxy.cs
public static bool TryCreate([NotNullWhen(true)] out IWebProxy? proxy)
{
// This will get basic proxy setting from system using existing
// WinInetProxyHelper functions. If no proxy is enabled, it will return null.
SafeWinHttpHandle? sessionHandle = null;
proxy = null;
WinInetProxyHelper proxyHelper = new WinInetProxyHelper();
if (!proxyHelper.ManualSettingsOnly && !proxyHelper.AutoSettingsUsed)
{
return false;
}
if (proxyHelper.AutoSettingsUsed)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(proxyHelper, $"AutoSettingsUsed, calling {nameof(Interop.WinHttp.WinHttpOpen)}");
sessionHandle = Interop.WinHttp.WinHttpOpen(
Windows コントロールパネルの、プロキシ設定に対応するコードなのだろうな。
PS /home/kanda> Invoke-WebRequest https://www.powershellgallery.com/api/v2
Thread 17 "pwsh" hit Breakpoint 1, 0x00007ff3b1fd2d00 in connect ()
from /lib64/libpthread.so.0
(gdb) bt
#0 0x00007ff3b1fd2d00 in connect () from /lib64/libpthread.so.0
#1 0x00007ff3ac2e1a0d in SystemNative_Connect ()
from /opt/microsoft/powershell/7/System.Native.so
#2 0x00007ff33c620dd3 in ?? ()
#3 0x00007ff33609a3d0 in ?? ()
#4 0x000000000015f8c1 in ?? ()
#5 0x00007ff3b0bad728 in vtable for InlinedCallFrame ()
from /opt/microsoft/powershell/7/libcoreclr.so
[kanda@localhost src]$ ag SystemNative_Connect
libraries/Common/src/Interop/Unix/System.Native/Interop.Connect.cs
12: [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Connect")]
internal static partial class Interop
{
internal static partial class Sys
{
[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Connect")]
internal static extern unsafe Error Connect(SafeHandle socket, byte* socketAddress, int socketAddressLen);
}
}
libraries/Native/Unix/System.Native/pal_networking.c
int32_t SystemNative_Connect(intptr_t socket, uint8_t* socketAddress, int32_t socketAddressLen)
{
int fd = ToFileDescriptor(socket);
int err;
while ((err = connect(fd, (struct sockaddr*)socketAddress, (socklen_t)socketAddressLen)) < 0 && errno == EINTR);
return err == 0 ? Error_SUCCESS : SystemNative_ConvertErrorPlatformToPal(errno);
}
このへんが、 Windows/Unix 互換層らしい。
[kanda@localhost System.Native]$ pwd
/home/kanda/git/runtime/src/libraries/Native/Unix/System.Native
[kanda@localhost System.Native]$ ls
CMakeLists.txt pal_memory.c pal_runtimeinformation.c
..
.net core を ビルドする
[kanda@localhost runtime]$ ./build.sh
libicu-dev がない、
Please install CMake 3.14.2 or newer
ここまで対策したが、
liblttng-ust-dev で、あきらめた。 Centos8 には、そういうパッケージはないし、 el7 の devel パッケージは、バージョンが違うと言われて入らない。
https://docs.microsoft.com/ja-jp/aspnet/core/tutorials/grpc/grpc-start
に従う。
[kanda@localhost grpc]$ dotnet new grpc -o GrpcGreeter
[kanda@localhost grpcclient]$ dotnet new console -o GrpcGreeterClient
あら?
Unhandled exception. Grpc.Core.RpcException: Status(StatusCode=Internal, Detail="Error starting gRPC call: The SSL connection could not be established, see inner exception.")
証明書問題か。 TLS なしで動かそう。
に従う。
ビルド時に、HttpProtocols.Http2 が無いと言われたら、
using Microsoft.AspNetCore.Server.Kestrel.Core;
を追加する。
サーバは動いた。
[kanda@localhost ~]$ curl --http2-prior-knowledge http://localhost:5000/
Communication with gRPC endpoints must be made through a gRPC client.
クライアントも、
に従ってなおす。
できた。
[kanda@localhost GrpcGreeterClient]$ dotnet run
Greeting: Hello GreeterClient
Press any key to exit...
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/2 POST http://localhost:5000/greet.Greeter/SayHello application/grpc
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
Executing endpoint 'gRPC - /greet.Greeter/SayHello'
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint 'gRPC - /greet.Greeter/SayHello'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 1.3291ms 200 application/grpc
wireshark で、 grpc, http2 電文を見るには、grpc, http2 and wireshark を参照。
dotnet dev-certs https --trust
は、 linux では動かないので、手でやろうとしたが、証明書がどこにあるのかわからない。
これかな。
[kanda@localhost my]$ pwd
/home/kanda/.dotnet/corefx/cryptography/x509stores/my
[kanda@localhost my]$ ls
3C4F04C47B61ACD8D8B6249AA37356BAEBBF3BD9.pfx
[kanda@localhost my]$ openssl pkcs12 -in 3C4F04C47B61ACD8D8B6249AA37356BAEBBF3BD9.pfx
Enter Import Password:
わからん。
Windows だと、ここに入る。
https://docs.microsoft.com/ja-jp/dotnet/core/diagnostics/dotnet-trace
に従う。
[kanda@localhost ~]$ dotnet tool install --global dotnet-trace
[kanda@localhost ~]$ dotnet-trace list-profiles
cpu-sampling - Useful for tracking CPU usage and general .NET runtime information. This is the default option if no profile or providers are specified.
gc-verbose - Tracks GC collections and samples object allocations.
gc-collect - Tracks GC collections only at very low overhead.
[kanda@localhost ~]$ dotnet-trace collect -p 9355 --format Speedscope
No profile or providers specified, defaulting to trace profile 'cpu-sampling'
Provider Name Keywords Level Enabled By
Microsoft-DotNETCore-SampleProfiler 0x0000000000000000 Informational(4) --profile
Microsoft-Windows-DotNETRuntime 0x00000014C14FCCBD Informational(4) --profile
Process : /home/kanda/csharp/GrpcGreeterClient/bin/Debug/netcoreapp3.1/GrpcGreeterClient
Output File : /home/kanda/trace.nettrace
[00:00:00:05] Recording trace 1.0373 (MB)
Press <Enter> or <Ctrl+C> to exit...
Trace completed.
Writing: /home/kanda/trace.speedscope.json
Conversion complete
Web ブラウザにロードして見る。今ひとつ、見かたがわからん。perf の結果も見られるそうなので、それで調べよう。
Windows の PerfView を使ってみる。
C:\PerfView.exe trace.nettrace
スタック表示で、上から下に呼び出し元と先モジュールが見えて、消費時間がわかる、という画面はまあ、わかる。使いこなすには、きちんと文書を読まないといけない。
それとも、モジュールのデータベースがあるのか。
[kanda@localhost src]$ ag Uninstall-Module
powershell-unix/bin/Debug/netcoreapp5.0/linux-x64/publish/Modules/PowerShellGet/PowerShellGet.psd1
@{
RootModule = 'PSModule.psm1'
FunctionsToExport = @(
'Uninstall-Module',
ここにあるらしい。
powershell-unix/bin/Debug/netcoreapp5.0/linux-x64/publish/Modules/PowerShellGet/PSModule.psm1
function Uninstall-Module
実体は、これらしい。
$null = PackageManagement\Uninstall-Package @PSBoundParameters
function Uninstall-Package
PSGetInstalledModules に、削除しようとするモジュールがなければ、エラー。
なんだこれ。データベースなのか?実行時にディレクトリを探しているのか。
$InstalledModuleInfo = $script:PSGetInstalledModules["$($moduleName)$($version)"]
if(-not $InstalledModuleInfo)
{
$message = $LocalizedData.ModuleUninstallationNotPossibleAsItIsNotInstalledUsingPowerShellGet -f $moduleName
削除しようとするモジュールに依存している人がいれば、エラー。
$dependentModuleScript = {
param ([string] $moduleName)
Microsoft.PowerShell.Core\Get-Module -ListAvailable |
Microsoft.PowerShell.Core\Where-Object {
($moduleName -ne $_.Name) -and (
($_.RequiredModules -and $_.RequiredModules.Name -contains $moduleName) -or
($_.NestedModules -and $_.NestedModules.Name -contains $moduleName))
}
}
これが、ディレクトリの削除。
Microsoft.PowerShell.Management\Remove-Item -Path $ModuleBaseFolderToBeRemoved `
-Force -Recurse `
-ErrorAction SilentlyContinue `
-WarningAction SilentlyContinue `
-Confirm:$false -WhatIf:$false
bin にあるということは、他のソースをビルドした結果だろうが、もとねたがわからない。まあいいか。
カバレッジをとる
のは、Linux では面倒そう。
https://docs.microsoft.com/ja-jp/dotnet/core/tutorials/testing-with-cli
に従う。
[kanda@localhost NewTypesTests]$ pwd
/home/kanda/git/dotnet/samples/core/console-apps/NewTypesMsBuild/test/NewTypesTests
[kanda@localhost NewTypesTests]$ dotnet new xunit
[kanda@localhost NewTypesTests]$ dotnet test
[xUnit.net 00:00:00.71] NewTypesTests.UnitTest1.DogTalkToOwnerReturnsWoof [FAIL]
X NewTypesTests.UnitTest1.DogTalkToOwnerReturnsWoof [5ms]
Error Message:
Assert.NotEqual() Failure
Expected: Not "Woof!"
Actual: "Woof!"
Stack Trace:
at NewTypesTests.UnitTest1.DogTalkToOwnerReturnsWoof() in /home/kanda/git/dotnet/samples/core/console-apps/NewTypesMsBuild/test/NewTypesTests/PetTests.cs:line 13
Test Run Failed.
Total tests: 1
Failed: 1
Visual Studio code で、 Debug Test を押したら、こう言われた。なんで?
Failed to start debugger: "System.InvalidOperationException: The debugger could not be started\n at OmniSharp.DotNetTest.Services.DebugTestService.Handle (OmniSharp.DotNetTest.Models.DebugTestGetStartInfoRequest request) [0x0004a] in <15fcd90c145d4c7da4c544801bb6f3fd>:0 \n at OmniSharp.Endpoint.Exports.RequestHandlerExportHandler`2[TRequest,TResponse].Handle (TRequest request) [0x00000] in <65b65aa47dd84527b66fbba929d6fb42>:0 \n at OmniSharp.Endpoint.EndpointHandler`2[TRequest,TResponse].GetFirstNotEmptyResponseFromHandlers (OmniSharp.Endpoint.Exports.ExportHandler`2[TRequest,TResponse][] handlers, TRequest request) [0x00022] in <65b65aa47dd84527b66fbba929d6fb42>:0 \n at OmniSharp.Endpoint.EndpointHandler`2[TRequest,TResponse].HandleRequestForLanguage (System.String language, TRequest request, OmniSharp.Protocol.RequestPacket packet) [0x00163] in <65b65aa47dd84527b66fbba929d6fb42>:0 \n at OmniSharp.Endpoint.EndpointHandler`2[TRequest,TResponse].Process (OmniSharp.Protocol.RequestPacket packet, OmniSharp.Endpoint.LanguageModel model, Newtonsoft.Json.Linq.JToken requestObject) [0x0024b] in <65b65aa47dd84527b66fbba929d6fb42>:0 \n at OmniSharp.Stdio.Host.HandleRequest (System.String json, Microsoft.Extensions.Logging.ILogger logger) [0x000e7] in <37764013d46e4991957fbb61092f4a0f>:0 "
collect というオプションがあるから、動くかと思ったがだめだった。
[kanda@localhost NewTypesTests]$ dotnet test --collect "Code Coverage"
Data collector 'Code Coverage' message: コード カバレッジ データを利用できません。現在、コード カバレッジは Windows でのみサポートされています。.
Test Run Successful.
Total tests: 1
Passed: 1
に従う。
[kanda@localhost BooksApi]$ dotnet add BooksApi.csproj package -v 2.10.3 MongoDB.Driver
info : Adding PackageReference for package 'MongoDB.Driver' into project 'BooksApi.csproj'.
info : Restoring packages for /home/kanda/csharp/BooksApi/BooksApi.csproj...
info : GET https://api.nuget.org/v3-flatcontainer/mongodb.driver/2.10.3/mongodb.driver.2.10.3.nupkg
[kanda@localhost BooksApi]$ dotnet build
Restore completed in 16.61 ms for /home/kanda/csharp/BooksApi/BooksApi.csproj.
Startup.cs(35,39): error CS0246: 型または名前空間の名前 'IOptions<>' が見つかりませんでした
と言われたら、Startup.cs に、以下を追加する。
using Microsoft.Extensions.Options;
[kanda@localhost BooksApi]$ dotnet run
info: Microsoft.Hosting.Lifetime[0]
Now listening on: https://localhost:5001
[kanda@localhost ~]$ curl -k https://localhost:5001/api/books
[{"id":"5e9560f4a22542666e1771c5","bookName":"Design Patterns","price":54.93,"category":"Computers","author":"Ralph Johnson"},
{"id":"5e9560f4a22542666e1771c6","bookName":"Clean Code","price":43.15,"category":"Computers","author":"Robert C. Martin"}][
[kanda@localhost ~]$ curl -s -k https://localhost:5001/api/books/5e9560f4a22542666e1771c5 | python3 -m json.tool
{
"id": "5e9560f4a22542666e1771c5",
"bookName": "Design Patterns",
"price": 54.93,
"category": "Computers",
"author": "Ralph Johnson"
}
JsonProperty が無いと言われたら、
[kanda@localhost BooksApi]$ dotnet add BooksApi.csproj package Microsoft.AspNetCore.Mvc.NewtonsoftJson
info : Adding PackageReference for package 'Microsoft.AspNetCore.Mvc.NewtonsoftJson' into project 'BooksApi.csproj'.
info : GET https://api.nuget.org/v3-flatcontainer/microsoft.aspnetcore.mvc.newtonsoftjson/3.1.3/microsoft.aspnetcore.mvc.newtonsoftjson.3.1.3.nupkg
[kanda@localhost BooksApi]$ dotnet run
[kanda@localhost BooksApi]$ curl -s -k https://localhost:5001/api/books/5e9560f4a22542666e1771c5 | python3 -m json.tool
{
"Id": "5e9560f4a22542666e1771c5",
"Name": "Design Patterns",
"Price": 54.93,
"Category": "Computers",
"Author": "Ralph Johnson"
}
なるほど。 bookName が、 Name になった。
作成
id は、つけなくても、振ってくれる。
[kanda@localhost ~]$ curl -k -X POST -H "Content-Type: application/json" -d '{ "Name": "Quantum Computation and Quantum Information", "Price": 7183, "Category": "Quantum Computers", "Author": "Nielsen & Chuang" }' https://localhost:5001/api/books
{"Id":"5e9570fabc476528b8406c59","Name":"Quantum Computation and Quantum Information","Price":7183.0,"Category":"Quantum Computers","Author":"Nielsen & Chuang"}
削除
[kanda@localhost ~]$ curl -k -X DELETE https://localhost:5001/api/books/5e9570fabc476528b8406c59
Content-Type は必須。
[kanda@localhost ~]$ curl -k -X POST -d '{ "Name": "A", "Price": 1, "Category": "B", "Author": "C" }' https://localhost:5001/api/books
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"|de49ff2d-4d08c36e6cf2a74b."}[
変更
[kanda@localhost ~]$ curl -k -X PUT -H "Content-Type: application/json" -d '{ "Name": "あ", "Price": 2, "Category": "い", "Author": "う" }' https://localhost:5001/api/books/5e95729dbc476528b8406c5b
MongoDB.Driver.MongoWriteException: A write operation resulted in an error.
After applying the update, the (immutable) field '_id' was found to have been altered to _id: null
---> MongoDB.Driver.MongoBulkWriteException`1[BooksApi.Models.Book]: A bulk write operation resulted in one or more errors.
After applying the update, the (immutable) field '_id' was found to have been altered to _id: null
at MongoDB.Driver.MongoCollectionImpl`1.BulkWrite(IClientSessionHandle session, IEnumerable`1 requests, BulkWriteOptions options, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.<>c__DisplayClass23_0.<BulkWrite>b__0(IClientSessionHandle session)
at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSession[TResult](Func`2 func, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.BulkWrite(IEnumerable`1 requests, BulkWriteOptions options, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionBase`1.<>c__DisplayClass82_0.<ReplaceOne>b__0(IEnumerable`1 requests, BulkWriteOptions bulkWriteOptions)
at MongoDB.Driver.MongoCollectionBase`1.ReplaceOne(FilterDefinition`1 filter, TDocument replacement, ReplaceOptions options, Func`3 bulkWrite)
--- End of inner exception stack trace ---
at MongoDB.Driver.MongoCollectionBase`1.ReplaceOne(FilterDefinition`1 filter, TDocument replacement, ReplaceOptions options, Func`3 bulkWrite)
at MongoDB.Driver.MongoCollectionBase`1.ReplaceOne(FilterDefinition`1 filter, TDocument replacement, ReplaceOptions options, CancellationToken cancellationToken)
at MongoDB.Driver.IMongoCollectionExtensions.ReplaceOne[TDocument](IMongoCollection`1 collection, Expression`1 filter, TDocument replacement, ReplaceOptions options, CancellationToken cancellationToken)
at BooksApi.Services.BookService.Update(String id, Book bookIn) in /home/kanda/csharp/BooksApi/Services/BookService.cs:line 33
at BooksApi.Controllers.BooksController.Update(String id, Book bookIn) in /home/kanda/csharp/BooksApi/Controllers/BooksController.cs:line 54
at lambda_method(Closure , Object , Object[] )
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
HEADERS
=======
Content-Type: application/json
Accept: */*
Host: localhost:5001
User-Agent: curl/7.61.1
Content-Length: 65
:method: PUT
:path: /api/books/5e95729dbc476528b8406c5b
:scheme: https
:authority: localhost:5001
PUT は、 id が必要。
[kanda@localhost ~]$ curl -k -X PUT -H "Content-Type: application/json" -d '{ "Id": "5e95729dbc476528b8406c5b", "Name": "あ", "Price": 2, "Category": "い", "Author": "う" }' https://localhost:5001/api/books/5e95729dbc476528b8406c5b
not found
[kanda@localhost BooksApi]$ curl -v -k https://localhost:5001/api/1234
< HTTP/2 404
https://docs.microsoft.com/ja-jp/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1
$ cat appsettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Trace",
"Microsoft": "Trace",
"Microsoft.Hosting.Lifetime": "Trace"
}
}
}
[kanda@localhost BooksApi]$ curl -s -k https://localhost:5001/api/books/5bc476528b8406c5b
[kanda@localhost BooksApi]$ dotnet run
dbug: Microsoft.Extensions.Hosting.Internal.Host[1]
Hosting starting
dbug: Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer[2]
Failed to locate the development https certificate at '(null)'.
dbug: Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer[0]
Using development certificate: CN=localhost (Thumbprint: 3C4F04C47B61ACD8D8B6249AA37356BAEBBF3BD9)
info: Microsoft.Hosting.Lifetime[0]
Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://localhost:5000
dbug: Microsoft.AspNetCore.Hosting.Diagnostics[0]
Loaded hosting startup assembly BooksApi
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: /home/kanda/csharp/BooksApi
dbug: Microsoft.Extensions.Hosting.Internal.Host[2]
Hosting started
dbug: Microsoft.AspNetCore.Server.Kestrel[39]
Connection id "0HLV09UNBQ9MD" accepted.
dbug: Microsoft.AspNetCore.Server.Kestrel[1]
Connection id "0HLV09UNBQ9MD" started.
trce: Microsoft.AspNetCore.Server.Kestrel[37]
Connection id "0HLV09UNBQ9MD" sending SETTINGS frame for stream ID 0 with length 18 and flags NONE
trce: Microsoft.AspNetCore.Server.Kestrel[37]
Connection id "0HLV09UNBQ9MD" sending WINDOW_UPDATE frame for stream ID 0 with length 4 and flags 0x0
trce: Microsoft.AspNetCore.Server.Kestrel[37]
Connection id "0HLV09UNBQ9MD" received SETTINGS frame for stream ID 0 with length 18 and flags NONE
trce: Microsoft.AspNetCore.Server.Kestrel[37]
Connection id "0HLV09UNBQ9MD" sending SETTINGS frame for stream ID 0 with length 0 and flags ACK
trce: Microsoft.AspNetCore.Server.Kestrel[37]
Connection id "0HLV09UNBQ9MD" received WINDOW_UPDATE frame for stream ID 0 with length 4 and flags 0x0
trce: Microsoft.AspNetCore.Server.Kestrel[37]
Connection id "0HLV09UNBQ9MD" received HEADERS frame for stream ID 1 with length 56 and flags END_STREAM, END_HEADERS
trce: Microsoft.AspNetCore.Server.Kestrel[37]
Connection id "0HLV09UNBQ9MD" received SETTINGS frame for stream ID 0 with length 0 and flags ACK
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/2 GET https://localhost:5001/api/books/5e95729dbc476528b8406c5b
dbug: Microsoft.AspNetCore.HostFiltering.HostFilteringMiddleware[0]
Wildcard detected, all requests with hosts will be allowed.
trce: Microsoft.AspNetCore.HostFiltering.HostFilteringMiddleware[2]
All hosts are allowed.
dbug: Microsoft.AspNetCore.Routing.Matching.DfaMatcher[1001]
1 candidate(s) found for the request path '/api/books/5e95729dbc476528b8406c5b'
dbug: Microsoft.AspNetCore.Routing.Matching.DfaMatcher[1005]
Endpoint 'BooksApi.Controllers.BooksController.Get (BooksApi)' with route pattern 'api/Books/{id:length(24)}' is valid for the request path '/api/books/5e95729dbc476528b8406c5b'
dbug: Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware[1]
Request matched endpoint 'BooksApi.Controllers.BooksController.Get (BooksApi)'
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
Executing endpoint 'BooksApi.Controllers.BooksController.Get (BooksApi)'
dbug: Microsoft.AspNetCore.Mvc.ModelBinding.ModelBinderFactory[12]
Registered model binder providers, in the following order: Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BinderTypeModelBinderProvider, Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ServicesModelBinderProvider, Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinderProvider, Microsoft.AspNetCore.Mvc.ModelBinding.Binders.HeaderModelBinderProvider, Microsoft.AspNetCore.Mvc.ModelBinding.Binders.FloatingPointTypeModelBinderProvider, Microsoft.AspNetCore.Mvc.ModelBinding.Binders.EnumTypeModelBinderProvider, Microsoft.AspNetCore.Mvc.ModelBinding.Binders.SimpleTypeModelBinderProvider, Microsoft.AspNetCore.Mvc.ModelBinding.Binders.CancellationTokenModelBinderProvider, Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ByteArrayModelBinderProvider, Microsoft.AspNetCore.Mvc.ModelBinding.Binders.FormFileModelBinderProvider, Microsoft.AspNetCore.Mvc.ModelBinding.Binders.FormCollectionModelBinderProvider, Microsoft.AspNetCore.Mvc.ModelBinding.Binders.KeyValuePairModelBinderProvider, Microsoft.AspNetCore.Mvc.ModelBinding.Binders.DictionaryModelBinderProvider, Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ArrayModelBinderProvider, Microsoft.AspNetCore.Mvc.ModelBinding.Binders.CollectionModelBinderProvider, Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinderProvider
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Route matched with {action = "Get", controller = "Books"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.ActionResult`1[BooksApi.Models.Book] Get(System.String) on controller BooksApi.Controllers.BooksController (BooksApi).
dbug: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[1]
Execution plan of authorization filters (in the following order): None
dbug: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[1]
Execution plan of resource filters (in the following order): None
dbug: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[1]
Execution plan of action filters (in the following order): Microsoft.AspNetCore.Mvc.ModelBinding.UnsupportedContentTypeFilter (Order: -3000), Microsoft.AspNetCore.Mvc.Infrastructure.ModelStateInvalidFilter (Order: -2000)
dbug: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[1]
Execution plan of exception filters (in the following order): None
dbug: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[1]
Execution plan of result filters (in the following order): Microsoft.AspNetCore.Mvc.Infrastructure.ClientErrorResultFilter (Order: -2000)
dbug: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[1]
Executing controller factory for controller BooksApi.Controllers.BooksController (BooksApi)
dbug: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Executed controller factory for controller BooksApi.Controllers.BooksController (BooksApi)
dbug: Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder[22]
Attempting to bind parameter 'id' of type 'System.String' ...
dbug: Microsoft.AspNetCore.Mvc.ModelBinding.Binders.SimpleTypeModelBinder[44]
Attempting to bind parameter 'id' of type 'System.String' using the name 'id' in request data ...
dbug: Microsoft.AspNetCore.Mvc.ModelBinding.Binders.SimpleTypeModelBinder[45]
Done attempting to bind parameter 'id' of type 'System.String'.
dbug: Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder[23]
Done attempting to bind parameter 'id' of type 'System.String'.
dbug: Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder[26]
Attempting to validate the bound parameter 'id' of type 'System.String' ...
dbug: Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder[27]
Done attempting to validate the bound parameter 'id' of type 'System.String'.
trce: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Action Filter: Before executing OnActionExecuting on filter Microsoft.AspNetCore.Mvc.ModelBinding.UnsupportedContentTypeFilter.
trce: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Action Filter: After executing OnActionExecuting on filter Microsoft.AspNetCore.Mvc.ModelBinding.UnsupportedContentTypeFilter.
trce: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Action Filter: Before executing OnActionExecuting on filter Microsoft.AspNetCore.Mvc.Infrastructure.ModelStateInvalidFilter.
trce: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Action Filter: After executing OnActionExecuting on filter Microsoft.AspNetCore.Mvc.Infrastructure.ModelStateInvalidFilter.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[1]
Executing action method BooksApi.Controllers.BooksController.Get (BooksApi) - Validation state: Valid
trce: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[1]
Executing action method BooksApi.Controllers.BooksController.Get (BooksApi) with arguments (5e95729dbc476528b8406c5b)
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Executed action method BooksApi.Controllers.BooksController.Get (BooksApi), returned result Microsoft.AspNetCore.Mvc.ObjectResult in 71.0764ms.
trce: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Action Filter: Before executing OnActionExecuted on filter Microsoft.AspNetCore.Mvc.Infrastructure.ModelStateInvalidFilter.
trce: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Action Filter: After executing OnActionExecuted on filter Microsoft.AspNetCore.Mvc.Infrastructure.ModelStateInvalidFilter.
trce: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Action Filter: Before executing OnActionExecuted on filter Microsoft.AspNetCore.Mvc.ModelBinding.UnsupportedContentTypeFilter.
trce: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Action Filter: After executing OnActionExecuted on filter Microsoft.AspNetCore.Mvc.ModelBinding.UnsupportedContentTypeFilter.
trce: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Result Filter: Before executing OnResultExecuting on filter Microsoft.AspNetCore.Mvc.Infrastructure.ClientErrorResultFilter.
trce: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Result Filter: After executing OnResultExecuting on filter Microsoft.AspNetCore.Mvc.Infrastructure.ClientErrorResultFilter.
trce: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[4]
Before executing action result Microsoft.AspNetCore.Mvc.ObjectResult.
dbug: Microsoft.AspNetCore.Mvc.Infrastructure.DefaultOutputFormatterSelector[11]
List of registered output formatters, in the following order: Microsoft.AspNetCore.Mvc.Formatters.HttpNoContentOutputFormatter, Microsoft.AspNetCore.Mvc.Formatters.StringOutputFormatter, Microsoft.AspNetCore.Mvc.Formatters.StreamOutputFormatter, Microsoft.AspNetCore.Mvc.Formatters.NewtonsoftJsonOutputFormatter
dbug: Microsoft.AspNetCore.Mvc.Infrastructure.DefaultOutputFormatterSelector[4]
No information found on request to perform content negotiation.
dbug: Microsoft.AspNetCore.Mvc.Infrastructure.DefaultOutputFormatterSelector[8]
Attempting to select an output formatter without using a content type as no explicit content types were specified for the response.
dbug: Microsoft.AspNetCore.Mvc.Infrastructure.DefaultOutputFormatterSelector[10]
Attempting to select the first formatter in the output formatters list which can write the result.
dbug: Microsoft.AspNetCore.Mvc.Infrastructure.DefaultOutputFormatterSelector[2]
Selected output formatter 'Microsoft.AspNetCore.Mvc.Formatters.NewtonsoftJsonOutputFormatter' and content type 'application/json' to write the response.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor[1]
Executing ObjectResult, writing value of type 'BooksApi.Models.Book'.
trce: Microsoft.AspNetCore.Server.Kestrel[37]
Connection id "0HLV09UNBQ9MD" sending HEADERS frame for stream ID 1 with length 118 and flags END_HEADERS
trce: Microsoft.AspNetCore.Server.Kestrel[37]
Connection id "0HLV09UNBQ9MD" sending DATA frame for stream ID 1 with length 90 and flags NONE
dbug: Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets[6]
Connection id "0HLV09UNBQ9MD" received FIN.
trce: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[5]
After executing action result Microsoft.AspNetCore.Mvc.ObjectResult.
trce: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Result Filter: Before executing OnResultExecuted on filter Microsoft.AspNetCore.Mvc.Infrastructure.ClientErrorResultFilter.
trce: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Result Filter: After executing OnResultExecuted on filter Microsoft.AspNetCore.Mvc.Infrastructure.ClientErrorResultFilter.
dbug: Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets[7]
Connection id "0HLV09UNBQ9MD" sending FIN because: "The client closed the connection."
dbug: Microsoft.AspNetCore.Server.Kestrel[36]
Connection id "0HLV09UNBQ9MD" is closed. The last processed stream ID was 1.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Executed action BooksApi.Controllers.BooksController.Get (BooksApi) in 365.4898ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint 'BooksApi.Controllers.BooksController.Get (BooksApi)'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 503.6413ms 200 application/json; charset=utf-8
dbug: Microsoft.AspNetCore.Server.Kestrel[2]
Connection id "0HLV09UNBQ9MD" stopped.
落ちるプログラムを書く。
[kanda@localhost console]$ cat Program.cs
class Program
{
static void Main(string[] args)
{
string s = args[0];
int i = System.Int32.Parse(s);
System.Console.WriteLine("Hello World!");
i = 1/i;
}
}
落とす。
[kanda@localhost console]$ dotnet run 0
Hello World!
Unhandled exception. System.DivideByZeroException: Attempted to divide by zero.
at Program.Main(String[] args) in /home/kanda/csharp/console/Program.cs:line 8
syslog に出る。
4月 15 09:48:48 localhost.localdomain systemd[1]: Started Process Core Dump (PID 10289/UID 0).
4月 15 09:48:48 localhost.localdomain systemd-coredump[10290]: Process 10279 (console) of user 1000 dumped core.
Stack trace of thread 10279:
#0 0x00007f78d16068df raise (libc.so.6)
#1 0x00007f78d15f0cf5 abort (libc.so.6)
#2 0x00007f78d0c498ae PROCAbort (libcoreclr.so)
#3 0x00007f78d0c497f1 _ZL14PROCEndProcessPvji (libcoreclr.so)
#4 0x00007f78d09fefe7 _Z27UnwindManagedExceptionPass1R16PAL_SEHExceptionP8_CONTEXT (libcoreclr.so)
#5 0x00007f78d09ff076 _Z24DispatchManagedExceptionR16PAL_SEHExceptionb (libcoreclr.so)
#6 0x00007f78d09f8e90 _Z23HandleHardwareExceptionP16PAL_SEHException (libcoreclr.so)
#7 0x00007f78d0c151f5 _Z19SEHProcessExceptionP16PAL_SEHException (libcoreclr.so)
#8 0x00007f78d0c168d1 _ZL21common_signal_handleriP9siginfo_tPviz (libcoreclr.so)
#9 0x00007f78d0c16112 _ZL14sigfpe_handleriP9siginfo_tPv (libcoreclr.so)
#10 0x00007f78d24d7dc0 __restore_rt (libpthread.so.0)
#11 0x00007f7857640525 n/a (n/a)
#12 0x00007f78d0a0b5ff CallDescrWorkerInternal (libcoreclr.so)
#13 0x00007f78d0937eb1 _ZN18MethodDescCallSite16CallTargetWorkerEPKmPmi (libcoreclr.so)
#14 0x00007f78d0a20a66 _Z7RunMainP10MethodDescsPiPP8PtrArray (libcoreclr.so)
#15 0x00007f78d0a20dd9 _ZN8Assembly17ExecuteMainMethodEPP8PtrArrayi (libcoreclr.so)
#16 0x00007f78d08801f2 _ZN8CorHost215ExecuteAssemblyEjPKDsiPS1_Pj (libcoreclr.so)
#17 0x00007f78d0857903 coreclr_execute_assembly (libcoreclr.so)
#18 0x00007f78d113815c _Z19run_app_for_contextRK20hostpolicy_context_tiPPKc (libhostpolicy.so)
#19 0x00007f78d11384ee _Z7run_appiPPKc (libhostpolicy.so)
#20 0x00007f78d1138cfc corehost_main (libhostpolicy.so)
#21 0x00007f78d139cbb2 _ZN10fx_muxer_t24handle_exec_host_commandERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERK19host_startup_info_tS7_RKSt13unordered_mapI13known_optionsSt6vectorIS5_SaIS5_EE18known_options_hashSt8equal_toISC_ESaISt4pairIKSC_SF_EEEiPPKci11host_mode_tPciPi (libhostfxr.so)
#22 0x00007f78d139bc73 _ZN10fx_muxer_t7executeENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEiPPKcRK19host_startup_info_tPciPi (libhostfxr.so)
#23 0x00007f78d1397d91 hostfxr_main_startupinfo (libhostfxr.so)
#24 0x000000000040eba6 n/a (/home/kanda/csharp/console/bin/Debug/netcoreapp3.1/console)
gdb で見る。
デバッグシンボルを入れる。
[root@localhost yum.repos.d]# dnf debuginfo-install dotnet-hostfxr-3.1-3.1.1-1.el8.x86_64 dotnet-runtime-3.1-3.1.1-1.el8.x86_64 glibc-2.28-72.el8_1.1.x86_64 libgcc-8.3.1-4.5.el8.x86_64
[root@localhost coredump]# coredumpctl debug 10279
(gdb) bt
#0 __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
#1 0x00007f78d15f0cf5 in __GI_abort () at abort.c:79
#2 0x00007f78d0c498ae in PROCAbort () at /usr/src/debug/dotnet3.1-3.1.101-1.el8.x86_64/src/coreclr.5558d18aafc84ecac3630ca6a31f52699cde0b66/src/pal/src/thread/process.cpp:3479
#3 0x00007f78d0c497f1 in PROCEndProcess (hProcess=<optimized out>, uExitCode=1, bTerminateUnconditionally=1)
at /usr/src/debug/dotnet3.1-3.1.101-1.el8.x86_64/src/coreclr.5558d18aafc84ecac3630ca6a31f52699cde0b66/src/pal/src/thread/process.cpp:1480
#4 0x00007f78d09fefe7 in UnwindManagedExceptionPass1 (ex=..., frameContext=0x7ffd97fcfcf0)
at /usr/src/debug/dotnet3.1-3.1.101-1.el8.x86_64/src/coreclr.5558d18aafc84ecac3630ca6a31f52699cde0b66/src/vm/exceptionhandling.cpp:4698
#5 0x00007f78d09ff076 in DispatchManagedException (ex=..., isHardwareException=false)
at /usr/src/debug/dotnet3.1-3.1.101-1.el8.x86_64/src/coreclr.5558d18aafc84ecac3630ca6a31f52699cde0b66/src/vm/exceptionhandling.cpp:4770
#6 0x00007f78d09f8e90 in HandleHardwareException (ex=0x7ffd97fd0830)
at /usr/src/debug/dotnet3.1-3.1.101-1.el8.x86_64/src/coreclr.5558d18aafc84ecac3630ca6a31f52699cde0b66/src/vm/exceptionhandling.cpp:5270
#7 0x00007f78d0c151f5 in SEHProcessException (exception=0x7ffd97fd0830)
at /usr/src/debug/dotnet3.1-3.1.101-1.el8.x86_64/src/coreclr.5558d18aafc84ecac3630ca6a31f52699cde0b66/src/pal/src/exception/seh.cpp:286
#8 0x00007f78d0c168d1 in common_signal_handler (code=8, siginfo=<optimized out>, sigcontext=0x7ffd97fd0ec0, numParams=<optimized out>)
at /usr/src/debug/dotnet3.1-3.1.101-1.el8.x86_64/src/coreclr.5558d18aafc84ecac3630ca6a31f52699cde0b66/src/pal/src/exception/signal.cpp:858
#9 0x00007f78d0c16112 in sigfpe_handler (code=8, siginfo=0x7ffd97fd0ff0, context=0x7ffd97fd0ec0)
at /usr/src/debug/dotnet3.1-3.1.101-1.el8.x86_64/src/coreclr.5558d18aafc84ecac3630ca6a31f52699cde0b66/src/pal/src/exception/signal.cpp:346
#10 <signal handler called>
#11 0x00007f7857640525 in ?? ()
#12 0x00007ffd97fd17c8 in ?? ()
#13 0x0000000000000000 in ?? ()
(gdb)
うーん。知りたいのはアセンブリの中の、 C# プログラムのふるまいであって、外側のランタイムのふるまいではない。 gdb だから無理か。
https://docs.microsoft.com/ja-jp/dotnet/core/diagnostics/dotnet-dump
に従う。
[kanda@localhost console]$ dotnet tool install -g dotnet-dump
次のコマンドを使用してツールを呼び出せます。dotnet-dump
ツール 'dotnet-dump' (バージョン '3.1.120604') が正常にインストールされました。
圧縮されているからだめなだけだ。
[root@localhost coredump]# dotnet-dump analyze core.console.1000.f900c677cff146d994a0ecd1a9aabc53.10279.1586911728000000.lz4
Loading core dump: core.console.1000.f900c677cff146d994a0ecd1a9aabc53.10279.1586911728000000.lz4 ...
/var/lib/systemd/coredump/core.console.1000.f900c677cff146d994a0ecd1a9aabc53.10279.1586911728000000.lz4 does not contain a valid ELF header.
[root@localhost coredump]# lz4cat core.console.1000.f900c677cff146d994a0ecd1a9aabc53.10279.1586911728000000.lz4 > /tmp/core.console
[root@localhost coredump]# file /tmp/core.console
/tmp/core.console: ELF 64-bit LSB core file x86-64, version 1 (SYSV), SVR4-style, from '/home/kanda/csharp/console/bin/Debug/netcoreapp3.1/console 0', real uid: 1000, effective uid: 1000, real gid: 1000, effective gid: 1000, execfn: '/home/kanda/csharp/console/bin/Debug/netcoreapp3.1/console', platform: 'x86_64'
すごい。見えた。
[kanda@localhost ~]$ dotnet-dump analyze /tmp/core.console
Loading core dump: /tmp/core.console ...
Ready to process analysis commands. Type 'help' to list available commands or 'help [command]' to get detailed help on a command.
Type 'quit' or 'exit' to exit the session.
> printexception
Exception object: 00007f7830017e00
Exception type: <Unknown>
Message: Attempted to divide by zero.
InnerException: <none>
StackTrace (generated):
SP IP Function
00007FFD97FD1550 00007F7857640525 console.dll!Unknown+0x75
StackTraceString: <none>
HResult: 80020012
> clrstack
OS Thread Id: 0x2827 (0)
Child SP IP Call Site
00007FFD97FD0200 00007f78d16068df [FaultingExceptionFrame: 00007ffd97fd0200]
00007FFD97FD1550 00007F7857640525 /home/kanda/csharp/console/bin/Debug/netcoreapp3.1/console.dll!Unknown
00007FFD97FD1848 00007f78d0a0b5ff [GCFrame: 00007ffd97fd1848]
00007FFD97FD1D40 00007f78d0a0b5ff [GCFrame: 00007ffd97fd1d40]
>
自分の書いたプログラムのシンボルつまり pdb を与えるにはどうするのだろう。
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
int i = System.Int32.Parse("0");
i = 1/i; // crash
あら、落ちない。
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
Executing endpoint 'gRPC - /greet.Greeter/SayHello'
fail: Grpc.AspNetCore.Server.ServerCallHandler[6]
Error when executing service method 'SayHello'.
System.DivideByZeroException: Attempted to divide by zero.
at GrpcGreeter.GreeterService.SayHello(HelloRequest request, ServerCallContext context) in /home/kanda/csharp/GrpcGreeter/Services/GreeterService.cs:line 21
at Grpc.AspNetCore.Server.Internal.CallHandlers.UnaryServerCallHandler`3.HandleCallAsyncCore(HttpContext httpContext, HttpContextServerCallContext serverCallContext)
at Grpc.AspNetCore.Server.Internal.CallHandlers.UnaryServerCallHandler`3.HandleCallAsyncCore(HttpContext httpContext, HttpContextServerCallContext serverCallContext)
at Grpc.AspNetCore.Server.Internal.CallHandlers.ServerCallHandlerBase`3.<HandleCallAsync>g__AwaitHandleCall|17_0(HttpContextServerCallContext serverCallContext, Method`2 method, Task handleCall)
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint 'gRPC - /greet.Greeter/SayHello'
クライアントが落ちた。
[kanda@localhost GrpcGreeterClient]$ dotnet run
Unhandled exception. Grpc.Core.RpcException: Status(StatusCode=Unknown, Detail="Exception was thrown by handler.")
at GrpcGreeterClient.Program.Main(String[] args) in /home/kanda/csharp/GrpcGreeterClient/Program.cs:line 25
at GrpcGreeterClient.Program.<Main>(String[] args)
[root@localhost coredump]# lz4cat core.GrpcGreeterClie.1000.f900c677cff146d994a0ecd1a9aabc53.16096.1586916972000000.lz4 >/tmp/core
[root@localhost coredump]# ls -hl /tmp/core
-rw-rw-rw- 1 root root 119M 4月 15 11:20 /tmp/core
> pe -lines
Exception object: 00007f81e4056ca0
Exception type: <Unknown>
Message: Status(StatusCode=Unknown, Detail="Exception was thrown by handler.")
InnerException: <none>
StackTrace (generated):
SP IP Function
00007F820906A780 00007F820A2F218E GrpcGreeterClient.dll!Unknown+0x2fe
00007FFE331856D0 00007F820A2F0B9D GrpcGreeterClient.dll!Unknown+0x5d
> lm
0000000000400000 00215000 /home/kanda/csharp/GrpcGreeterClient/bin/Debug/netcoreapp3.1/GrpcGreeterClient
00007F81E2454000 01BA9000 /usr/lib64/libicudata.so.60.3
00007F8209960000 00000000 /usr/lib64/dotnet/shared/Microsoft.NETCore.App/3.1.1/System.Private.CoreLib.dll
..
> clrthreads
ThreadCount: 8
UnstartedThread: 0
BackgroundThread: 7
PendingThread: 0
DeadThread: 0
Hosted Runtime: no
Lock
DBG ID OSID ThreadOBJ State GC Mode GC Alloc Context Domain Count Apt Exception
0 1 3ee0 00000000013C36E0 20020 Preemptive 00007F81E406FD78:00007F81E406FFD0 000000000133D950 0 Ukn <Invalid Object> (00007f81e4056ca0)
14 2 3ee7 00000000013E7FE0 21220 Preemptive 0000000000000000:0000000000000000 000000000133D950 0 Ukn (Finalizer)
2 3 3ee9 00007F81D8000C50 1020220 Preemptive 0000000000000000:0000000000000000 000000000133D950 0 Ukn (Threadpool Worker)
3 4 3eeb 00007F81D8001C10 1021220 Preemptive 00007F81E4057898:00007F81E4057FD0 000000000133D950 0 Ukn (Threadpool Worker)
9 5 3eef 00007F81D0001990 1021220 Preemptive 00007F81E4061110:00007F81E4061FD0 000000000133D950 0 Ukn (Threadpool Worker)
4 6 3ef0 00007F81D000C2D0 21220 Preemptive 00007F81E40401B8:00007F81E4041FD0 000000000133D950 0 Ukn
6 7 3ef1 00007F81C80018A0 1021220 Preemptive 00007F81E40581E8:00007F81E4059FD0 000000000133D950 0 Ukn (Threadpool Worker)
15 8 3ef2 00007F81C0001510 1021220 Preemptive 00007F81E4050258:00007F81E4051FD0 000000000133D950 0 Ukn (Threadpool Worker)
>
わからん。
Thread.Abort メソッドは、.NET Core ではサポートされていません。
https://docs.microsoft.com/ja-jp/dotnet/standard/threading/destroying-threads
ハードコア デバッギング ~ Windows のアプリケーション運用トラブルシューティング実践
でやったら?
(1684.2f80): Integer divide-by-zero - code c0000094 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
00007ffc`4d945857 f77dfc idiv eax,dword ptr [rbp-4] ss:000000f8`9457e50c=00000000
0:000> .sympath
Symbol search path is: E:\csharp\console\bin\Debug\netcoreapp3.1;srv*
Expanded Symbol search path is: e:\csharp\console\bin\debug\netcoreapp3.1;cache*;SRV*https://msdl.microsoft.com/download/symbols
************* Path validation summary **************
Response Time (ms) Location
OK E:\csharp\console\bin\Debug\netcoreapp3.1
Deferred srv*
0:000> k
# Child-SP RetAddr Call Site
00 000000f8`9457e4d0 00007ffc`4d941051 0x00007ffc`4d945857 # XXX <== おかしい。ここが、うちの関数のはずだが、シンボルが見えない。
01 000000f8`9457e520 00007ffc`ad436b63 0x00007ffc`4d941051
02 000000f8`9457e570 00007ffc`ad3ccb62 coreclr!CallDescrWorkerInternal+0x83 [F:\workspace\_work\1\s\src\vm\amd64\CallDescrWorkerAMD64.asm @ 101]
03 (Inline Function) --------`-------- coreclr!CallDescrWorkerWithHandler+0x57 [f:\workspace\_work\1\s\src\vm\callhelpers.cpp @ 70]
04 000000f8`9457e5b0 00007ffc`ad3d3b29 coreclr!MethodDescCallSite::CallTargetWorker+0x196 [f:\workspace\_work\1\s\src\vm\callhelpers.cpp @ 612]
05 (Inline Function) --------`-------- coreclr!MethodDescCallSite::Call+0xb [f:\workspace\_work\1\s\src\vm\callhelpers.h @ 468]
06 000000f8`9457e6f0 00007ffc`ad3d3fb7 coreclr!RunMain+0x1f5 [f:\workspace\_work\1\s\src\vm\assembly.cpp @ 1558]
07 000000f8`9457e8d0 00007ffc`ad3d4761 coreclr!Assembly::ExecuteMainMethod+0x1cb [f:\workspace\_work\1\s\src\vm\assembly.cpp @ 1681]
08 000000f8`9457ec70 00007ffc`ad2f21c1 coreclr!CorHost2::ExecuteAssembly+0x221 [f:\workspace\_work\1\s\src\vm\corhost.cpp @ 460]
09 000000f8`9457ee00 00007ffc`dbeb4e2d coreclr!coreclr_execute_assembly+0x101 [f:\workspace\_work\1\s\src\dlls\mscoree\unixinterface.cpp @ 412]
0a 000000f8`9457eea0 00007ffc`dbec2e27 hostpolicy!coreclr_t::execute_assembly+0x2d [f:\workspace\_work\1\s\src\corehost\cli\hostpolicy\coreclr.cpp @ 152]
0b 000000f8`9457eef0 00007ffc`dbec2a36 hostpolicy!run_app_for_context+0x387 [f:\workspace\_work\1\s\src\corehost\cli\hostpolicy\hostpolicy.cpp @ 247]
0c 000000f8`9457f050 00007ffc`dbec4262 hostpolicy!run_app+0x46 [f:\workspace\_work\1\s\src\corehost\cli\hostpolicy\hostpolicy.cpp @ 276]
0d 000000f8`9457f0a0 00007ffc`dbf70653 hostpolicy!corehost_main+0x132 [f:\workspace\_work\1\s\src\corehost\cli\hostpolicy\hostpolicy.cpp @ 390]
0e 000000f8`9457f250 00007ffc`dbf737c8 hostfxr!execute_app+0x2e3 [f:\workspace\_work\1\s\src\corehost\cli\fxr\fx_muxer.cpp @ 146]
0f 000000f8`9457f340 00007ffc`dbf727cd hostfxr!`anonymous namespace'::read_config_and_execute+0xa8 [f:\workspace\_work\1\s\src\corehost\cli\fxr\fx_muxer.cpp @ 502]
10 000000f8`9457f450 00007ffc`dbf7027c hostfxr!fx_muxer_t::handle_exec_host_command+0x15d [f:\workspace\_work\1\s\src\corehost\cli\fxr\fx_muxer.cpp @ 952]
11 000000f8`9457f4e0 00007ffc`dbf6bd0c hostfxr!fx_muxer_t::execute+0x1fc [f:\workspace\_work\1\s\src\corehost\cli\fxr\fx_muxer.cpp @ 541]
*** WARNING: Unable to verify checksum for apphost.exe
12 000000f8`9457f630 00007ff6`2a601b01 hostfxr!hostfxr_main_startupinfo+0x9c [f:\workspace\_work\1\s\src\corehost\cli\fxr\hostfxr.cpp @ 33]
13 000000f8`9457f730 00007ff6`2a601ef8 apphost!exe_start+0x651 [f:\workspace\_work\1\s\src\corehost\corehost.cpp @ 220]
14 000000f8`9457f960 00007ff6`2a603da8 apphost!wmain+0x88 [f:\workspace\_work\1\s\src\corehost\corehost.cpp @ 287]
15 (Inline Function) --------`-------- apphost!invoke_main+0x22 [d:\agent\_work\2\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl @ 90]
16 000000f8`9457f990 00007ffc`e52e7bd4 apphost!__scrt_common_main_seh+0x10c [d:\agent\_work\2\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl @ 288]
17 000000f8`9457f9d0 00007ffc`e6a2ced1 KERNEL32!BaseThreadInitThunk+0x14
18 000000f8`9457fa00 00000000`00000000 ntdll!RtlUserThreadStart+0x21
マネッジドコードを Windbg でデバッグするには、 sos.dll を読み込ませろと書いてある。
C:\Users\kanda_000>dotnet tool install -g dotnet-dump
次のコマンドを使用してツールを呼び出せます。dotnet-dump
ツール 'dotnet-dump' (バージョン '3.1.120604') が正常にインストールされました。
0:000> .load C:\Users\kanda_000\.dotnet\tools\.store\dotnet-dump\3.1.120604\dotnet-dump\3.1.120604\tools\netcoreapp2.1\any\win-x64\sos.dll
0:000> !chain
Extension DLL chain:
C:\Users\kanda_000\.dotnet\tools\.store\dotnet-dump\3.1.120604\dotnet-dump\3.1.120604\tools\netcoreapp2.1\any\win-x64\sos.dll: image 3.1.120604+97218bff6a14e60360862529b09b687789cc1279, API 2.0.0, built Tue Apr 7 12:06:44 2020
[path: C:\Users\kanda_000\.dotnet\tools\.store\dotnet-dump\3.1.120604\dotnet-dump\3.1.120604\tools\netcoreapp2.1\any\win-x64\sos.dll]
同じだ。
0:000> k
# Child-SP RetAddr Call Site
00 000000f8`9457e4d0 00007ffc`4d941051 0x00007ffc`4d945857
マネッジドコードをデバッグするには、 sos が必要で、 linux 環境では、 lldb デバッガでサポートされるそうな。
https://github.com/dotnet/diagnostics/blob/master/documentation/sos.md
# dnf install lldb
https://github.com/dotnet/diagnostics/blob/master/documentation/installing-sos-instructions.md
に従う。
[kanda@localhost ~]$ dotnet tool install -g dotnet-sos
次のコマンドを使用してツールを呼び出せます。dotnet-sos
ツール 'dotnet-sos' (バージョン '3.1.120604') が正常にインストールされました。
[kanda@localhost ~]$ dotnet-sos install
Installing SOS to /home/kanda/.dotnet/sos from /home/kanda/.dotnet/tools/.store/dotnet-sos/3.1.120604/dotnet-sos/3.1.120604/tools/netcoreapp2.1/any/linux-x64
Creating installation directory...
Copying files...
Creating new /home/kanda/.lldbinit file - LLDB will load SOS automatically at startup
SOS install succeeded
[kanda@localhost ~]$ lldb
(lldb) soshelp
-------------------------------------------------------------------------------
SOS is a debugger extension DLL designed to aid in the debugging of managed
programs. Functions are listed by category, then roughly in order of
importance. Shortcut names for popular functions are listed in parenthesis.
Type "soshelp <functionname>" for detailed info on that function.
Object Inspection Examining code and stacks
----------------------------- -----------------------------
DumpObj (dumpobj) Threads (clrthreads)
。。
[kanda@localhost netcoreapp3.1]$ lldb console
(lldb) target create "console"
Current executable set to 'console' (x86_64).
(lldb) run
Process 7165 launched: '/home/kanda/csharp/console/bin/Debug/netcoreapp3.1/console' (x86_64)
warning: (x86_64) /usr/lib64/dotnet/shared/Microsoft.NETCore.App/3.1.1/System.Native.so unsupported DW_FORM values: 0x1f20 0x1f21
Hello World!
Process 7165 stopped
* thread #1, name = 'console', stop reason = signal SIGFPE: integer divide by zero
frame #0: 0x00007fff7cd16dbd
-> 0x7fff7cd16dbd: idivl -0xc(%rbp)
0x7fff7cd16dc0: movl %eax, -0xc(%rbp)
0x7fff7cd16dc3: movabsq $0x7fff68001410, %rax ; imm = 0x7FFF68001410
0x7fff7cd16dcd: movq (%rax), %rax
これが求めるものだった。
(lldb) clrstack
OS Thread Id: 0x1bfd (1)
Child SP IP Call Site
00007FFFFFFFC5B0 00007FFF7CD16DBD console.YourClass.Greeting() [/home/kanda/csharp/classlib/Class1.cs @ 9]
00007FFFFFFFC5E0 00007FFF7CD10527 Program.Main(System.String[]) [/home/kanda/csharp/console/Program.cs @ 8]
00007FFFFFFFC8E8 00007ffff60fa5ff [GCFrame: 00007fffffffc8e8]
00007FFFFFFFCDE0 00007ffff60fa5ff [GCFrame: 00007fffffffcde0]
(lldb) help clrstack
Provides a stack trace of managed code only.
Syntax: clrstack
(lldb) clrthreads
ThreadCount: 4
UnstartedThread: 0
BackgroundThread: 3
PendingThread: 0
DeadThread: 0
Hosted Runtime: no
Lock
DBG ID OSID ThreadOBJ State GC Mode GC Alloc Context Domain Count Apt Exception
1 1 1bfd 00000000006F54D0 20020 Cooperative 00007FFF58017E78:00007FFF58018730 000000000066F740 0 Ukn
7 2 1c95 0000000000719970 21220 Preemptive 0000000000000000:0000000000000000 000000000066F740 0 Ukn (Finalizer)
9 3 1c97 00007FFF48000C50 1020220 Preemptive 0000000000000000:0000000000000000 000000000066F740 0 Ukn (Threadpool Worker)
10 4 1c98 00007FFF48001C10 1021220 Preemptive 0000000000000000:0000000000000000 000000000066F740 0 Ukn (Threadpool Worker)
(lldb) dumpstack
OS Thread Id: 0x1bfd (1)
TEB information is not available so a stack size of 0xFFFF is assumed
Current frame: (MethodDesc 00007fff7ce707e8 + 0x4d console.YourClass.Greeting())
Child-SP RetAddr Caller, Callee
00007FFFFFFFC5D0 00007fff7cd10527 (MethodDesc 00007fff7ce00340 + 0x77 Program.Main(System.String[])), calling 00007fff7cd0f6e0 (stub for console.YourClass.Greeting())
00007FFFFFFFC610 00007ffff60fa5ff libcoreclr.so!CallDescrWorkerInternal + 0x7c
00007FFFFFFFC630 00007ffff6026eb1 libcoreclr.so!MethodDescCallSite::CallTargetWorker(unsigned long const*, unsigned long*, int) + 0x5c1, calling libcoreclr.so!CallDescrWorkerInternal
00007FFFFFFFC650 00007ffff6319fea libcoreclr.so!HeapFree + 0x3a, calling libcoreclr.so!PAL_free
00007FFFFFFFC670 00007ffff605d591 libcoreclr.so!EEHeapFreeInProcessHeap(unsigned int, void*) + 0x31, calling libcoreclr.so!HeapFree
00007FFFFFFFC690 00007ffff628e3fc libcoreclr.so!MDInternalRO::GetSigOfMethodDef(unsigned int, unsigned int*, unsigned char const**) + 0x7c, calling libcoreclr.so!StgBlobPoolReadOnly::GetBlob(unsigned int, MetaData::DataBlob*)
00007FFFFFFFC6D0 00007ffff5fdc4db libcoreclr.so!MetaSig::Init(unsigned char const*, unsigned int, Module*, SigTypeContext const*, MetaSig::MetaSigKind) + 0x2ab, calling libcoreclr.so!SigParser::SkipExactlyOne()
00007FFFFFFFC700 00007ffff5fdc78d libcoreclr.so!MetaSig::MetaSig(MethodDesc*, TypeHandle) + 0xed, calling libcoreclr.so!MethodDesc::RequiresInstArg()
00007FFFFFFFC810 00007ffff610fa66 libcoreclr.so!RunMain(MethodDesc*, short, int*, PtrArray**) + 0x316, calling libcoreclr.so!MethodDescCallSite::CallTargetWorker(unsigned long const*, unsigned long*, int)
00007FFFFFFFCA30 00007ffff610fdd9 libcoreclr.so!Assembly::ExecuteMainMethod(PtrArray**, int) + 0x189, calling libcoreclr.so!RunMain(MethodDesc*, short, int*, PtrArray**)
00007FFFFFFFCA90 00007ffff5f4ab14 libcoreclr.so!REGUTIL::EnvGetString(char16_t const*, int) + 0x1b4, calling libcoreclr.so!GetEnvironmentVariableWrapper(char16_t const*, SString&)
00007FFFFFFFCC80 00007ffff5f4af16 libcoreclr.so!REGUTIL::GetConfigDWORD_DontUse_(char16_t const*, unsigned int, unsigned int*, REGUTIL::CORConfigLevel, int) + 0x36, calling libcoreclr.so!REGUTIL::EnvGetString(char16_t const*, int)
00007FFFFFFFCCD0 00007ffff5f49d96 libcoreclr.so!CLRConfig::GetConfigValue(CLRConfig::ConfigDWORDInfo const&, bool, bool*) + 0x66, calling libcoreclr.so!REGUTIL::GetConfigDWORD_DontUse_(char16_t const*, unsigned int, unsigned int*, REGUTIL::CORConfigLevel, int)
00007FFFFFFFCD50 00007ffff5f6f1f2 libcoreclr.so!CorHost2::ExecuteAssembly(unsigned int, char16_t const*, int, char16_t const**, unsigned int*) + 0x242, calling libcoreclr.so!Assembly::ExecuteMainMethod(PtrArray**, int)
00007FFFFFFFCE40 00007ffff5f46903 libcoreclr.so!coreclr_execute_assembly + 0xf3
00007FFFFFFFCEA0 00007ffff682715c libhostpolicy.so!run_app_for_context(hostpolicy_context_t const&, int, char const**) + 0x44c, calling libhostpolicy.so!coreclr_t::execute_assembly(int, char const**, char const*, unsigned int*)
00007FFFFFFFCF70 00007ffff68274ee libhostpolicy.so!run_app(int, char const**) + 0x3e, calling libhostpolicy.so!run_app_for_context(hostpolicy_context_t const&, int, char const**)
00007FFFFFFFCFB0 00007ffff6827cfc libhostpolicy.so!corehost_main + 0xec, calling libhostpolicy.so!run_app(int, char const**)
00007FFFFFFFD040 00007ffff6a866de libhostfxr.so!。。
00007FFFFFFFD270 00007ffff6a8ac73 libhostfxr.so!。。
00007FFFFFFFD320 00007ffff6d43937 libc.so.6!__GI___libc_malloc + 0x97 [/usr/src/debug/glibc-2.28/malloc/malloc.c:3065], calling libc.so.6!_int_malloc [/usr/src/debug/glibc-2.28/malloc/malloc.c:3529]
00007FFFFFFFD360 00007ffff6a73b5c libhostfxr.so!host_startup_info_t::host_startup_info_t(char const*, char const*, char const*) + 0x14c, calling libhostfxr.so!memcpy
00007FFFFFFFD3A0 00007ffff6a86d91 libhostfxr.so!hostfxr_main_startupinfo + 0xa1, calling libhostfxr.so!fx_muxer_t::execute(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, char const**, host_startup_info_t const&, char*, int, int*)
00007FFFFFFFD470 000000000040eba6 console!___lldb_unnamed_symbol137$$console + 0x306
00007FFFFFFFD520 000000000040f1fe console!___lldb_unnamed_symbol138$$console + 0x8e, calling console!___lldb_unnamed_symbol137$$console
00007FFFFFFFD550 00007ffff6ce1873 libc.so.6!.annobin_libc_start.c + 0xf3 [/usr/src/debug/glibc-2.28/csu/libc-start.c:342]
00007FFFFFFFD5E0 00007ffff7de3e0a ld-2.28.so!_dl_init + 0x7a [/usr/src/debug/glibc-2.28/elf/dl-init.c:118], calling ld-2.28.so!.annobin_dl_init.c [/usr/src/debug/glibc-2.28/elf/dl-init.c:36]
00007FFFFFFFD610 0000000000403550 console!_start + 0x29, calling console!__libc_start_main
(lldb)
コアだけを与える。
[kanda@localhost ~]$ lldb --core /tmp/core
(lldb) target create --core "/tmp/core"
Core file '/tmp/core' (x86_64) was loaded.
(lldb) clrstack
OS Thread Id: 0x1d8f (1)
Child SP IP Call Site
00007FFF7F11DCC0 00007f74132728df [FaultingExceptionFrame: 00007fff7f11dcc0]
00007FFF7F11F010 00007F7399286DBD /home/kanda/csharp/console/bin/Debug/netcoreapp3.1/classlib.dll!Unknown XXX シンボルが見えない。
00007FFF7F11F040 00007F7399280527 /home/kanda/csharp/console/bin/Debug/netcoreapp3.1/console.dll!Unknown
elf ファイルを与えても、シンボルは見えない。 pdb を拾うしかけが無いのか。llvm のメーリングリストを見ると、そうみたい。
[kanda@localhost netcoreapp3.1]$ lldb --file console --core /tmp/core
(lldb) target create "console" --core "/tmp/core"
(lldb) clrstack
OS Thread Id: 0x1d8f (1)
Child SP IP Call Site
00007FFF7F11DCC0 00007f74132728df [FaultingExceptionFrame: 00007fff7f11dcc0]
00007FFF7F11F010 00007F7399286DBD /home/kanda/csharp/console/bin/Debug/netcoreapp3.1/classlib.dll!Unknown
setsymbolserver -directory
しても、だめだった。
PS /home/kanda> Invoke-WebRequest https://www.powershellgallery.com/api/v2
* thread #22, name = 'pwsh', stop reason = breakpoint 1.1
frame #0: 0x00007f528becfd00 libpthread.so.0`__libc_connect(fd=108, addr=__CONST_SOCKADDR_ARG @ rsi, len=16) at connect.c:24:1
21
22 int
23 __libc_connect (int fd, __CONST_SOCKADDR_ARG addr, socklen_t len)
-> 24 {
25 #ifdef __ASSUME_CONNECT_SYSCALL
26 return SYSCALL_CANCEL (connect, fd, addr.__sockaddr__, len);
27 #else
(lldb) bt
* thread #22, name = 'pwsh', stop reason = breakpoint 1.1
* frame #0: 0x00007f528becfd00 libpthread.so.0`__libc_connect(fd=108, addr=__CONST_SOCKADDR_ARG @ rsi, len=16) at connect.c:24:1
frame #1: 0x00007f528802da0d System.Native.so`SystemNative_Connect + 45
frame #2: 0x00007f52164e0953
frame #3: 0x00007f521570563a
frame #4: 0x00007f5215704009
frame #5: 0x00007f5215703f7d
frame #6: 0x00007f5215703ce2
frame #7: 0x00007f52157038f4
frame #8: 0x00007f521570375c
frame #9: 0x00007f52157034d4
frame #10: 0x00007f5215703373
frame #11: 0x00007f521544adfe
frame #12: 0x00007f521544ad53
frame #13: 0x00007f521544ad19
frame #14: 0x00007f5210cceac0
frame #15: 0x00007f521544ac13
frame #16: 0x00007f521544aaec
frame #17: 0x00007f521544a231
frame #18: 0x00007f521544a1ce
frame #19: 0x00007f5210cea192
frame #20: 0x00007f5210cced32
frame #21: 0x00007f5210ce4611
frame #22: 0x00007f5210ce4428
frame #23: 0x00007f5210ce43bb
frame #24: 0x00007f5210cc6b8b
frame #25: 0x00007f528a508135 libcoreclr.so`CallDescrWorkerWithHandler(CallDescrData*, int) + 117
frame #26: 0x00007f528a508c10 libcoreclr.so`MethodDescCallSite::CallTargetWorker(unsigned long const*, unsigned long*, int) + 1264
frame #27: 0x00007f528a6521da libcoreclr.so`QueueUserWorkItemManagedCallback(void*) + 74
frame #28: 0x00007f528a4da3d5 libcoreclr.so`ManagedThreadBase_DispatchOuter(ManagedThreadCallState*) + 341
frame #29: 0x00007f528a4daa3d libcoreclr.so`ManagedThreadBase::ThreadPool(void (*)(void*), void*) + 45
frame #30: 0x00007f528a63dbde libcoreclr.so`ManagedPerAppDomainTPCount::DispatchWorkItem(bool*, bool*) + 270
frame #31: 0x00007f528a4f9689 libcoreclr.so`ThreadpoolMgr::WorkerThreadStart(void*) + 1241
frame #32: 0x00007f528a80bb7d libcoreclr.so`CorUnix::CPalThread::ThreadEntry(void*) + 349
frame #33: 0x00007f528bec62de libpthread.so.0`start_thread(arg=<unavailable>) at pthread_create.c:486:8
frame #34: 0x00007f528b0c4133 libc.so.6`__GI___clone at clone.S:95
(lldb)
(lldb) clrstack
OS Thread Id: 0x2907 (22)
Child SP IP Call Site
00007F52811AD3C0 00007f528becfd00 [InlinedCallFrame: 00007f52811ad3c0] Interop+Sys.Connect(System.Runtime.InteropServices.SafeHandle, Byte*, Int32)
00007F52811AD3C0 00007f52164e0953 [InlinedCallFrame: 00007f52811ad3c0] Interop+Sys.Connect(System.Runtime.InteropServices.SafeHandle, Byte*, Int32)
00007F52811AD3B0 00007F52164E0953 ILStubClass.IL_STUB_PInvoke(System.Runtime.InteropServices.SafeHandle, Byte*, Int32)
00007F52811AD450 00007F521570563A System.Net.Sockets.SocketPal.TryStartConnect(System.Net.Sockets.SafeSocketHandle, Byte[], Int32, System.Net.Sockets.SocketError ByRef) [/_/src/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs @ 524]
00007F52811AD470 00007F5215704009 System.Net.Sockets.SocketAsyncContext.ConnectAsync(Byte[], Int32, System.Action`1<System.Net.Sockets.SocketError>) [/_/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncContext.Unix.cs @ 1398]
00007F52811AD4C0 00007F5215703F7D System.Net.Sockets.SocketAsyncEventArgs.DoOperationConnect(System.Net.Sockets.Socket, System.Net.Sockets.SafeSocketHandle) [/_/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Unix.cs @ 100]
00007F52811AD500 00007F5215703CE2 System.Net.Sockets.Socket.ConnectAsync(System.Net.Sockets.SocketAsyncEventArgs, Boolean) [/_/src/System.Net.Sockets/src/System/Net/Sockets/Socket.cs @ 3883]
00007F52811AD550 00007F52157038F4 System.Net.Sockets.MultipleConnectAsync.AttemptConnection(System.Net.Sockets.Socket, System.Net.Sockets.SocketAsyncEventArgs) [/_/src/System.Net.Sockets/src/System/Net/Sockets/MultipleConnectAsync.cs @ 264]
00007F52811AD590 00007F521570375C System.Net.Sockets.MultipleConnectAsync.AttemptConnection() [/_/src/System.Net.Sockets/src/System/Net/Sockets/MultipleConnectAsync.cs @ 243]
00007F52811AD5E0 00007F52157034D4 System.Net.Sockets.MultipleConnectAsync.DoDnsCallback(System.IAsyncResult, Boolean) [/_/src/System.Net.Sockets/src/System/Net/Sockets/MultipleConnectAsync.cs @ 132]
00007F52811AD640 00007F5215703373 System.Net.Sockets.MultipleConnectAsync.DnsCallback(System.IAsyncResult) [/_/src/System.Net.Sockets/src/System/Net/Sockets/MultipleConnectAsync.cs @ 84]
00007F52811AD660 00007F521544ADFE System.Net.LazyAsyncResult.Complete(IntPtr) [/_/src/Common/src/System/Net/LazyAsyncResult.cs @ 397]
00007F52811AD6B0 00007F521544AD53 System.Net.ContextAwareResult.CompleteCallback() [/_/src/Common/src/System/Net/ContextAwareResult.cs @ 394]
00007F52811AD6D0 00007F521544AD19 System.Net.ContextAwareResult+<>c.<Complete>b__15_0(System.Object) [/_/src/Common/src/System/Net/ContextAwareResult.cs @ 388]
00007F52811AD6E0 00007F5210CCEB51 System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object) [/_/src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs @ 172]
00007F52811AD730 00007F5210CCEAC0 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object) [/_/src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs @ 131]
00007F52811AD740 00007F521544AC13 System.Net.ContextAwareResult.Complete(IntPtr) [/_/src/Common/src/System/Net/ContextAwareResult.cs @ 388]
00007F52811AD770 00007F521544AAEC System.Net.LazyAsyncResult.ProtectedInvokeCallback(System.Object, IntPtr) [/_/src/Common/src/System/Net/LazyAsyncResult.cs @ 351]
00007F52811AD7B0 00007F521544A231 System.Net.Dns.ResolveCallback(System.Object) [/_/src/System.Net.NameResolution/src/System/Net/DNS.cs @ 231]
00007F52811AD7D0 00007F521544A1CE System.Net.Dns+<>c.<HostResolutionBeginHelper>b__10_0(System.Object) [/_/src/System.Net.NameResolution/src/System/Net/DNS.cs @ 285]
00007F52811AD7E0 00007F5210CE47C3 System.Threading.Tasks.Task.InnerInvoke() [/_/src/System.Private.CoreLib/shared/System/Threading/Tasks/Task.cs @ 2445]
00007F52811AD800 00007F5210CEA192 System.Threading.Tasks.Task+<>c.<.cctor>b__274_0(System.Object) [/_/src/System.Private.CoreLib/shared/System/Threading/Tasks/Task.cs @ 2427]
00007F52811AD810 00007F5210CCED32 System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(System.Threading.Thread, System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object) [/_/src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs @ 289]
00007F52811AD850 00007F5210CE4611 System.Threading.Tasks.Task.ExecuteWithThreadLocal(System.Threading.Tasks.Task ByRef, System.Threading.Thread) [/_/src/System.Private.CoreLib/shared/System/Threading/Tasks/Task.cs @ 2389]
00007F52811AD8D0 00007F5210CE4428 System.Threading.Tasks.Task.ExecuteEntryUnsafe(System.Threading.Thread) [/_/src/System.Private.CoreLib/shared/System/Threading/Tasks/Task.cs @ 2321]
00007F52811AD8F0 00007F5210CE43BB System.Threading.Tasks.Task.ExecuteFromThreadPool(System.Threading.Thread) [/_/src/System.Private.CoreLib/shared/System/Threading/Tasks/Task.cs @ 2312]
00007F52811AD900 00007F5210CD8B64 System.Threading.ThreadPoolWorkQueue.Dispatch() [/_/src/System.Private.CoreLib/shared/System/Threading/ThreadPool.cs @ 663]
00007F52811AD980 00007F5210CC6B8B System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() [/_/src/System.Private.CoreLib/src/System/Threading/ThreadPool.CoreCLR.cs @ 29]
00007F52811ADD30 00007f528a5d7d9f [DebuggerU2MCatchHandlerFrame: 00007f52811add30]
(lldb)
C:\Users\kanda_000>dotnet tool install -g dotnet-sos
次のコマンドを使用してツールを呼び出せます。dotnet-sos
ツール 'dotnet-sos' (バージョン '3.1.120604') が正常にインストールされました。
C:\Users\kanda_000>dotnet-sos install
Installing SOS to C:\Users\kanda_000\.dotnet\sos from C:\Users\kanda_000\.dotnet\tools\.store\dotnet-sos\3.1.120604\dotnet-sos\3.1.120604\tools\netcoreapp2.1\any\win-x64
Creating installation directory...
Copying files...
Execute '.load C:\Users\kanda_000\.dotnet\sos\sos.dll' to load SOS in your Windows debugger.
SOS install succeeded
0:000> .sympath
Symbol search path is: srv*;C:\Users\kanda_000\crash\crash\bin\Debug
Expanded Symbol search path is: cache*;SRV*https://msdl.microsoft.com/download/symbols;c:\users\kanda_000\crash\crash\bin\debug
************* Path validation summary **************
Response Time (ms) Location
Deferred srv*
OK C:\Users\kanda_000\crash\crash\bin\Debug
0:000> .load C:\Users\kanda_000\.dotnet\sos\sos.dll
(176c.2b54): Integer divide-by-zero - code c0000094 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
02a20890 f77df8 idiv eax,dword ptr [ebp-8] ss:002b:00d5f250=00000000
0:000:x86> k
# ChildEBP RetAddr
WARNING: Frame IP not in any known module. Following frames may be wrong.
00 00d5f258 731ff066 0x2a20890 # XXX シンボルが見えないのは同じ。
01 00d5f264 7320231a clr!CallDescrWorkerInternal+0x34
02 00d5f2b8 732085bb clr!CallDescrWorkerWithHandler+0x6b
03 00d5f320 733ab10b clr!MethodDescCallSite::CallTargetWorker+0x16a
04 00d5f444 733ab7ea clr!RunMain+0x1b3
05 00d5f6b0 733ab717 clr!Assembly::ExecuteMainMethod+0xf7
06 00d5fb94 733ab898 clr!SystemDomain::ExecuteMainMethod+0x5ef
07 00d5fbec 733ab9be clr!ExecuteEXE+0x4c
08 00d5fc2c 733a72e5 clr!_CorExeMainInternal+0xdc
09 00d5fc68 739bfa84 clr!_CorExeMain+0x4d
0a 00d5fca0 73a4e80e mscoreei!_CorExeMain+0xd6
0b 00d5fcb0 73a54338 MSCOREE!ShellShim__CorExeMain+0x9e
0c 00d5fcb8 75956359 MSCOREE!_CorExeMain_Exported+0x8
0d 00d5fcc8 778a7c14 KERNEL32!BaseThreadInitThunk+0x19
0e 00d5fd24 778a7be4 ntdll_77840000!__RtlUserThreadStart+0x2f
0f 00d5fd34 00000000 ntdll_77840000!_RtlUserThreadStart+0x1b
でも、見えているスタックが、 sos を使わない時と違う。