diff --git a/README.md b/README.md index 291fbb5..4634aab 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,33 @@ # Haiku-riscv Haiku port to RISC-V architecture -Latest version: revision 2. +Latest version: revision 3. -Source code is located at https://github.com/X547/haiku/tree/riscv. +[HiFive Unmatched](https://www.sifive.com/boards/hifive-unmatched) board is supported. Radeon graphics card is required for booting to desktop, text mode is not supported. + +Booting instructions for HiFive Unmatched: + +1. Connect USB keyboard and mouse. + +2. Write release image to USB drive. USB 3 drive is recomended. + +3. Connect board to UEFI terminal. + +4. Start board and press any key on UART terminal to stop boot process. + +5. Type following commands in UART u-boot promt: `pci enum ; usb start ; run bootcmd_usb0`. + +6. When Haiku boot loader menu appear on UART terminal (not on screen) hit Enter key 3 times. + +7. Boot process whould start and eventually desktop will be loaded. + + +Patchset is provided. Exact Haiku version should be used when appliying patchset. ![](https://raw.githubusercontent.com/X547/Haiku-riscv/main/screenshot.png) -Detail disscussion: https://discuss.haiku-os.org/t/my-haiku-risc-v-port-progress/10663. +Detail disscussion: + +* https://discuss.haiku-os.org/t/my-haiku-risc-v-port-progress/10663 + +* https://discuss.haiku-os.org/t/my-progress-on-real-risc-v-hardware/10963 diff --git a/patchset-hrev55144/0001-app_server-WIP-fix-alpha-mask-clipping.patch b/patchset-hrev55144/0001-app_server-WIP-fix-alpha-mask-clipping.patch new file mode 100644 index 0000000..74bf381 --- /dev/null +++ b/patchset-hrev55144/0001-app_server-WIP-fix-alpha-mask-clipping.patch @@ -0,0 +1,34 @@ +From 277c776e3b3e082bd3302bb0ce484f12487da262 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 29 Nov 2020 20:29:27 +0900 +Subject: app_server: [WIP] fix alpha mask clipping + +Change-Id: Iad1e0f3c59b04ef92049d0992a45d18215a63c09 +--- + src/servers/app/drawing/AlphaMask.cpp | 4 ++++ + 1 file changed, 4 insertions(+) + +diff --git a/src/servers/app/drawing/AlphaMask.cpp b/src/servers/app/drawing/AlphaMask.cpp +index 78b1708e6a..caecce27c4 100644 +--- a/src/servers/app/drawing/AlphaMask.cpp ++++ b/src/servers/app/drawing/AlphaMask.cpp +@@ -320,12 +320,16 @@ VectorAlphaMask::_RenderSource(const IntRect& canvasBounds) + { + fBounds = static_cast(this)->DetermineBoundingBox(); + ++#if 0 + if (fBounds.Width() > canvasBounds.Width() + || fBounds.Height() > canvasBounds.Height()) { + fBounds = fBounds & canvasBounds; + fClippedToCanvas = true; + } else + fClippedToCanvas = false; ++#else ++ fClippedToCanvas = false; ++#endif + + if (fPreviousMask != NULL) + fBounds = fBounds & _PreviousMaskBounds(); +-- +2.30.2 + diff --git a/patchset-hrev55144/0002-libbe_test-add-more-applications.patch b/patchset-hrev55144/0002-libbe_test-add-more-applications.patch new file mode 100644 index 0000000..97ce892 --- /dev/null +++ b/patchset-hrev55144/0002-libbe_test-add-more-applications.patch @@ -0,0 +1,82 @@ +From add8607e00fbfafc368f3d556495db57cfb91f88 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 29 Nov 2020 18:40:09 +0900 +Subject: libbe_test: add more applications + +Change-Id: I0fdb73bc2c069bf1748eec99f4c2c483e6dbb68e +--- + src/apps/deskbar/Jamfile | 2 ++ + src/apps/launchbox/Jamfile | 4 +++- + src/apps/mediaplayer/Jamfile | 2 ++ + src/apps/processcontroller/Jamfile | 4 +++- + 4 files changed, 10 insertions(+), 2 deletions(-) + +diff --git a/src/apps/deskbar/Jamfile b/src/apps/deskbar/Jamfile +index 5f97856b81..802f5d3120 100644 +--- a/src/apps/deskbar/Jamfile ++++ b/src/apps/deskbar/Jamfile +@@ -1,5 +1,7 @@ + SubDir HAIKU_TOP src apps deskbar ; + ++AddSubDirSupportedPlatforms libbe_test ; ++ + UsePrivateHeaders app interface locale shared tracker ; + UsePrivateHeaders private shared ; + SubDirHdrs $(HAIKU_TOP) src kits tracker ; +diff --git a/src/apps/launchbox/Jamfile b/src/apps/launchbox/Jamfile +index 850d9d2bfe..68658b70b8 100644 +--- a/src/apps/launchbox/Jamfile ++++ b/src/apps/launchbox/Jamfile +@@ -1,5 +1,7 @@ + SubDir HAIKU_TOP src apps launchbox ; + ++AddSubDirSupportedPlatforms libbe_test ; ++ + UsePrivateHeaders shared ; + + Application LaunchBox : +@@ -11,7 +13,7 @@ Application LaunchBox : + PadView.cpp + Panel.cpp + support.cpp +- : be translation shared [ TargetLibsupc++ ] localestub ++ : be translation shared [ TargetLibstdc++ ] [ TargetLibsupc++ ] localestub + : LaunchBox.rdef + ; + +diff --git a/src/apps/mediaplayer/Jamfile b/src/apps/mediaplayer/Jamfile +index bba251d3d2..07ea5ff9fa 100644 +--- a/src/apps/mediaplayer/Jamfile ++++ b/src/apps/mediaplayer/Jamfile +@@ -1,5 +1,7 @@ + SubDir HAIKU_TOP src apps mediaplayer ; + ++AddSubDirSupportedPlatforms libbe_test ; ++ + # for BRecentItems + UsePublicHeaders [ FDirName be_apps Tracker ] ; + UsePrivateHeaders interface shared ; +diff --git a/src/apps/processcontroller/Jamfile b/src/apps/processcontroller/Jamfile +index a189b088cb..8d98329a5d 100644 +--- a/src/apps/processcontroller/Jamfile ++++ b/src/apps/processcontroller/Jamfile +@@ -1,5 +1,7 @@ + SubDir HAIKU_TOP src apps processcontroller ; + ++SetSubDirSupportedPlatforms libbe_test ; ++ + UsePrivateSystemHeaders ; + UsePrivateHeaders app interface shared ; + +@@ -21,7 +23,7 @@ Application ProcessController : + ThreadBarMenu.cpp + ThreadBarMenuItem.cpp + Utilities.cpp +- : be shared [ TargetLibsupc++ ] localestub ++ : be shared [ TargetLibstdc++ ] [ TargetLibsupc++ ] localestub + : ProcessController.rdef + ; + +-- +2.30.2 + diff --git a/patchset-hrev55144/0003-DriveSetup-Add-creating-virtual-disk-and-RAM-disk-su.patch b/patchset-hrev55144/0003-DriveSetup-Add-creating-virtual-disk-and-RAM-disk-su.patch new file mode 100644 index 0000000..62cd2ff --- /dev/null +++ b/patchset-hrev55144/0003-DriveSetup-Add-creating-virtual-disk-and-RAM-disk-su.patch @@ -0,0 +1,297 @@ +From f339a452a148ad7c2c520dc0dd9602cf3eda7907 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Tue, 18 Feb 2020 05:35:52 +0900 +Subject: DriveSetup: Add creating virtual disk and RAM disk support + +TODO: +* Implement path, size dialog for RAM disk. +* Implement file choose dialog for virtual disk. +* Implement eject. + +Add functionality of "diskimage" and "ramdisk" command line utilities to +DriveSetup. + +Virtual and RAM disks can be created by Disk > Create virtual/RAM disk menu. + +Disk can be detached by Disk > Eject menu. + +Change-Id: I0010428de0357b55617d51c89941f7a85daf50c0 +--- + src/apps/drivesetup/CreateRamDiskPanel.cpp | 66 +++++++++++++++++++++ + src/apps/drivesetup/CreateRamDiskPanel.h | 27 +++++++++ + src/apps/drivesetup/Jamfile | 1 + + src/apps/drivesetup/MainWindow.cpp | 69 ++++++++++++++++++++++ + src/apps/drivesetup/MainWindow.h | 5 ++ + 5 files changed, 168 insertions(+) + create mode 100644 src/apps/drivesetup/CreateRamDiskPanel.cpp + create mode 100644 src/apps/drivesetup/CreateRamDiskPanel.h + +diff --git a/src/apps/drivesetup/CreateRamDiskPanel.cpp b/src/apps/drivesetup/CreateRamDiskPanel.cpp +new file mode 100644 +index 0000000000..6cc0e2bd91 +--- /dev/null ++++ b/src/apps/drivesetup/CreateRamDiskPanel.cpp +@@ -0,0 +1,66 @@ ++/* ++ * Copyright 2020 Haiku, Inc. All rights reserved. ++ * Distributed under the terms of the MIT license. ++ */ ++ ++ ++#include "CreateRamDiskPanel.h" ++ ++#include ++#include ++#include ++#include ++#include ++ ++ ++#undef B_TRANSLATION_CONTEXT ++#define B_TRANSLATION_CONTEXT "CreateRamDiskPanel" ++ ++ ++static const uint32 kMsgOk = 'okok'; ++ ++ ++CreateRamDiskPanel::CreateRamDiskPanel(BWindow* window) ++ : ++ BWindow(BRect(300.0, 200.0, 600.0, 300.0), "Create RAM disk", B_TITLED_WINDOW, ++ B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS) ++{ ++ fPathControl = new BTextControl("Path", B_TRANSLATE("Mount point:"), "", NULL); ++ fSizeControl = new BTextControl("Size", B_TRANSLATE("Size:"), "", NULL); ++ ++ BLayoutBuilder::Group<> builder = BLayoutBuilder::Group<>(this, B_VERTICAL); ++ ++ BLayoutBuilder::Group<>::GridBuilder gridBuilder = builder.AddGrid(0.0, B_USE_DEFAULT_SPACING); ++ ++ gridBuilder.Add(fPathControl->CreateLabelLayoutItem(), 0, 0) ++ .Add(fPathControl->CreateTextViewLayoutItem(), 1, 0); ++ gridBuilder.Add(fSizeControl->CreateLabelLayoutItem(), 0, 1) ++ .Add(fSizeControl->CreateTextViewLayoutItem(), 1, 1); ++ ++ BButton* okButton; ++ builder.AddGroup(B_HORIZONTAL, B_USE_DEFAULT_SPACING) ++ .AddGlue() ++ .Add(new BButton(B_TRANSLATE("Cancel"), new BMessage(B_CANCEL))) ++ .Add(okButton = new BButton(B_TRANSLATE("OK"), new BMessage(kMsgOk))) ++ .End() ++ .SetInsets(B_USE_DEFAULT_SPACING); ++ ++ SetDefaultButton(okButton); ++} ++ ++ ++CreateRamDiskPanel::~CreateRamDiskPanel() ++{ ++} ++ ++void CreateRamDiskPanel::MessageReceived(BMessage* msg) ++{ ++ switch (msg->what) { ++ case B_OK: ++ break; ++ case B_CANCEL: ++ PostMessage(B_QUIT_REQUESTED); ++ break; ++ } ++} ++ +diff --git a/src/apps/drivesetup/CreateRamDiskPanel.h b/src/apps/drivesetup/CreateRamDiskPanel.h +new file mode 100644 +index 0000000000..aa1c0e789b +--- /dev/null ++++ b/src/apps/drivesetup/CreateRamDiskPanel.h +@@ -0,0 +1,27 @@ ++/* ++ * Copyright 2020 Haiku Inc. All rights reserved. ++ * Distributed under the terms of the MIT license. ++ */ ++#ifndef _CREATERAMDISKPANEL_H_ ++#define _CREATERAMDISKPANEL_H_ ++ ++ ++#include ++ ++class BTextControl; ++ ++ ++class CreateRamDiskPanel : public BWindow { ++public: ++ CreateRamDiskPanel(BWindow* window); ++ virtual ~CreateRamDiskPanel(); ++ ++private: ++ void MessageReceived(BMessage* msg); ++ ++ BTextControl* fPathControl; ++ BTextControl* fSizeControl; ++}; ++ ++ ++#endif // _CREATERAMDISKPANEL_H_ +diff --git a/src/apps/drivesetup/Jamfile b/src/apps/drivesetup/Jamfile +index de36f2da3b..3505479b40 100644 +--- a/src/apps/drivesetup/Jamfile ++++ b/src/apps/drivesetup/Jamfile +@@ -8,6 +8,7 @@ Preference DriveSetup : + AbstractParametersPanel.cpp + ChangeParametersPanel.cpp + CreateParametersPanel.cpp ++ CreateRamDiskPanel.cpp + DiskView.cpp + DriveSetup.cpp + EncryptionUtils.cpp +diff --git a/src/apps/drivesetup/MainWindow.cpp b/src/apps/drivesetup/MainWindow.cpp +index 272189fd62..a35748ade5 100644 +--- a/src/apps/drivesetup/MainWindow.cpp ++++ b/src/apps/drivesetup/MainWindow.cpp +@@ -15,6 +15,7 @@ + + #include + #include ++#include + + #include + #include +@@ -40,6 +41,8 @@ + #include + + #include ++#include ++#include + #include + + #include "ChangeParametersPanel.h" +@@ -49,6 +52,7 @@ + #include "InitParametersPanel.h" + #include "PartitionList.h" + #include "Support.h" ++#include "CreateRamDiskPanel.h" + + + #undef B_TRANSLATION_CONTEXT +@@ -63,6 +67,9 @@ enum { + MSG_CREATE = 'crtp', + MSG_CHANGE = 'chgp', + MSG_INITIALIZE = 'init', ++ MSG_CREATE_VIRTUAL_DISK = 'ctvd', ++ MSG_OPEN_VIRTUAL_DISK = 'opvd', ++ MSG_CREATE_RAM_DISK = 'ctrd', + MSG_DELETE = 'delt', + MSG_EJECT = 'ejct', + MSG_OPEN_DISKPROBE = 'opdp', +@@ -214,6 +221,12 @@ MainWindow::MainWindow() + fMenuBar = new BMenuBar(Bounds(), "root menu"); + + // create all the menu items ++ fCreateVirtualDiskMenuItem = new BMenuItem(B_TRANSLATE("Create virtual disk" B_UTF8_ELLIPSIS), ++ new BMessage(MSG_CREATE_VIRTUAL_DISK)); ++ fOpenVirtualDiskMenuItem = new BMenuItem(B_TRANSLATE("Open virtual disk" B_UTF8_ELLIPSIS), ++ new BMessage(MSG_OPEN_VIRTUAL_DISK)); ++ fCreateRamDiskMenuItem = new BMenuItem(B_TRANSLATE("Create RAM disk" B_UTF8_ELLIPSIS), ++ new BMessage(MSG_CREATE_RAM_DISK)); + fWipeMenuItem = new BMenuItem(B_TRANSLATE("Wipe (not implemented)"), + new BMessage(MSG_FORMAT)); + fEjectMenuItem = new BMenuItem(B_TRANSLATE("Eject"), +@@ -251,6 +264,10 @@ MainWindow::MainWindow() + + fDiskMenu->AddSeparatorItem(); + ++ fDiskMenu->AddItem(fCreateVirtualDiskMenuItem); ++ fDiskMenu->AddItem(fOpenVirtualDiskMenuItem); ++ fDiskMenu->AddItem(fCreateRamDiskMenuItem); ++ fDiskMenu->AddSeparatorItem(); + fDiskMenu->AddItem(fEjectMenuItem); + // fDiskMenu->AddItem(fSurfaceTestMenuItem); + fDiskMenu->AddItem(fRescanMenuItem); +@@ -384,6 +401,21 @@ MainWindow::MessageReceived(BMessage* message) + break; + } + ++ case MSG_CREATE_VIRTUAL_DISK: ++ _CreateVirtualDisk(); ++ break; ++ ++ case MSG_OPEN_VIRTUAL_DISK: ++ printf("MSG_OPEN_VIRTUAL_DISK\n"); ++ break; ++ ++ case MSG_CREATE_RAM_DISK: { ++ BWindow *wnd = new CreateRamDiskPanel(this); ++ wnd->Show(); ++ //_CreateRamDisk(); ++ break; ++ } ++ + case MSG_CHANGE: + _ChangeParameters(fCurrentDisk, fCurrentPartitionID); + break; +@@ -1473,3 +1505,40 @@ MainWindow::_UpdateWindowZoomLimits() + SetZoomLimits(maxWidth, maxHeight); + } + ++ ++void ++MainWindow::_CreateVirtualDisk() ++{ ++ const char *path = "/boot/home/downloads/haiku-master-hrev53759-x86_gcc2h-anyboot/haiku-master-hrev53759-x86_gcc2h-anyboot.iso"; ++ BDiskDeviceRoster roster; ++ partition_id id = roster.RegisterFileDevice(path); ++ if (id < 0) { ++ fprintf(stderr, "Error: Failed to register file disk device: %s\n", ++ strerror(id)); ++ } ++} ++ ++ ++void ++MainWindow::_CreateRamDisk() ++{ ++ const char *ctrlDevPath = "/dev/" RAM_DISK_CONTROL_DEVICE_NAME; ++ ++ ram_disk_ioctl_register request; ++ request.size = 1024*1024*1024 /* 1GB */; ++ request.path[0] = '\0'; ++ request.id = -1; ++ ++ int fd = open(ctrlDevPath, O_RDONLY); ++ if (fd < 0) { ++ fprintf(stderr, "Error: Failed to open RAM disk control device \"%s\": " ++ "%s\n", ctrlDevPath, strerror(errno)); ++ return; ++ } ++ FileDescriptorCloser fdCloser(fd); ++ ++ // issue the request ++ if (ioctl(fd, RAM_DISK_IOCTL_REGISTER, &request) < 0) ++ fprintf(stderr, "Error: Failed to create RAM disk device: %s\n", ++ strerror(errno)); ++} +diff --git a/src/apps/drivesetup/MainWindow.h b/src/apps/drivesetup/MainWindow.h +index 4e0823208d..769d66e37d 100644 +--- a/src/apps/drivesetup/MainWindow.h ++++ b/src/apps/drivesetup/MainWindow.h +@@ -81,6 +81,8 @@ private: + float _ColumnListViewHeight(BColumnListView* list, + BRow* currentRow); + void _UpdateWindowZoomLimits(); ++ void _CreateVirtualDisk(); ++ void _CreateRamDisk(); + + private: + BDiskDeviceRoster fDiskDeviceRoster; +@@ -100,6 +102,9 @@ private: + + BMenuBar* fMenuBar; + ++ BMenuItem* fCreateVirtualDiskMenuItem; ++ BMenuItem* fOpenVirtualDiskMenuItem; ++ BMenuItem* fCreateRamDiskMenuItem; + BMenuItem* fWipeMenuItem; + BMenuItem* fEjectMenuItem; + BMenuItem* fSurfaceTestMenuItem; +-- +2.30.2 + diff --git a/patchset-hrev55144/0004-StyledEdit-choose-lowest-unused-number-for-Untitled-.patch b/patchset-hrev55144/0004-StyledEdit-choose-lowest-unused-number-for-Untitled-.patch new file mode 100644 index 0000000..4747a88 --- /dev/null +++ b/patchset-hrev55144/0004-StyledEdit-choose-lowest-unused-number-for-Untitled-.patch @@ -0,0 +1,72 @@ +From 6463db5ab772dc5ab3319a334a14a8516a35f9ec Mon Sep 17 00:00:00 2001 +From: ejno +Date: Wed, 26 Jun 2013 08:48:24 +0000 +Subject: StyledEdit: choose lowest unused number for Untitled documents + +Change-Id: I8825008f45f2549e233be2c7adad13c8993f003d +--- + src/apps/stylededit/StyledEditApp.cpp | 25 +++++++++++++++++++++++-- + src/apps/stylededit/StyledEditApp.h | 1 - + 2 files changed, 23 insertions(+), 3 deletions(-) + +diff --git a/src/apps/stylededit/StyledEditApp.cpp b/src/apps/stylededit/StyledEditApp.cpp +index 7e3ecdc08d..810dc37ed6 100644 +--- a/src/apps/stylededit/StyledEditApp.cpp ++++ b/src/apps/stylededit/StyledEditApp.cpp +@@ -130,7 +130,6 @@ StyledEditApp::StyledEditApp() + fOpenPanelEncodingMenu = NULL; + + fWindowCount = 0; +- fNextUntitledWindow = 1; + fBadArguments = false; + + float factor = be_plain_font->Size() / 12.0f; +@@ -179,10 +178,32 @@ StyledEditApp::MessageReceived(BMessage* message) + } + + ++static int32 ++GetNextUntitled() ++{ ++ int nextUntitled = 1; ++ ++ BString untitled(B_TRANSLATE("Untitled ")); ++ BString title = untitled; ++ title << nextUntitled; ++ ++ int32 numWindows = be_app->CountWindows(); ++ for (int32 i = 0; i < numWindows; i++) { ++ if (be_app->WindowAt(i)->Title() == title) ++ { ++ title = untitled; ++ title << ++nextUntitled; ++ } ++ } ++ ++ return nextUntitled; ++} ++ ++ + void + StyledEditApp::OpenDocument() + { +- new StyledEditWindow(sWindowRect, fNextUntitledWindow++, fOpenAsEncoding); ++ new StyledEditWindow(sWindowRect, GetNextUntitled(), fOpenAsEncoding); + cascade(); + fWindowCount++; + } +diff --git a/src/apps/stylededit/StyledEditApp.h b/src/apps/stylededit/StyledEditApp.h +index 71f1f748bb..0de971fc07 100644 +--- a/src/apps/stylededit/StyledEditApp.h ++++ b/src/apps/stylededit/StyledEditApp.h +@@ -49,7 +49,6 @@ private: + BMenu* fOpenPanelEncodingMenu; + uint32 fOpenAsEncoding; + int32 fWindowCount; +- int32 fNextUntitledWindow; + bool fBadArguments; + }; + +-- +2.30.2 + diff --git a/patchset-hrev55144/0005-app_server-remove-lock-check-in-DrawStringDry.patch b/patchset-hrev55144/0005-app_server-remove-lock-check-in-DrawStringDry.patch new file mode 100644 index 0000000..a2b312e --- /dev/null +++ b/patchset-hrev55144/0005-app_server-remove-lock-check-in-DrawStringDry.patch @@ -0,0 +1,39 @@ +From 0b044e5c0c5dbbbb1c7169fe28e85c2e76299972 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sat, 16 May 2020 19:28:42 +0900 +Subject: app_server: remove lock check in DrawStringDry + +It doesn't perform actual drawing so locking is not needed. + +Fixes #16036. + +Change-Id: I5ec8118c95c10d10afa1e18210f673669c8f1bb8 +--- + src/servers/app/drawing/DrawingEngine.cpp | 4 ---- + 1 file changed, 4 deletions(-) + +diff --git a/src/servers/app/drawing/DrawingEngine.cpp b/src/servers/app/drawing/DrawingEngine.cpp +index fe61307121..e970b6af1a 100644 +--- a/src/servers/app/drawing/DrawingEngine.cpp ++++ b/src/servers/app/drawing/DrawingEngine.cpp +@@ -1430,8 +1430,6 @@ BPoint + DrawingEngine::DrawStringDry(const char* string, int32 length, + const BPoint& pt, escapement_delta* delta) + { +- ASSERT_PARALLEL_LOCKED(); +- + BPoint penLocation = pt; + + // try a fast path first +@@ -1451,8 +1449,6 @@ BPoint + DrawingEngine::DrawStringDry(const char* string, int32 length, + const BPoint* offsets) + { +- ASSERT_PARALLEL_LOCKED(); +- + BPoint penLocation; + fPainter->BoundingBox(string, length, offsets, &penLocation, NULL); + +-- +2.30.2 + diff --git a/patchset-hrev55144/0006-libbnetapi-add-libbe_test.patch b/patchset-hrev55144/0006-libbnetapi-add-libbe_test.patch new file mode 100644 index 0000000..d3727db --- /dev/null +++ b/patchset-hrev55144/0006-libbnetapi-add-libbe_test.patch @@ -0,0 +1,25 @@ +From 79c572017c7bd5fe38d5d4b87ced2d47d9321221 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 17 May 2020 19:04:28 +0900 +Subject: libbnetapi: add libbe_test + +Change-Id: I8f8f96887bc1d696fed90bee2624d498a32137f7 +--- + src/kits/network/libnetapi/Jamfile | 2 ++ + 1 file changed, 2 insertions(+) + +diff --git a/src/kits/network/libnetapi/Jamfile b/src/kits/network/libnetapi/Jamfile +index a08c92b93b..f48658a8cf 100644 +--- a/src/kits/network/libnetapi/Jamfile ++++ b/src/kits/network/libnetapi/Jamfile +@@ -1,5 +1,7 @@ + SubDir HAIKU_TOP src kits network libnetapi ; + ++AddSubDirSupportedPlatforms libbe_test ; ++ + UsePrivateHeaders app net shared storage support ; + UsePrivateHeaders locale shared ; + +-- +2.30.2 + diff --git a/patchset-hrev55144/0007-Webpositive-add-libbe_test.patch b/patchset-hrev55144/0007-Webpositive-add-libbe_test.patch new file mode 100644 index 0000000..eacbd43 --- /dev/null +++ b/patchset-hrev55144/0007-Webpositive-add-libbe_test.patch @@ -0,0 +1,25 @@ +From bed6c027f63821e6d8f0ffbccd554c8c6f6f4313 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Fri, 22 May 2020 11:08:56 +0900 +Subject: Webpositive: add libbe_test + +Change-Id: Iea616e17d8c6de0202568446886ba474ccc75a7d +--- + src/apps/webpositive/Jamfile | 2 ++ + 1 file changed, 2 insertions(+) + +diff --git a/src/apps/webpositive/Jamfile b/src/apps/webpositive/Jamfile +index 5e2c335dc7..894eb67d0a 100644 +--- a/src/apps/webpositive/Jamfile ++++ b/src/apps/webpositive/Jamfile +@@ -1,5 +1,7 @@ + SubDir HAIKU_TOP src apps webpositive ; + ++AddSubDirSupportedPlatforms libbe_test ; ++ + SubDirC++Flags $(defines) -Wno-error=sequence-point -Wno-error=format-truncation ; + SubDirCcFlags $(defines) -Wno-error=sequence-point -Wno-error=format-truncation ; + +-- +2.30.2 + diff --git a/patchset-hrev55144/0008-WebPositive-Fix-crash-for-libbe_test.patch b/patchset-hrev55144/0008-WebPositive-Fix-crash-for-libbe_test.patch new file mode 100644 index 0000000..1f189c7 --- /dev/null +++ b/patchset-hrev55144/0008-WebPositive-Fix-crash-for-libbe_test.patch @@ -0,0 +1,34 @@ +From add1c538231dc93a538f427011f14db73945f32e Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 1 Jun 2020 10:21:48 +0900 +Subject: WebPositive: Fix crash for libbe_test + +Change-Id: I509484a2e7f91cf1f39ec249c079564e58a38f0d +--- + src/apps/webpositive/BrowserWindow.cpp | 3 +++ + 1 file changed, 3 insertions(+) + +diff --git a/src/apps/webpositive/BrowserWindow.cpp b/src/apps/webpositive/BrowserWindow.cpp +index 833173871f..182911017c 100644 +--- a/src/apps/webpositive/BrowserWindow.cpp ++++ b/src/apps/webpositive/BrowserWindow.cpp +@@ -671,6 +671,8 @@ BrowserWindow::BrowserWindow(BRect frame, SettingsMessage* appSettings, + AddShortcut(numStr[0], B_COMMAND_KEY, selectTab); + } + ++// BKeymap is not working for libbe_test ++#ifndef HAIKU_TARGET_PLATFORM_LIBBE_TEST + BKeymap keymap; + keymap.SetToCurrent(); + BObjectList unmodified(3, true); +@@ -687,6 +689,7 @@ BrowserWindow::BrowserWindow(BRect frame, SettingsMessage* appSettings, + } + } + unmodified.MakeEmpty(); ++#endif + + be_app->PostMessage(WINDOW_OPENED); + } +-- +2.30.2 + diff --git a/patchset-hrev55144/0009-BGradient-add-Copy-method.patch b/patchset-hrev55144/0009-BGradient-add-Copy-method.patch new file mode 100644 index 0000000..e8fe6f2 --- /dev/null +++ b/patchset-hrev55144/0009-BGradient-add-Copy-method.patch @@ -0,0 +1,109 @@ +From 2db4112d9245e2bd34bf72e661e47f0de7f8a79f Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 1 Jun 2020 20:57:30 +0900 +Subject: BGradient: add Copy method + +Change-Id: I3edd4eb42f1bbd0f1f50a9488652dad8b59a13b8 +--- + headers/os/interface/Gradient.h | 1 + + src/kits/interface/Gradient.cpp | 58 +++++++++++++++++++++------------ + 2 files changed, 38 insertions(+), 21 deletions(-) + +diff --git a/headers/os/interface/Gradient.h b/headers/os/interface/Gradient.h +index ca3f8035a9..bb1045d0ac 100644 +--- a/headers/os/interface/Gradient.h ++++ b/headers/os/interface/Gradient.h +@@ -88,6 +88,7 @@ public: + + void MakeEmpty(); + ++ BGradient* Copy() const; + status_t Flatten(BDataIO* stream) const; + static status_t Unflatten(BGradient *&output, BDataIO* stream); + +diff --git a/src/kits/interface/Gradient.cpp b/src/kits/interface/Gradient.cpp +index c0c8fce68b..9365b8f7cf 100644 +--- a/src/kits/interface/Gradient.cpp ++++ b/src/kits/interface/Gradient.cpp +@@ -12,6 +12,7 @@ + #include + #include + #include ++#include + + #include + #include +@@ -487,6 +488,42 @@ BGradient::MakeEmpty() + } + + ++static BGradient* ++gradient_for_type(BGradient::Type type) ++{ ++ switch (type) { ++ case BGradient::TYPE_LINEAR: ++ return new (std::nothrow) BGradientLinear(); ++ case BGradient::TYPE_RADIAL: ++ return new (std::nothrow) BGradientRadial(); ++ case BGradient::TYPE_RADIAL_FOCUS: ++ return new (std::nothrow) BGradientRadialFocus(); ++ case BGradient::TYPE_DIAMOND: ++ return new (std::nothrow) BGradientDiamond(); ++ case BGradient::TYPE_CONIC: ++ return new (std::nothrow) BGradientConic(); ++ case BGradient::TYPE_NONE: ++ return new (std::nothrow) BGradient(); ++ } ++ return NULL; ++} ++ ++ ++BGradient* ++BGradient::Copy() const ++{ ++ BGradient* gradient = gradient_for_type(fType); ++ if (gradient == NULL) ++ return gradient; ++ ++ gradient->fType = fType; ++ gradient->SetColorStops(*this); ++ memcpy(&gradient->fData, &fData, sizeof(fData)); ++ ++ return gradient; ++} ++ ++ + status_t + BGradient::Flatten(BDataIO* stream) const + { +@@ -535,27 +572,6 @@ BGradient::Flatten(BDataIO* stream) const + } + + +-static BGradient* +-gradient_for_type(BGradient::Type type) +-{ +- switch (type) { +- case BGradient::TYPE_LINEAR: +- return new (std::nothrow) BGradientLinear(); +- case BGradient::TYPE_RADIAL: +- return new (std::nothrow) BGradientRadial(); +- case BGradient::TYPE_RADIAL_FOCUS: +- return new (std::nothrow) BGradientRadialFocus(); +- case BGradient::TYPE_DIAMOND: +- return new (std::nothrow) BGradientDiamond(); +- case BGradient::TYPE_CONIC: +- return new (std::nothrow) BGradientConic(); +- case BGradient::TYPE_NONE: +- return new (std::nothrow) BGradient(); +- } +- return NULL; +-} +- +- + status_t + BGradient::Unflatten(BGradient *&output, BDataIO* stream) + { +-- +2.30.2 + diff --git a/patchset-hrev55144/0010-registrar-use-smaller-minimal-timer-interval.patch b/patchset-hrev55144/0010-registrar-use-smaller-minimal-timer-interval.patch new file mode 100644 index 0000000..7ebcd4c --- /dev/null +++ b/patchset-hrev55144/0010-registrar-use-smaller-minimal-timer-interval.patch @@ -0,0 +1,37 @@ +From f72139b3889cfdc33a7e37732df8de9a59ee9eae Mon Sep 17 00:00:00 2001 +From: X512 +Date: Fri, 5 Jun 2020 14:06:19 +0900 +Subject: registrar: use smaller minimal timer interval + +Change-Id: Ie0788ba9b48597bb9cead20b3125af251b5b59cf +--- + src/servers/registrar/MessageRunnerManager.cpp | 6 +++--- + 1 file changed, 3 insertions(+), 3 deletions(-) + +diff --git a/src/servers/registrar/MessageRunnerManager.cpp b/src/servers/registrar/MessageRunnerManager.cpp +index 2df05d914d..9b04157827 100644 +--- a/src/servers/registrar/MessageRunnerManager.cpp ++++ b/src/servers/registrar/MessageRunnerManager.cpp +@@ -64,8 +64,8 @@ using std::nothrow; + + using namespace BPrivate; + +-//! The minimal time interval for message runners (50 ms). +-static const bigtime_t kMininalTimeInterval = 50000LL; ++//! The minimal time interval for message runners (1 us). ++static const bigtime_t kMininalTimeInterval = 1LL; + + + static bigtime_t +@@ -101,7 +101,7 @@ public: + /*! \brief Hook method invoked when the event is executed. + + Implements Event. Calls MessageRunnerManager::_DoEvent(). +- ++ + \param queue The event queue executing the event. + \return \c true, if the object shall be deleted, \c false otherwise. + */ +-- +2.30.2 + diff --git a/patchset-hrev55144/0011-print_server-fix-scripting.patch b/patchset-hrev55144/0011-print_server-fix-scripting.patch new file mode 100644 index 0000000..fb8f152 --- /dev/null +++ b/patchset-hrev55144/0011-print_server-fix-scripting.patch @@ -0,0 +1,275 @@ +From fa97658e3d5fdbc43a7be4bce7b73c32705e00c6 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 29 Jun 2020 13:31:43 +0900 +Subject: print_server: fix scripting + +* Refactor code to use BPropertyInfo::FindMatch. +* Call base class when PrintServerApp don't support scripting message +* Rename "Printers" to "Printer" and "Transports" to "Transport" to + follow scriptint property naming conventions. +* Replace "OpenBeOS" to "Haiku" in scripting suite name. + +Change-Id: I19053799f60d71485297a1cbf0efacbb2a8eedb7 +--- + .../print/PrintServerApp.Scripting.cpp | 161 +++++++++--------- + src/servers/print/PrintServerApp.cpp | 12 +- + src/servers/print/Printer.Scripting.cpp | 2 +- + src/servers/print/Transport.Scripting.cpp | 2 +- + 4 files changed, 82 insertions(+), 95 deletions(-) + +diff --git a/src/servers/print/PrintServerApp.Scripting.cpp b/src/servers/print/PrintServerApp.Scripting.cpp +index 531f7efc37..3c48a68aa1 100644 +--- a/src/servers/print/PrintServerApp.Scripting.cpp ++++ b/src/servers/print/PrintServerApp.Scripting.cpp +@@ -35,12 +35,12 @@ static property_info prop_list[] = { + { "Printer", { B_DELETE_PROPERTY }, { B_INDEX_SPECIFIER, B_NAME_SPECIFIER, + B_REVERSE_INDEX_SPECIFIER }, + B_TRANSLATE_MARK("Delete a specific printer") }, +- { "Printers", { B_COUNT_PROPERTIES }, { B_DIRECT_SPECIFIER }, ++ { "Printer", { B_COUNT_PROPERTIES }, { B_DIRECT_SPECIFIER }, + B_TRANSLATE_MARK("Return the number of available printers") }, + { "Transport", { B_GET_PROPERTY }, { B_INDEX_SPECIFIER, B_NAME_SPECIFIER, + B_REVERSE_INDEX_SPECIFIER }, + B_TRANSLATE_MARK("Retrieve a specific transport") }, +- { "Transports", { B_COUNT_PROPERTIES }, { B_DIRECT_SPECIFIER }, ++ { "Transport", { B_COUNT_PROPERTIES }, { B_DIRECT_SPECIFIER }, + B_TRANSLATE_MARK("Return the number of available transports") }, + { "UseConfigWindow", { B_GET_PROPERTY, B_SET_PROPERTY }, + { B_DIRECT_SPECIFIER }, +@@ -53,94 +53,87 @@ static property_info prop_list[] = { + void + PrintServerApp::HandleScriptingCommand(BMessage* msg) + { +- BString propName; +- BMessage spec; +- int32 idx; ++ BMessage reply(B_REPLY); ++ status_t err = B_BAD_SCRIPT_SYNTAX; ++ int32 index; ++ BMessage specifier; ++ int32 what; ++ const char* property; ++ ++ if (msg->GetCurrentSpecifier(&index, &specifier, &what, &property) ++ != B_OK) { ++ return Inherited::MessageReceived(msg); ++ } + +- if (msg->GetCurrentSpecifier(&idx,&spec) == B_OK && +- spec.FindString("property",&propName) == B_OK) { +- switch(msg->what) { +- case B_GET_PROPERTY: +- if (propName == "ActivePrinter") { +- BMessage reply(B_REPLY); +- reply.AddString("result", fDefaultPrinter ++ BPropertyInfo propInfo(prop_list); ++ switch (propInfo.FindMatch(msg, index, &specifier, what, property)) { ++ case 0: // ActivePrinter: GET, SET ++ switch (msg->what) { ++ case B_GET_PROPERTY: ++ err = reply.AddString("result", fDefaultPrinter + ? fDefaultPrinter->Name() : ""); +- reply.AddInt32("error", B_OK); +- msg->SendReply(&reply); +- } else if (propName == "UseConfigWindow") { +- BMessage reply(B_REPLY); +- reply.AddString("result", fUseConfigWindow +- ? "true" : "false"); +- reply.AddInt32("error", B_OK); +- msg->SendReply(&reply); +- } +- break; +- +- case B_SET_PROPERTY: +- if (propName == "ActivePrinter") { ++ break; ++ case B_SET_PROPERTY: { + BString newActivePrinter; +- if (msg->FindString("data", &newActivePrinter) == B_OK) { +- BMessage reply(B_REPLY); +- reply.AddInt32("error", +- SelectPrinter(newActivePrinter.String())); +- msg->SendReply(&reply); +- } +- } else if (propName == "UseConfigWindow") { ++ err = msg->FindString("data", &newActivePrinter); ++ if (err >= B_OK) ++ err = SelectPrinter(newActivePrinter.String()); ++ break; ++ } ++ } ++ break; ++ case 2: { // Printer: CREATE ++ BString name, driver, transport, config; ++ err = msg->FindString("name", &name); ++ if (err >= B_OK) ++ err = msg->FindString("driver", &driver); ++ if (err >= B_OK) ++ err = msg->FindString("transport", &transport); ++ if (err >= B_OK) ++ err = msg->FindString("config", &config); ++ if (err >= B_OK) ++ err = CreatePrinter(name, driver, "Local", transport, config); ++ break; ++ } ++ case 3: { // Printer: DELETE ++ Printer* printer = GetPrinterFromSpecifier(&specifier); ++ if (printer == NULL) ++ err = B_BAD_VALUE; ++ if (err >= B_OK) ++ err = printer->Remove(); ++ break; ++ } ++ case 4: // Printers: COUNT ++ err = reply.AddInt32("result", Printer::CountPrinters()); ++ break; ++ case 6: // Transports: COUNT ++ err = reply.AddInt32("result", Transport::CountTransports()); ++ break; ++ case 7: // UseConfigWindow: GET, SET ++ switch (msg->what) { ++ case B_GET_PROPERTY: ++ err = reply.AddString("result", fUseConfigWindow ? "true" ++ : "false"); ++ break; ++ case B_SET_PROPERTY: + bool useConfigWindow; +- if (msg->FindBool("data", &useConfigWindow) == B_OK) { ++ err = msg->FindBool("data", &useConfigWindow); ++ if (err >= B_OK) + fUseConfigWindow = useConfigWindow; +- BMessage reply(B_REPLY); +- reply.AddInt32("error", fUseConfigWindow); +- msg->SendReply(&reply); +- } +- } +- break; +- +- case B_CREATE_PROPERTY: +- if (propName == "Printer") { +- BString name, driver, transport, config; +- +- if (msg->FindString("name", &name) == B_OK +- && msg->FindString("driver", &driver) == B_OK +- && msg->FindString("transport", &transport) == B_OK +- && msg->FindString("config", &config) == B_OK) { +- BMessage reply(B_REPLY); +- reply.AddInt32("error", CreatePrinter(name.String(), +- driver.String(), "Local", transport.String(), +- config.String())); +- msg->SendReply(&reply); +- } +- } +- break; +- +- case B_DELETE_PROPERTY: { +- Printer* printer = GetPrinterFromSpecifier(&spec); +- status_t rc = B_BAD_VALUE; +- +- if (printer != NULL) +- rc=printer->Remove(); ++ break; ++ } ++ break; ++ default: ++ return Inherited::MessageReceived(msg); ++ } + +- BMessage reply(B_REPLY); +- reply.AddInt32("error", rc); +- msg->SendReply(&reply); +- } +- break; +- +- case B_COUNT_PROPERTIES: +- if (propName == "Printers") { +- BMessage reply(B_REPLY); +- reply.AddInt32("result", Printer::CountPrinters()); +- reply.AddInt32("error", B_OK); +- msg->SendReply(&reply); +- } else if (propName == "Transports") { +- BMessage reply(B_REPLY); +- reply.AddInt32("result", Transport::CountTransports()); +- reply.AddInt32("error", B_OK); +- msg->SendReply(&reply); +- } +- break; +- } ++ if (err < B_OK) { ++ reply.what = B_MESSAGE_NOT_UNDERSTOOD; ++ reply.AddString("message", strerror(err)); + } ++ ++ reply.AddInt32("error", err); ++ msg->SendReply(&reply); + } + + +@@ -256,7 +249,7 @@ PrintServerApp::ResolveSpecifier(BMessage* msg, int32 index, BMessage* spec, + status_t + PrintServerApp::GetSupportedSuites(BMessage* msg) + { +- msg->AddString("suites", "suite/vnd.OpenBeOS-printserver"); ++ msg->AddString("suites", "suite/vnd.Haiku-printserver"); + + static bool localized = false; + if (!localized) { +diff --git a/src/servers/print/PrintServerApp.cpp b/src/servers/print/PrintServerApp.cpp +index 4a5be6e316..e00f2ccc80 100644 +--- a/src/servers/print/PrintServerApp.cpp ++++ b/src/servers/print/PrintServerApp.cpp +@@ -315,6 +315,9 @@ PrintServerApp::SetupPrinterList() + void + PrintServerApp::MessageReceived(BMessage* msg) + { ++ if (msg->HasSpecifiers()) ++ return HandleScriptingCommand(msg); ++ + switch(msg->what) { + case PSRV_GET_ACTIVE_PRINTER: + case PSRV_MAKE_PRINTER_ACTIVE_QUIETLY: +@@ -327,15 +330,6 @@ PrintServerApp::MessageReceived(BMessage* msg) + Handle_BeOSR5_Message(msg); + break; + +- case B_GET_PROPERTY: +- case B_SET_PROPERTY: +- case B_CREATE_PROPERTY: +- case B_DELETE_PROPERTY: +- case B_COUNT_PROPERTIES: +- case B_EXECUTE_PROPERTY: +- HandleScriptingCommand(msg); +- break; +- + default: + Inherited::MessageReceived(msg); + } +diff --git a/src/servers/print/Printer.Scripting.cpp b/src/servers/print/Printer.Scripting.cpp +index bf386039ef..804ea38b65 100644 +--- a/src/servers/print/Printer.Scripting.cpp ++++ b/src/servers/print/Printer.Scripting.cpp +@@ -105,7 +105,7 @@ Printer::ResolveSpecifier(BMessage* msg, int32 index, BMessage* spec, + status_t + Printer::GetSupportedSuites(BMessage* msg) + { +- msg->AddString("suites", "application/x-vnd.OpenBeOS-printer"); ++ msg->AddString("suites", "application/x-vnd.Haiku-printer"); + + static bool localized = false; + if (!localized) { +diff --git a/src/servers/print/Transport.Scripting.cpp b/src/servers/print/Transport.Scripting.cpp +index 04f1f447eb..b4470f01cb 100644 +--- a/src/servers/print/Transport.Scripting.cpp ++++ b/src/servers/print/Transport.Scripting.cpp +@@ -99,7 +99,7 @@ Transport::ResolveSpecifier(BMessage* msg, int32 index, BMessage* spec, + status_t + Transport::GetSupportedSuites(BMessage* msg) + { +- msg->AddString("suites", "application/x-vnd.OpenBeOS-transport"); ++ msg->AddString("suites", "application/x-vnd.Haiku-transport"); + + static bool localized = false; + if (!localized) { +-- +2.30.2 + diff --git a/patchset-hrev55144/0012-XHCI-add-zero-division-checks.patch b/patchset-hrev55144/0012-XHCI-add-zero-division-checks.patch new file mode 100644 index 0000000..a78f862 --- /dev/null +++ b/patchset-hrev55144/0012-XHCI-add-zero-division-checks.patch @@ -0,0 +1,42 @@ +From 8b665f1e0e31f25806a9f518b64bdb10e77ea712 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Thu, 2 Jul 2020 14:48:01 +0900 +Subject: XHCI: add zero division checks + +Change-Id: I6f5bcc61f53c0fb665808229dee55d42632ce433 +--- + src/add-ons/kernel/busses/usb/xhci.cpp | 11 +++++++++++ + 1 file changed, 11 insertions(+) + +diff --git a/src/add-ons/kernel/busses/usb/xhci.cpp b/src/add-ons/kernel/busses/usb/xhci.cpp +index 13cb0cc5c9..fdee4b592a 100644 +--- a/src/add-ons/kernel/busses/usb/xhci.cpp ++++ b/src/add-ons/kernel/busses/usb/xhci.cpp +@@ -805,6 +805,11 @@ XHCI::SubmitNormalRequest(Transfer *transfer) + // things simple by setting trbSize to the MBP. (XHCI 1.2 ยง 4.11.7.1 p235.) + size_t trbSize = endpoint->max_burst_payload; + ++ if (trbSize == 0) { ++ TRACE_ALWAYS("[!] trbSize == 0\n"); ++ return B_BAD_VALUE; ++ } ++ + if (isochronousData != NULL) { + if (isochronousData->packet_count == 0) + return B_BAD_VALUE; +@@ -825,6 +830,12 @@ XHCI::SubmitNormalRequest(Transfer *transfer) + + // Normal Stage + const size_t maxPacketSize = pipe->MaxPacketSize(); ++ ++ if (maxPacketSize == 0) { ++ TRACE_ALWAYS("[!] maxPacketSize == 0\n"); ++ return B_BAD_VALUE; ++ } ++ + size_t remaining = transfer->DataLength(); + for (int32 i = 0; i < trbCount; i++) { + int32 trbLength = (remaining < trbSize) ? remaining : trbSize; +-- +2.30.2 + diff --git a/patchset-hrev55144/0013-BMenu-fix-memory-leak-in-scripting.patch b/patchset-hrev55144/0013-BMenu-fix-memory-leak-in-scripting.patch new file mode 100644 index 0000000..79a9e4a --- /dev/null +++ b/patchset-hrev55144/0013-BMenu-fix-memory-leak-in-scripting.patch @@ -0,0 +1,33 @@ +From 2b6c2bb053142cdd68bc73d68f0cececb75d84fe Mon Sep 17 00:00:00 2001 +From: X512 +Date: Thu, 2 Jul 2020 23:48:47 +0900 +Subject: BMenu: fix memory leak in scripting + +Change-Id: Ib1f43ee61f1e300e5a60bb398aa29b4a6ca8f7a5 +--- + src/kits/interface/Menu.cpp | 2 ++ + 1 file changed, 2 insertions(+) + +diff --git a/src/kits/interface/Menu.cpp b/src/kits/interface/Menu.cpp +index 72c094692b..04bd3b5acc 100644 +--- a/src/kits/interface/Menu.cpp ++++ b/src/kits/interface/Menu.cpp +@@ -1678,6 +1678,7 @@ void BMenu::_ScriptReceived(BMessage* message) + RemoveItem(index); + else + RemoveItem(item); ++ delete item; + } + } + } +@@ -1750,6 +1751,7 @@ void BMenu::_ScriptReceived(BMessage* message) + RemoveItem(index); + else + RemoveItem(item); ++ delete item; + } + } + break; +-- +2.30.2 + diff --git a/patchset-hrev55144/0014-video_mixer-fix-build-and-crash-add-to-image.patch b/patchset-hrev55144/0014-video_mixer-fix-build-and-crash-add-to-image.patch new file mode 100644 index 0000000..cb47fd1 --- /dev/null +++ b/patchset-hrev55144/0014-video_mixer-fix-build-and-crash-add-to-image.patch @@ -0,0 +1,261 @@ +From 4199755cfb1895411078274dc46e9bf5dbda1d7a Mon Sep 17 00:00:00 2001 +From: X512 +Date: Tue, 14 Jul 2020 21:37:00 +0900 +Subject: video_mixer: fix build and crash, add to image + +Change-Id: I3c58538666313e74134fb6f1f5fc0c697b213cca +--- + build/jam/images/definitions/regular | 1 + + .../media-add-ons/video_mixer/BufferMixer.cpp | 2 +- + .../media/media-add-ons/video_mixer/Jamfile | 2 +- + .../video_mixer/VideoMixerAddOn.cpp | 16 ++++++++-------- + .../media-add-ons/video_mixer/VideoMixerNode.cpp | 16 ++++++++-------- + .../video_mixer/VideoMixerNodeConsumer.cpp | 4 ++-- + .../video_mixer/VideoMixerNodeEventLooper.cpp | 4 ++-- + .../video_mixer/VideoMixerNodeProducer.cpp | 4 ++-- + 8 files changed, 25 insertions(+), 24 deletions(-) + +diff --git a/build/jam/images/definitions/regular b/build/jam/images/definitions/regular +index 43d5117915..6d42312521 100644 +--- a/build/jam/images/definitions/regular ++++ b/build/jam/images/definitions/regular +@@ -147,6 +147,7 @@ SYSTEM_ADD_ONS_MEDIA += [ FFilterByBuildFeatures + opensound.media_addon + tone_producer_demo.media_addon + usb_webcam.media_addon ++ video_mixer.media_addon + video_producer_demo.media_addon video_window_demo.media_addon + vst_host.media_addon + ] ; +diff --git a/src/add-ons/media/media-add-ons/video_mixer/BufferMixer.cpp b/src/add-ons/media/media-add-ons/video_mixer/BufferMixer.cpp +index 22aeda7cbb..347cfd8649 100644 +--- a/src/add-ons/media/media-add-ons/video_mixer/BufferMixer.cpp ++++ b/src/add-ons/media/media-add-ons/video_mixer/BufferMixer.cpp +@@ -54,7 +54,7 @@ BufferMixer::Merge(BBuffer *input, BBuffer *output) { + + uint8 *source = (uint8 *)input->Data(); + uint8 *destination = (uint8 *)output->Data(); +- uint32 size = input->Header()->size_used / 4; ++ uint32 size = input->Header()->size_used / 4; + uint8 alpha = 0; + uint8 c1, c2, c3; + +diff --git a/src/add-ons/media/media-add-ons/video_mixer/Jamfile b/src/add-ons/media/media-add-ons/video_mixer/Jamfile +index f41d494cbd..6446260270 100644 +--- a/src/add-ons/media/media-add-ons/video_mixer/Jamfile ++++ b/src/add-ons/media/media-add-ons/video_mixer/Jamfile +@@ -13,7 +13,7 @@ for architectureObject in [ MultiArchSubDirSetup ] { + VideoMixerAddOn.cpp + CpuCapabilities.cpp + BufferMixer.cpp +- yuvrgb.nasm ++ # yuvrgb.nasm + : be media [ TargetLibsupc++ ] [ TargetLibstdc++ ] + ; + } +diff --git a/src/add-ons/media/media-add-ons/video_mixer/VideoMixerAddOn.cpp b/src/add-ons/media/media-add-ons/video_mixer/VideoMixerAddOn.cpp +index af739abe0c..35d48063c7 100644 +--- a/src/add-ons/media/media-add-ons/video_mixer/VideoMixerAddOn.cpp ++++ b/src/add-ons/media/media-add-ons/video_mixer/VideoMixerAddOn.cpp +@@ -40,7 +40,7 @@ VideoMixerAddOn::~VideoMixerAddOn() + VideoMixerAddOn::VideoMixerAddOn(image_id image) : + BMediaAddOn(image) + { +- PRINT("VideoMixerAddOn::VideoMixerAddOn\n"); ++ PRINT(("VideoMixerAddOn::VideoMixerAddOn\n")); + refCount = 0; + } + +@@ -51,13 +51,13 @@ VideoMixerAddOn::VideoMixerAddOn(image_id image) : + status_t VideoMixerAddOn::InitCheck( + const char **out_failure_text) + { +- PRINT("VideoMixerAddOn::InitCheck\n"); ++ PRINT(("VideoMixerAddOn::InitCheck\n")); + return B_OK; + } + + int32 VideoMixerAddOn::CountFlavors() + { +- PRINT("VideoMixerAddOn::CountFlavors\n"); ++ PRINT(("VideoMixerAddOn::CountFlavors\n")); + return 1; + } + +@@ -65,7 +65,7 @@ status_t VideoMixerAddOn::GetFlavorAt( + int32 n, + const flavor_info **out_info) + { +- PRINT("VideoMixerAddOn::GetFlavorAt\n"); ++ PRINT(("VideoMixerAddOn::GetFlavorAt\n")); + if (n != 0) { + fprintf(stderr,"<- B_BAD_INDEX\n"); + return B_BAD_INDEX; +@@ -81,7 +81,7 @@ BMediaNode * VideoMixerAddOn::InstantiateNodeFor( + BMessage * config, + status_t * out_error) + { +- PRINT("VideoMixerAddOn::InstantiateNodeFor\n"); ++ PRINT(("VideoMixerAddOn::InstantiateNodeFor\n")); + VideoMixerNode *node = new VideoMixerNode(info, config, this); + if (node == NULL) { + *out_error = B_NO_MEMORY; +@@ -96,7 +96,7 @@ status_t VideoMixerAddOn::GetConfigurationFor( + BMediaNode * your_node, + BMessage * into_message) + { +- PRINT("VideoMixerAddOn::GetConfigurationFor\n"); ++ PRINT(("VideoMixerAddOn::GetConfigurationFor\n")); + VideoMixerNode *node = dynamic_cast(your_node); + if (node == NULL) { + fprintf(stderr,"<- B_BAD_TYPE\n"); +@@ -107,7 +107,7 @@ status_t VideoMixerAddOn::GetConfigurationFor( + + bool VideoMixerAddOn::WantsAutoStart() + { +- PRINT("VideoMixerAddOn::WantsAutoStart\n"); ++ PRINT(("VideoMixerAddOn::WantsAutoStart\n")); + return false; + } + +@@ -117,7 +117,7 @@ status_t VideoMixerAddOn::AutoStart( + int32 *out_internal_id, + bool *out_has_more) + { +- PRINT("VideoMixerAddOn::AutoStart\n"); ++ PRINT(("VideoMixerAddOn::AutoStart\n")); + return B_OK; + } + +diff --git a/src/add-ons/media/media-add-ons/video_mixer/VideoMixerNode.cpp b/src/add-ons/media/media-add-ons/video_mixer/VideoMixerNode.cpp +index e85e125340..0f9918dc2b 100644 +--- a/src/add-ons/media/media-add-ons/video_mixer/VideoMixerNode.cpp ++++ b/src/add-ons/media/media-add-ons/video_mixer/VideoMixerNode.cpp +@@ -93,7 +93,7 @@ VideoMixerNode::CreateInput(uint32 inputID) { + ClearInput(input); + + // don't overwrite available space, and be sure to terminate +- sprintf(input->name, "VideoMixer Input %ld", inputID); ++ sprintf(input->name, "VideoMixer Input %" B_PRIu32, inputID); + + return input; + } +@@ -185,7 +185,7 @@ BMediaAddOn *VideoMixerNode::AddOn( + + void VideoMixerNode::Start(bigtime_t performance_time) + { +- fprintf(stderr,"VideoMixerNode::Start(pt=%lld)\n", performance_time); ++ fprintf(stderr,"VideoMixerNode::Start(pt=%" B_PRIdBIGTIME ")\n", performance_time); + BMediaEventLooper::Start(performance_time); + } + +@@ -194,9 +194,9 @@ void VideoMixerNode::Stop( + bool immediate) + { + if (immediate) { +- fprintf(stderr,"VideoMixerNode::Stop(pt=%lld,)\n", performance_time); ++ fprintf(stderr,"VideoMixerNode::Stop(pt=%" B_PRIdBIGTIME ",)\n", performance_time); + } else { +- fprintf(stderr,"VideoMixerNode::Stop(pt=%lld,)\n", performance_time); ++ fprintf(stderr,"VideoMixerNode::Stop(pt=%" B_PRIdBIGTIME ",)\n", performance_time); + } + BMediaEventLooper::Stop(performance_time, immediate); + } +@@ -205,7 +205,7 @@ void VideoMixerNode::Seek( + bigtime_t media_time, + bigtime_t performance_time) + { +- fprintf(stderr,"VideoMixerNode::Seek(mt=%lld,pt=%lld)\n", media_time,performance_time); ++ fprintf(stderr,"VideoMixerNode::Seek(mt=%" B_PRIdBIGTIME ",pt=%" B_PRIdBIGTIME ")\n", media_time,performance_time); + BMediaEventLooper::Seek(media_time, performance_time); + } + +@@ -219,7 +219,7 @@ void VideoMixerNode::TimeWarp( + bigtime_t at_real_time, + bigtime_t to_performance_time) + { +- fprintf(stderr,"VideoMixerNode::TimeWarp(rt=%lld,pt=%lld)\n", at_real_time, to_performance_time); ++ fprintf(stderr,"VideoMixerNode::TimeWarp(rt=%" B_PRIdBIGTIME ",pt=%" B_PRIdBIGTIME ")\n", at_real_time, to_performance_time); + BMediaEventLooper::TimeWarp(at_real_time, to_performance_time); + } + +@@ -305,8 +305,8 @@ void VideoMixerNode::GetFlavor(flavor_info *outInfo, int32 id) + + if (outInfo != NULL) { + outInfo->internal_id = id; +- strcpy(outInfo->name, "Haiku VideoMixer"); +- strcpy(outInfo->info, "A VideoMixerNode node mixes multiple video" ++ outInfo->name = strdup("Haiku VideoMixer"); ++ outInfo->info = strdup("A VideoMixerNode node mixes multiple video" + " streams into a single stream."); + outInfo->kinds = B_BUFFER_CONSUMER | B_BUFFER_PRODUCER; + outInfo->flavor_flags = B_FLAVOR_IS_LOCAL; +diff --git a/src/add-ons/media/media-add-ons/video_mixer/VideoMixerNodeConsumer.cpp b/src/add-ons/media/media-add-ons/video_mixer/VideoMixerNodeConsumer.cpp +index 9fbedb45c6..90e937efd1 100644 +--- a/src/add-ons/media/media-add-ons/video_mixer/VideoMixerNodeConsumer.cpp ++++ b/src/add-ons/media/media-add-ons/video_mixer/VideoMixerNodeConsumer.cpp +@@ -45,7 +45,7 @@ status_t VideoMixerNode::GetNextInput( + int32 *cookie, + media_input *out_input) + { +- fprintf(stderr,"VideoMixerNode(BBufferConsumer)::GetNextInput (%ld)\n",*cookie); ++ fprintf(stderr,"VideoMixerNode(BBufferConsumer)::GetNextInput (%" B_PRId32 ")\n",*cookie); + + // Cookie 0 is the connecting input, all others are connected inputs + if (uint32(*cookie) == fConnectedInputs.size()) { +@@ -168,7 +168,7 @@ status_t VideoMixerNode::Connected( + + // compute the latency or just guess + fInternalLatency = 500; // just a guess +- fprintf(stderr," internal latency guessed = %lld\n", fInternalLatency); ++ fprintf(stderr," internal latency guessed = %" B_PRIdBIGTIME "\n", fInternalLatency); + + SetEventLatency(fInternalLatency); + +diff --git a/src/add-ons/media/media-add-ons/video_mixer/VideoMixerNodeEventLooper.cpp b/src/add-ons/media/media-add-ons/video_mixer/VideoMixerNodeEventLooper.cpp +index c2c4be104d..f6424c7b7e 100644 +--- a/src/add-ons/media/media-add-ons/video_mixer/VideoMixerNodeEventLooper.cpp ++++ b/src/add-ons/media/media-add-ons/video_mixer/VideoMixerNodeEventLooper.cpp +@@ -49,7 +49,7 @@ void VideoMixerNode::HandleEvent( + HandleParameter(event,lateness,realTimeEvent); + break; + default: +- fprintf(stderr," unknown event type: %ld\n",event->type); ++ fprintf(stderr," unknown event type: %" B_PRId32 "\n",event->type); + break; + } + } +@@ -99,7 +99,7 @@ status_t VideoMixerNode::HandleSeek( + bigtime_t lateness, + bool realTimeEvent) + { +- fprintf(stderr,"VideoMixerNode(BMediaEventLooper)::HandleSeek(t=%lld,d=%ld,bd=%lld)\n",event->event_time, event->data, event->bigdata); ++ fprintf(stderr,"VideoMixerNode(BMediaEventLooper)::HandleSeek(t=%" B_PRIdBIGTIME ",d=%" B_PRId32 ",bd=%" B_PRId64 ")\n",event->event_time, event->data, event->bigdata); + return B_OK; + } + +diff --git a/src/add-ons/media/media-add-ons/video_mixer/VideoMixerNodeProducer.cpp b/src/add-ons/media/media-add-ons/video_mixer/VideoMixerNodeProducer.cpp +index 8fa016b462..39ae8f8666 100644 +--- a/src/add-ons/media/media-add-ons/video_mixer/VideoMixerNodeProducer.cpp ++++ b/src/add-ons/media/media-add-ons/video_mixer/VideoMixerNodeProducer.cpp +@@ -99,7 +99,7 @@ status_t VideoMixerNode::GetNextOutput( /* cookie starts as 0 */ + int32 *cookie, + media_output *out_output) + { +- fprintf(stderr,"VideoMixerNode(BBufferProducer)::GetNextOutput (%ld)\n",*cookie); ++ fprintf(stderr,"VideoMixerNode(BBufferProducer)::GetNextOutput (%" B_PRId32 ")\n",*cookie); + + // only 1 output + if (*cookie != 0) { +@@ -240,7 +240,7 @@ void VideoMixerNode::Connect( + void VideoMixerNode::ComputeInternalLatency() { + fprintf(stderr,"VideoMixerNode(BBufferProducer)::ComputeInternalLatency\n"); + fInternalLatency = 100; // just guess +- fprintf(stderr," internal latency guessed = %lld\n",fInternalLatency); ++ fprintf(stderr," internal latency guessed = %" B_PRIdBIGTIME "\n",fInternalLatency); + } + + void VideoMixerNode::Disconnect( +-- +2.30.2 + diff --git a/patchset-hrev55144/0015-libbe_test-fix-Tracker-crash-and-mouse-click-behavio.patch b/patchset-hrev55144/0015-libbe_test-fix-Tracker-crash-and-mouse-click-behavio.patch new file mode 100644 index 0000000..ed3a01f --- /dev/null +++ b/patchset-hrev55144/0015-libbe_test-fix-Tracker-crash-and-mouse-click-behavio.patch @@ -0,0 +1,29 @@ +From 79aa443f4eac6652e08edaf5b4c332cd42e29c6a Mon Sep 17 00:00:00 2001 +From: X512 +Date: Tue, 14 Jul 2020 21:42:08 +0900 +Subject: libbe_test: fix Tracker crash and mouse click behavior + +Change-Id: Idc00cb3c9c72240b942ef27cb0091f36268410bc +--- + src/kits/interface/InterfaceDefs.cpp | 5 +---- + 1 file changed, 1 insertion(+), 4 deletions(-) + +diff --git a/src/kits/interface/InterfaceDefs.cpp b/src/kits/interface/InterfaceDefs.cpp +index 67bfc8ee3f..8c08bd3ac7 100644 +--- a/src/kits/interface/InterfaceDefs.cpp ++++ b/src/kits/interface/InterfaceDefs.cpp +@@ -579,10 +579,7 @@ get_click_speed(bigtime_t *speed) + BMessage reply; + + status_t err = _control_input_server_(&command, &reply); +- if (err != B_OK) +- return err; +- +- if (reply.FindInt64("speed", speed) != B_OK) ++ if (err != B_OK || reply.FindInt64("speed", speed) != B_OK) + *speed = 500000; + + return B_OK; +-- +2.30.2 + diff --git a/patchset-hrev55144/0016-Interface-kit-rewrite-menu-logic-by-using-input-even.patch b/patchset-hrev55144/0016-Interface-kit-rewrite-menu-logic-by-using-input-even.patch new file mode 100644 index 0000000..333883f --- /dev/null +++ b/patchset-hrev55144/0016-Interface-kit-rewrite-menu-logic-by-using-input-even.patch @@ -0,0 +1,2024 @@ +From 3502f043513d0e197e7267615cb2423441d4aed5 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Fri, 24 Jan 2020 08:30:48 +0900 +Subject: Interface kit: rewrite menu logic by using input events + +WIP, DON'T MERGE + +Keyboard navigation is implemented: +* Alt+Esc opens menu. +* Arrow keys are used to move to previous/next item and enter/leave submenu. +* Character key invoke or enter item with underlined character. +* Enter invoke menu, Esc leave current menu. + +TODO: +* Fix freeze when dymanically building submenu. +* Implement navigation area timeout. +* Menu is still sometimes displayed when not ready. + +Fixes #1621, #3259, #4335, #7182. + +Change-Id: Ia693570e9bf4cbea33cd7d71bd5e7249c089959f +--- + headers/os/interface/Menu.h | 27 +- + headers/private/interface/MenuPrivate.h | 35 +- + headers/private/interface/MenuWindow.h | 2 - + src/kits/interface/BMCPrivate.cpp | 6 + + src/kits/interface/Menu.cpp | 929 +++++++++++++----------- + src/kits/interface/MenuBar.cpp | 140 +--- + src/kits/interface/MenuField.cpp | 7 +- + src/kits/interface/MenuPrivate.cpp | 6 +- + src/kits/interface/MenuWindow.cpp | 137 ++-- + src/kits/interface/PopUpMenu.cpp | 10 - + 10 files changed, 677 insertions(+), 622 deletions(-) + +diff --git a/headers/os/interface/Menu.h b/headers/os/interface/Menu.h +index 017cbe0242..625287701f 100644 +--- a/headers/os/interface/Menu.h ++++ b/headers/os/interface/Menu.h +@@ -17,6 +17,7 @@ class BMenuItem; + + + namespace BPrivate { ++ class MenuTrackState; + class BMenuWindow; + class ExtraMenuData; + class TriggerList; +@@ -188,10 +189,9 @@ private: + BMenu& operator=(const BMenu& other); + + void _InitData(BMessage* archive); +- bool _Show(bool selectFirstItem = false, +- bool keyDown = false); ++ bool _Show(bool selectFirstItem = false); + void _Hide(); +- BMenuItem* _Track(int* action, long start = -1); ++ BMenuItem* _Track(int32* action, int32 start = -1); + void _ScriptReceived(BMessage* message); + void _ItemScriptReceived(BMessage* message, + BMenuItem* item); +@@ -206,14 +206,12 @@ private: + BRect& navAreaRectAbove, + BRect& navAreaBelow); + ++ bool _HitNavigationArea(BPoint position, BMenuItem* item); ++ + void _UpdateStateOpenSelect(BMenuItem* item, + BPoint position, BRect& navAreaRectAbove, + BRect& navAreaBelow, +- bigtime_t& selectedTime, +- bigtime_t& navigationAreaTime); +- void _UpdateStateClose(BMenuItem* item, +- const BPoint& where, +- const uint32& buttons); ++ bool isTimeout); + + bool _AddItem(BMenuItem* item, int32 index); + bool _RemoveItems(int32 index, int32 count, +@@ -250,8 +248,7 @@ private: + void _Uninstall(); + void _SelectItem(BMenuItem* item, + bool showSubmenu = true, +- bool selectFirstItem = false, +- bool keyDown = false); ++ bool selectFirstItem = false); + bool _SelectNextItem(BMenuItem* item, bool forward); + BMenuItem* _NextItem(BMenuItem* item, bool forward) const; + void _SetIgnoreHidden(bool ignoreHidden) +@@ -271,13 +268,11 @@ private: + uint32& trigger, + BPrivate::TriggerList& triggers); + void _UpdateWindowViewSize(const bool &updatePosition); +- bool _AddDynamicItems(bool keyDown = false); +- bool _OkToProceed(BMenuItem* item, +- bool keyDown = false); ++ bool _AddDynamicItems(); ++ bool _OkToProceed(BMenuItem* item); + +- bool _CustomTrackingWantsToQuit(); ++ void _CallTrackingHook(); + +- int _State(BMenuItem** _item = NULL) const; + void _InvokeItem(BMenuItem* item, bool now = false); + void _QuitTracking(bool onlyThis = true); + +@@ -291,7 +286,7 @@ private: + static uint32 sCommandKey; + static uint32 sMenuKey; + +- BMenuItem* fChosenItem; ++ BPrivate::MenuTrackState* fTrackState; + BList fItems; + BRect fPad; + BMenuItem* fSelected; +diff --git a/headers/private/interface/MenuPrivate.h b/headers/private/interface/MenuPrivate.h +index 4627b701ed..64bf3f2359 100644 +--- a/headers/private/interface/MenuPrivate.h ++++ b/headers/private/interface/MenuPrivate.h +@@ -11,14 +11,18 @@ + + + #include ++#include ++#include + ++#include + +-enum menu_states { +- MENU_STATE_TRACKING = 0, +- MENU_STATE_TRACKING_SUBMENU = 1, +- MENU_STATE_KEY_TO_SUBMENU = 2, +- MENU_STATE_KEY_LEAVE_SUBMENU = 3, +- MENU_STATE_CLOSED = 5 ++ ++enum menu_track_command { ++ MENU_TRACK_CMD_DONE ++}; ++ ++enum { ++ navigationAreaTimeoutMsg = 'nvat', + }; + + +@@ -48,7 +52,7 @@ public: + const; + void SetItemMargins(float, float, float, float); + +- int State(BMenuItem** item = NULL) const; ++ bool IsTracking() const; + + void Install(BWindow* window); + void Uninstall(); +@@ -78,6 +82,23 @@ private: + + }; + ++struct MenuTrackState { ++ thread_id trackThread; ++ BLocker locker; ++ bool quit; ++ BMenu* rootMenu; ++ BMenu* curMenu; ++ BMenu* cursorMenu; // menu that holding pointer event mask ++ BMenuItem* invokedItem; ++ bool cursorInside, cursorObscured; ++ BPoint clickPoint, enterPoint; ++ BRect navAreaRectAbove; ++ BRect navAreaRectBelow; ++ bigtime_t selectedTime; ++ bigtime_t navigationAreaTime; ++ ObjectDeleter navigationAreaTimer; ++}; ++ + }; // namespace BPrivate + + +diff --git a/headers/private/interface/MenuWindow.h b/headers/private/interface/MenuWindow.h +index eb1b943c9d..c409bd4c54 100644 +--- a/headers/private/interface/MenuWindow.h ++++ b/headers/private/interface/MenuWindow.h +@@ -38,12 +38,10 @@ public: + void SetSmallStep(float step); + void GetSteps(float* _smallStep, float* _largeStep) const; + bool HasScrollers() const; +- bool CheckForScrolling(const BPoint& cursor); + bool TryScrollBy(const float& step); + bool TryScrollTo(const float& where); + + private: +- bool _Scroll(const BPoint& cursor); + void _ScrollBy(const float& step); + + BMenu* fMenu; +diff --git a/src/kits/interface/BMCPrivate.cpp b/src/kits/interface/BMCPrivate.cpp +index 6e6ca327e4..537cb00c33 100644 +--- a/src/kits/interface/BMCPrivate.cpp ++++ b/src/kits/interface/BMCPrivate.cpp +@@ -21,6 +21,8 @@ + #include + #include + ++#include ++ + + static const float kPopUpIndicatorWidth = 13.0f; + +@@ -76,6 +78,10 @@ _BMCFilter_::~_BMCFilter_() + filter_result + _BMCFilter_::Filter(BMessage* message, BHandler** handler) + { ++ BPrivate::MenuPrivate menuPrivate(fMenuField->MenuBar()); ++ if (menuPrivate.IsTracking()) ++ return B_DISPATCH_MESSAGE; ++ + if (message->what == B_MOUSE_DOWN) { + if (BView* view = dynamic_cast(*handler)) { + BPoint point; +diff --git a/src/kits/interface/Menu.cpp b/src/kits/interface/Menu.cpp +index 04bd3b5acc..9235564acd 100644 +--- a/src/kits/interface/Menu.cpp ++++ b/src/kits/interface/Menu.cpp +@@ -39,6 +39,7 @@ + #include + #include + #include ++#include + + #include + #include +@@ -53,6 +54,8 @@ + + #define USE_CACHED_MENUWINDOW 1 + ++#define SHOW_NAVIGATION_AREA 0 ++ + using BPrivate::gSystemCatalog; + + #undef B_TRANSLATION_CONTEXT +@@ -227,7 +230,7 @@ struct BMenu::LayoutData { + BMenu::BMenu(const char* name, menu_layout layout) + : + BView(BRect(0, 0, 0, 0), name, 0, B_WILL_DRAW), +- fChosenItem(NULL), ++ fTrackState(NULL), + fSelected(NULL), + fCachedMenuWindow(NULL), + fSuper(NULL), +@@ -235,7 +238,6 @@ BMenu::BMenu(const char* name, menu_layout layout) + fAscent(-1.0f), + fDescent(-1.0f), + fFontHeight(-1.0f), +- fState(MENU_STATE_CLOSED), + fLayout(layout), + fExtraRect(NULL), + fMaxContentWidth(0.0f), +@@ -264,7 +266,7 @@ BMenu::BMenu(const char* name, menu_layout layout) + BMenu::BMenu(const char* name, float width, float height) + : + BView(BRect(0.0f, 0.0f, 0.0f, 0.0f), name, 0, B_WILL_DRAW), +- fChosenItem(NULL), ++ fTrackState(NULL), + fPad(14.0f, 2.0f, 20.0f, 0.0f), + fSelected(NULL), + fCachedMenuWindow(NULL), +@@ -273,7 +275,6 @@ BMenu::BMenu(const char* name, float width, float height) + fAscent(-1.0f), + fDescent(-1.0f), + fFontHeight(-1.0f), +- fState(0), + fLayout(B_ITEMS_IN_MATRIX), + fExtraRect(NULL), + fMaxContentWidth(0.0f), +@@ -299,7 +300,7 @@ BMenu::BMenu(const char* name, float width, float height) + BMenu::BMenu(BMessage* archive) + : + BView(archive), +- fChosenItem(NULL), ++ fTrackState(NULL), + fPad(14.0f, 2.0f, 20.0f, 0.0f), + fSelected(NULL), + fCachedMenuWindow(NULL), +@@ -308,7 +309,6 @@ BMenu::BMenu(BMessage* archive) + fAscent(-1.0f), + fDescent(-1.0f), + fFontHeight(-1.0f), +- fState(MENU_STATE_CLOSED), + fLayout(B_ITEMS_IN_ROW), + fExtraRect(NULL), + fMaxContentWidth(0.0f), +@@ -402,14 +402,7 @@ BMenu::AttachedToWindow() + _GetOptionKey(sOptionKey); + _GetMenuKey(sMenuKey); + +- // The menu should be added to the menu hierarchy and made visible if: +- // * the mouse is over the menu, +- // * the user has requested the menu via the keyboard. +- // So if we don't pass keydown in here, keyboard navigation breaks since +- // fAttachAborted will return false if the mouse isn't over the menu +- bool keyDown = Supermenu() != NULL +- ? Supermenu()->fState == MENU_STATE_KEY_TO_SUBMENU : false; +- fAttachAborted = _AddDynamicItems(keyDown); ++ fAttachAborted = _AddDynamicItems(); + + if (!fAttachAborted) { + _CacheFontInfo(); +@@ -450,15 +443,43 @@ BMenu::Draw(BRect updateRect) + + DrawBackground(updateRect); + DrawItems(updateRect); ++ ++ #if SHOW_NAVIGATION_AREA ++ if (fTrackState != NULL) { ++ BRect above, below; ++ { ++ AutoLocker locker(fTrackState->locker); ++ above = ConvertFromScreen(fTrackState->navAreaRectAbove); ++ below = ConvertFromScreen(fTrackState->navAreaRectBelow); ++ } ++ bool isLeft = above.left == 0; ++ PushState(); ++ SetDrawingMode(B_OP_ALPHA); ++ SetHighColor(0xff, 0, 0, 0x66); ++ if (!isLeft) { ++ FillTriangle(above.LeftBottom(), above.RightTop(), above.RightBottom()); ++ FillTriangle(below.LeftTop(), below.RightBottom(), above.RightTop()); ++ } else { ++ FillTriangle(above.RightBottom(), above.LeftTop(), above.LeftBottom()); ++ FillTriangle(below.RightTop(), below.LeftBottom(), above.LeftTop()); ++ } ++ PopState(); ++ } ++ #endif + } + + ++const static bigtime_t kNavigationAreaTimeout = 1000000; ++ + void + BMenu::MessageReceived(BMessage* message) + { + if (message->HasSpecifiers()) + return _ScriptReceived(message); + ++ if (fTrackState == NULL) ++ return BView::MessageReceived(message); ++ + switch (message->what) { + case B_MOUSE_WHEEL_CHANGED: + { +@@ -485,6 +506,159 @@ BMenu::MessageReceived(BMessage* message) + break; + } + ++ case B_MOUSE_DOWN: { ++ printf("B_MOUSE_DOWN, _IsStickyMode: %d\n", _IsStickyMode()); ++ BPoint where = B_ORIGIN; ++ message->FindPoint("be:view_where", &where); ++ { ++ AutoLocker locker(fTrackState->locker); ++ if (!fTrackState->cursorInside) { ++ _QuitTracking(false); ++ BView::MessageReceived(message); ++ return; ++ } ++ } ++ if (_IsStickyMode()) ++ _SetStickyMode(false); ++ ++ _CallTrackingHook(); ++ ++ BView::MessageReceived(message); ++ break; ++ } ++ ++ case B_MOUSE_UP: { ++ printf("B_MOUSE_UP, _IsStickyMode: %d\n", _IsStickyMode()); ++ BPoint where = B_ORIGIN; ++ message->FindPoint("be:view_where", &where); ++ BMenuItem* item = _HitTestItems(where, B_ORIGIN); ++ if ( ++ !_IsStickyMode() || ( ++ !(fExtraRect != NULL && fExtraRect->Contains(where)) && ++ dynamic_cast(Window()) == NULL && ++ (item == NULL || item->Submenu() == NULL) ++ ) ++ ) { ++ if (item != NULL) _InvokeItem(item); ++ _QuitTracking(false); ++ } ++ _CallTrackingHook(); ++ BView::MessageReceived(message); ++ break; ++ } ++ ++ case B_MOUSE_MOVED: { ++ BPoint where = B_ORIGIN; ++ int32 buttons = 0; ++ int32 transit = B_OUTSIDE_VIEW; ++ ++ message->FindPoint("be:view_where", &where); ++ message->FindInt32("buttons", &buttons); ++ message->FindInt32("be:transit", &transit); ++ ++ if (fTrackState == NULL) { ++ BView::MessageReceived(message); ++ return; ++ } ++ ++ { ++ AutoLocker locker(fTrackState->locker); ++ ++ BRect checkRect(-8, -8, 8, 8); ++ checkRect.OffsetBy(fTrackState->clickPoint); ++ ++ if (_IsStickyMode() && !checkRect.Contains(ConvertToScreen(where))) { ++ printf("outside of checkRect\n"); ++ _SetStickyMode(false); ++ } ++ ++ switch (transit) { ++ case B_ENTERED_VIEW: ++ fTrackState->cursorMenu = this; ++ fTrackState->cursorMenu->SetEventMask(B_POINTER_EVENTS, 0); ++ fTrackState->cursorInside = true; ++ break; ++ case B_EXITED_VIEW: ++ if (fTrackState->cursorMenu == this) ++ fTrackState->cursorInside = false; ++ ++ if ((fSelected != NULL) && (fSelected->Submenu() == NULL)) ++ _SelectItem(NULL); ++ ++ break; ++ } ++ ++ if (fTrackState->cursorMenu != this) ++ SetEventMask(0, 0); ++ } ++ ++ switch (transit) { ++ case B_ENTERED_VIEW: ++ case B_INSIDE_VIEW: { ++ { ++ AutoLocker locker(fTrackState->locker); ++ if (fTrackState->cursorObscured) { ++ if (transit == B_ENTERED_VIEW) { ++ fTrackState->enterPoint = where; ++ break; ++ } ++ if (fTrackState->enterPoint == where) ++ break; ++ ++ fTrackState->cursorObscured = false; ++ } ++ } ++ BMenuItem* oldSelected = fSelected; ++ BMenuItem* item = _HitTestItems(where, B_ORIGIN); ++ if (item == NULL) { ++ if ((fSelected != NULL) && (fSelected->Submenu() == NULL)) ++ _SelectItem(NULL); ++ } else if (fSelected != item) { ++ if (!_HitNavigationArea(where, item)) { ++ fTrackState->navigationAreaTimer.Unset(); ++ _SelectItem(item, true); ++ } else { ++ if (fTrackState->navigationAreaTimer.Get() != NULL) ++ fTrackState->navigationAreaTimer.SetTo(new(std::nothrow) BMessageRunner(BMessenger(this), BMessage(navigationAreaTimeoutMsg), kNavigationAreaTimeout, 1)); ++ } ++ } ++ { ++ AutoLocker locker(fTrackState->locker); ++ if (oldSelected != fSelected) ++ fTrackState->curMenu = this; ++ } ++ break; ++ } ++ } ++ ++ _CallTrackingHook(); ++ ++ BView::MessageReceived(message); ++ break; ++ } ++ ++ case navigationAreaTimeoutMsg: { ++ if (fTrackState->navigationAreaTimer.Get() != NULL) { ++ fTrackState->navigationAreaTimer.Unset(); ++ BPoint where; ++ GetMouse(&where, NULL); ++ BMenuItem* oldSelected = fSelected; ++ BMenuItem* item = _HitTestItems(where, B_ORIGIN); ++ if (item == NULL) { ++ if ((fSelected != NULL) && (fSelected->Submenu() == NULL)) ++ _SelectItem(NULL); ++ } else ++ _SelectItem(item, true); ++ ++ { ++ AutoLocker locker(fTrackState->locker); ++ if (oldSelected != fSelected) ++ fTrackState->curMenu = this; ++ } ++ } ++ break; ++ } ++ + default: + BView::MessageReceived(message); + break; +@@ -495,64 +669,63 @@ BMenu::MessageReceived(BMessage* message) + void + BMenu::KeyDown(const char* bytes, int32 numBytes) + { +- // TODO: Test how it works on BeOS R5 and implement this correctly ++ if (fTrackState == NULL) ++ return; ++ ++ AutoLocker locker(fTrackState->locker); ++ ++ if (fTrackState->curMenu != this) { ++ BMessenger messenger(fTrackState->curMenu); ++ messenger.SendMessage(Window()->CurrentMessage()); ++ return; ++ } ++ ++ fTrackState->cursorObscured = true; ++ be_app->ObscureCursor(); ++ + switch (bytes[0]) { + case B_UP_ARROW: +- if (fLayout == B_ITEMS_IN_COLUMN) ++ if (fLayout == B_ITEMS_IN_COLUMN) { + _SelectNextItem(fSelected, false); ++ } else if (fLayout == B_ITEMS_IN_ROW || fLayout == B_ITEMS_IN_MATRIX) { ++ _QuitTracking(true); ++ } + break; + + case B_DOWN_ARROW: +- { +- BMenuBar* bar = dynamic_cast(Supermenu()); +- if (bar != NULL && fState == MENU_STATE_CLOSED) { +- // tell MenuBar's _Track: +- bar->fState = MENU_STATE_KEY_TO_SUBMENU; +- } +- if (fLayout == B_ITEMS_IN_COLUMN) ++ if (fLayout == B_ITEMS_IN_COLUMN) { + _SelectNextItem(fSelected, true); ++ } else if (fLayout == B_ITEMS_IN_ROW || fLayout == B_ITEMS_IN_MATRIX) { ++ if (fSelected != NULL) { ++ BMenu* subMenu = fSelected->Submenu(); ++ if (subMenu != NULL && subMenu->LockLooper()) { ++ subMenu->_SelectNextItem(subMenu->fSelected, true); ++ subMenu->UnlockLooper(); ++ fTrackState->curMenu = subMenu; ++ } ++ } ++ } + break; +- } + + case B_LEFT_ARROW: +- if (fLayout == B_ITEMS_IN_ROW) ++ if (fLayout == B_ITEMS_IN_ROW || fLayout == B_ITEMS_IN_MATRIX) { + _SelectNextItem(fSelected, false); +- else { +- // this case has to be handled a bit specially. +- BMenuItem* item = Superitem(); +- if (item) { +- if (dynamic_cast(Supermenu())) { +- // If we're at the top menu below the menu bar, pass +- // the keypress to the menu bar so we can move to +- // another top level menu. +- BMessenger messenger(Supermenu()); +- messenger.SendMessage(Window()->CurrentMessage()); +- } else { +- // tell _Track +- fState = MENU_STATE_KEY_LEAVE_SUBMENU; +- } +- } ++ } else if (fLayout == B_ITEMS_IN_COLUMN) { ++ _QuitTracking(true); + } + break; + + case B_RIGHT_ARROW: +- if (fLayout == B_ITEMS_IN_ROW) ++ if (fLayout == B_ITEMS_IN_ROW || fLayout == B_ITEMS_IN_MATRIX) { + _SelectNextItem(fSelected, true); +- else { +- if (fSelected != NULL && fSelected->Submenu() != NULL) { +- fSelected->Submenu()->_SetStickyMode(true); +- // fix me: this shouldn't be needed but dynamic menus +- // aren't getting it set correctly when keyboard +- // navigating, which aborts the attach +- fState = MENU_STATE_KEY_TO_SUBMENU; +- _SelectItem(fSelected, true, true, true); +- } else if (dynamic_cast(Supermenu())) { +- // if we have no submenu and we're an +- // item in the top menu below the menubar, +- // pass the keypress to the menubar +- // so you can use the keypress to switch menus. +- BMessenger messenger(Supermenu()); +- messenger.SendMessage(Window()->CurrentMessage()); ++ } else if (fLayout == B_ITEMS_IN_COLUMN) { ++ if (fSelected != NULL) { ++ BMenu* subMenu = fSelected->Submenu(); ++ if (subMenu != NULL && subMenu->LockLooper()) { ++ subMenu->_SelectNextItem(subMenu->fSelected, true); ++ subMenu->UnlockLooper(); ++ fTrackState->curMenu = subMenu; ++ } + } + } + break; +@@ -575,21 +748,13 @@ BMenu::KeyDown(const char* bytes, int32 numBytes) + case B_ENTER: + case B_SPACE: + if (fSelected != NULL) { +- fChosenItem = fSelected; +- // preserve for exit handling ++ _InvokeItem(fSelected); + _QuitTracking(false); + } + break; + + case B_ESCAPE: +- _SelectItem(NULL); +- if (fState == MENU_STATE_CLOSED +- && dynamic_cast(Supermenu())) { +- // Keyboard may show menu without tracking it +- BMessenger messenger(Supermenu()); +- messenger.SendMessage(Window()->CurrentMessage()); +- } else +- _QuitTracking(false); ++ _QuitTracking(false); + break; + + default: +@@ -601,8 +766,18 @@ BMenu::KeyDown(const char* bytes, int32 numBytes) + if (item->fTriggerIndex < 0 || item->fTrigger != trigger) + continue; + +- _InvokeItem(item); +- _QuitTracking(false); ++ if (item->Submenu()) { ++ _SelectItem(item, true, false); ++ BMenu* subMenu = fSelected->Submenu(); ++ if (subMenu != NULL && subMenu->LockLooper()) { ++ subMenu->_SelectNextItem(subMenu->fSelected, true); ++ subMenu->UnlockLooper(); ++ fTrackState->curMenu = subMenu; ++ } ++ } else { ++ _InvokeItem(item); ++ _QuitTracking(false); ++ } + break; + } + break; +@@ -1279,7 +1454,7 @@ BMenu::BMenu(BRect frame, const char* name, uint32 resizingMode, uint32 flags, + menu_layout layout, bool resizeToFit) + : + BView(frame, name, resizingMode, flags), +- fChosenItem(NULL), ++ fTrackState(NULL), + fSelected(NULL), + fCachedMenuWindow(NULL), + fSuper(NULL), +@@ -1287,7 +1462,6 @@ BMenu::BMenu(BRect frame, const char* name, uint32 resizingMode, uint32 flags, + fAscent(-1.0f), + fDescent(-1.0f), + fFontHeight(-1.0f), +- fState(MENU_STATE_CLOSED), + fLayout(layout), + fExtraRect(NULL), + fMaxContentWidth(0.0f), +@@ -1382,7 +1556,7 @@ BMenu::Track(bool sticky, BRect* clickToOpenRect) + + _SetStickyMode(sticky); + +- int action; ++ int32 action; + BMenuItem* menuItem = _Track(&action); + + fExtraRect = NULL; +@@ -1498,7 +1672,7 @@ BMenu::_InitData(BMessage* archive) + + + bool +-BMenu::_Show(bool selectFirstItem, bool keyDown) ++BMenu::_Show(bool selectFirstItem) + { + if (Window() != NULL) + return false; +@@ -1525,17 +1699,6 @@ BMenu::_Show(bool selectFirstItem, bool keyDown) + return false; + + if (window->Lock()) { +- bool addAborted = false; +- if (keyDown) +- addAborted = _AddDynamicItems(keyDown); +- +- if (addAborted) { +- if (ourWindow) +- window->Quit(); +- else +- window->Unlock(); +- return false; +- } + fAttachAborted = false; + + window->AttachMenu(this); +@@ -1549,6 +1712,7 @@ BMenu::_Show(bool selectFirstItem, bool keyDown) + + // Menu didn't have the time to add its items: aborting... + if (fAttachAborted) { ++ printf("fAttachAborted\n"); + window->DetachMenu(); + // TODO: Probably not needed, we can just let _hide() quit the + // window. +@@ -1562,6 +1726,11 @@ BMenu::_Show(bool selectFirstItem, bool keyDown) + _UpdateWindowViewSize(true); + window->Show(); + ++ if (Supermenu() != NULL) { ++ fTrackState = Supermenu()->fTrackState; ++ fTriggerEnabled = Supermenu()->fTriggerEnabled; ++ } ++ + if (selectFirstItem) + _SelectItem(ItemAt(0), false); + +@@ -1582,6 +1751,22 @@ BMenu::_Hide() + if (fSelected != NULL) + _SelectItem(NULL); + ++ BMenu *rootMenu = NULL; ++ if (fTrackState != NULL) { ++ AutoLocker locker(fTrackState->locker); ++ if (fTrackState->cursorMenu == this) { ++ SetEventMask(0, 0); ++ rootMenu = fTrackState->rootMenu; ++ fTrackState->cursorMenu = rootMenu; ++ } ++ } ++ if (rootMenu != NULL && rootMenu->LockLooper()) { ++ rootMenu->SetEventMask(B_POINTER_EVENTS, 0); ++ rootMenu->UnlockLooper(); ++ } ++ ++ fTrackState = NULL; ++ + window->Hide(); + window->DetachMenu(); + // we don't want to be deleted when the window is removed +@@ -1934,189 +2119,92 @@ status_t BMenu::_InsertItemAtSpecifier(const BMessage& specifier, int32 what, + // #pragma mark - mouse tracking + + +-const static bigtime_t kOpenSubmenuDelay = 0; +-const static bigtime_t kNavigationAreaTimeout = 1000000; +- +- + BMenuItem* +-BMenu::_Track(int* action, long start) ++BMenu::_Track(int32* action, int32 start) + { +- // TODO: cleanup ++ if (fTrackState != NULL) { ++ printf("Track: already entered\n"); ++ return NULL; ++ } ++ printf("+Track\n"); ++ printf("sticky: %d\n", fStickyMode); ++ if (fExtraRect != NULL) { ++ printf("extraRect: "); fExtraRect->PrintToStream(); ++ } ++ if (sMenuInfo.click_to_open) ++ _SetStickyMode(true); ++ BPrivate::MenuTrackState trackState; + BMenuItem* item = NULL; +- BRect navAreaRectAbove; +- BRect navAreaRectBelow; +- bigtime_t selectedTime = system_time(); +- bigtime_t navigationAreaTime = 0; ++ BMenuItem* startItem = ItemAt(start); ++ bool oldTriggerEnabled = fTriggerEnabled; ++ thread_id senderThread; ++ bool run = true; ++ ++ fTrackState = &trackState; ++ fTrackState->trackThread = find_thread(NULL); ++ fTrackState->quit = false; ++ fTrackState->rootMenu = this; ++ fTrackState->curMenu = this; ++ fTrackState->cursorMenu = this; ++ fTrackState->invokedItem = NULL; ++ fTrackState->cursorInside = false; ++ fTrackState->cursorObscured = false; ++ fTrackState->navAreaRectAbove = BRect(); ++ fTrackState->navAreaRectBelow = BRect(); ++ //fTrackState->navigationAreaTimer = NULL; + +- fState = MENU_STATE_TRACKING; +- fChosenItem = NULL; +- // we will use this for keyboard selection +- +- BPoint location; +- uint32 buttons = 0; + if (LockLooper()) { +- GetMouse(&location, &buttons); +- UnlockLooper(); +- } +- +- bool releasedOnce = buttons == 0; +- while (fState != MENU_STATE_CLOSED) { +- if (_CustomTrackingWantsToQuit()) +- break; +- +- if (!LockLooper()) +- break; +- +- BMenuWindow* window = static_cast(Window()); +- BPoint screenLocation = ConvertToScreen(location); +- if (window->CheckForScrolling(screenLocation)) { +- UnlockLooper(); +- continue; ++ SetEventMask(B_POINTER_EVENTS, 0); ++ BPoint where; ++ uint32 btns; ++ GetMouse(&where, &btns); ++ fTrackState->cursorInside = Bounds().Contains(where); ++ fTrackState->clickPoint = ConvertToScreen(where); ++ if (startItem == NULL) { ++ startItem = _HitTestItems(where, B_ORIGIN); + } +- +- // The order of the checks is important +- // to be able to handle overlapping menus: +- // first we check if mouse is inside a submenu, +- // then if the mouse is inside this menu, +- // then if it's over a super menu. +- if (_OverSubmenu(fSelected, screenLocation) +- || fState == MENU_STATE_KEY_TO_SUBMENU) { +- if (fState == MENU_STATE_TRACKING) { +- // not if from R.Arrow +- fState = MENU_STATE_TRACKING_SUBMENU; +- } +- navAreaRectAbove = BRect(); +- navAreaRectBelow = BRect(); +- +- // Since the submenu has its own looper, +- // we can unlock ours. Doing so also make sure +- // that our window gets any update message to +- // redraw itself +- UnlockLooper(); +- +- // To prevent NULL access violation, ensure a menu has actually +- // been selected and that it has a submenu. Because keyboard and +- // mouse interactions set selected items differently, the menu +- // tracking thread needs to be careful in triggering the navigation +- // to the submenu. +- if (fSelected != NULL) { +- BMenu* submenu = fSelected->Submenu(); +- int submenuAction = MENU_STATE_TRACKING; +- if (submenu != NULL) { +- submenu->_SetStickyMode(_IsStickyMode()); +- +- // The following call blocks until the submenu +- // gives control back to us, either because the mouse +- // pointer goes out of the submenu's bounds, or because +- // the user closes the menu +- BMenuItem* submenuItem = submenu->_Track(&submenuAction); +- if (submenuAction == MENU_STATE_CLOSED) { +- item = submenuItem; +- fState = MENU_STATE_CLOSED; +- } else if (submenuAction == MENU_STATE_KEY_LEAVE_SUBMENU) { +- if (LockLooper()) { +- BMenuItem* temp = fSelected; +- // close the submenu: +- _SelectItem(NULL); +- // but reselect the item itself for user: +- _SelectItem(temp, false); +- UnlockLooper(); +- } +- // cancel key-nav state +- fState = MENU_STATE_TRACKING; +- } else +- fState = MENU_STATE_TRACKING; +- } +- } +- if (!LockLooper()) +- break; +- } else if ((item = _HitTestItems(location, B_ORIGIN)) != NULL) { +- _UpdateStateOpenSelect(item, location, navAreaRectAbove, +- navAreaRectBelow, selectedTime, navigationAreaTime); +- releasedOnce = true; +- } else if (_OverSuper(screenLocation) +- && fSuper->fState != MENU_STATE_KEY_TO_SUBMENU) { +- fState = MENU_STATE_TRACKING; +- UnlockLooper(); +- break; +- } else if (fState == MENU_STATE_KEY_LEAVE_SUBMENU) { +- UnlockLooper(); +- break; +- } else if (fSuper == NULL +- || fSuper->fState != MENU_STATE_KEY_TO_SUBMENU) { +- // Mouse pointer outside menu: +- // If there's no other submenu opened, +- // deselect the current selected item +- if (fSelected != NULL +- && (fSelected->Submenu() == NULL +- || fSelected->Submenu()->Window() == NULL)) { +- _SelectItem(NULL); +- fState = MENU_STATE_TRACKING; +- } +- +- if (fSuper != NULL) { +- // Give supermenu the chance to continue tracking +- *action = fState; +- UnlockLooper(); +- return NULL; +- } ++ if (!oldTriggerEnabled && btns == 0) { ++ fTrackState->cursorObscured = true; ++ be_app->ObscureCursor(); ++ fTriggerEnabled = true; ++ Invalidate(); + } +- ++ _SelectItem(startItem, true, false); + UnlockLooper(); +- +- if (releasedOnce) +- _UpdateStateClose(item, location, buttons); +- +- if (fState != MENU_STATE_CLOSED) { +- bigtime_t snoozeAmount = 50000; +- +- BPoint newLocation = location; +- uint32 newButtons = buttons; +- +- // If user doesn't move the mouse, loop here, +- // so we don't interfere with keyboard menu navigation +- do { +- snooze(snoozeAmount); +- if (!LockLooper()) +- break; +- GetMouse(&newLocation, &newButtons, true); +- UnlockLooper(); +- } while (newLocation == location && newButtons == buttons +- && !(item != NULL && item->Submenu() != NULL +- && item->Submenu()->Window() == NULL) +- && fState == MENU_STATE_TRACKING); +- +- if (newLocation != location || newButtons != buttons) { +- if (!releasedOnce && newButtons == 0 && buttons != 0) +- releasedOnce = true; +- location = newLocation; +- buttons = newButtons; +- } +- +- if (releasedOnce) +- _UpdateStateClose(item, location, buttons); ++ } ++ while (run) { ++ int32 cmd = receive_data(&senderThread, NULL, 0); ++ switch (cmd) { ++ case MENU_TRACK_CMD_DONE: ++ run = false; ++ break; + } + } + +- if (action != NULL) +- *action = fState; ++ item = fTrackState->invokedItem; + +- // keyboard Enter will set this +- if (fChosenItem != NULL) +- item = fChosenItem; +- else if (fSelected == NULL) { +- // needed to cover (rare) mouse/ESC combination +- item = NULL; +- } +- +- if (fSelected != NULL && LockLooper()) { ++ if (LockLooper()) { ++ // hide submenus + _SelectItem(NULL); ++ SetEventMask(0, 0); ++ if (fTriggerEnabled != oldTriggerEnabled) { ++ fTriggerEnabled = oldTriggerEnabled; ++ Invalidate(); ++ } ++/* ++ if (fTrackState->navigationAreaTimer != NULL) { ++ delete fTrackState->navigationAreaTimer; ++ fTrackState->navigationAreaTimer = NULL; ++ } ++*/ ++ fTrackState = NULL; + UnlockLooper(); + } + + // delete the menu window recycled for all the child menus + _DeleteMenuWindow(); + ++ printf("-Track\n"); + return item; + } + +@@ -2162,16 +2250,15 @@ BMenu::_UpdateNavigationArea(BPoint position, BRect& navAreaRectAbove, + if (fSelected == NULL) + return; + +- BMenu* submenu = fSelected->Submenu(); ++ BView* submenu = fSelected->Submenu()->Parent(); + + if (submenu != NULL) { + BRect menuBounds = ConvertToScreen(Bounds()); + + BRect submenuBounds; +- if (fSelected->Submenu()->LockLooper()) { +- submenuBounds = fSelected->Submenu()->ConvertToScreen( +- fSelected->Submenu()->Bounds()); +- fSelected->Submenu()->UnlockLooper(); ++ if (submenu->LockLooper()) { ++ submenuBounds = submenu->ConvertToScreen(submenu->Bounds()); ++ submenu->UnlockLooper(); + } + + if (menuBounds.left < submenuBounds.left) { +@@ -2193,21 +2280,95 @@ BMenu::_UpdateNavigationArea(BPoint position, BRect& navAreaRectAbove, + navAreaRectAbove = BRect(); + navAreaRectBelow = BRect(); + } ++ ++ #if SHOW_NAVIGATION_AREA ++ Invalidate(); ++ #endif ++} ++ ++ ++bool ++BMenu::_HitNavigationArea(BPoint position, BMenuItem* item) ++{ ++ if (fLayout != B_ITEMS_IN_COLUMN) ++ return false; ++ ++ BRect navAreaRectAbove, navAreaRectBelow; ++ { ++ AutoLocker locker(fTrackState->locker); ++ navAreaRectAbove = fTrackState->navAreaRectAbove; ++ navAreaRectBelow = fTrackState->navAreaRectBelow; ++ } ++ ++ position = ConvertToScreen(position); ++ printf("position: "); position.PrintToStream(); ++ ++ if (!navAreaRectAbove.IsValid() && !navAreaRectBelow.IsValid() && fSelected != NULL && fSelected->Submenu() != NULL) { ++ printf("_UpdateNavigationArea\n"); ++ _UpdateNavigationArea(position, navAreaRectAbove, ++ navAreaRectBelow); ++ } ++ ++ printf("navAreaRectAbove: "); navAreaRectAbove.PrintToStream(); ++ printf("navAreaRectBelow: "); navAreaRectBelow.PrintToStream(); ++ ++ bool inNavArea = false; ++ bool inNavAreaRectAbove = navAreaRectAbove.Contains(position); ++ bool inNavAreaRectBelow = navAreaRectBelow.Contains(position); ++ ++ if (inNavAreaRectAbove || inNavAreaRectBelow) { ++ bool isLeft = ConvertFromScreen(navAreaRectAbove).left == 0; ++ BPoint p1, p2; ++ ++ if (inNavAreaRectAbove) { ++ if (!isLeft) { ++ p1 = navAreaRectAbove.LeftBottom(); ++ p2 = navAreaRectAbove.RightTop(); ++ } else { ++ p2 = navAreaRectAbove.RightBottom(); ++ p1 = navAreaRectAbove.LeftTop(); ++ } ++ } else { ++ if (!isLeft) { ++ p2 = navAreaRectBelow.LeftTop(); ++ p1 = navAreaRectBelow.RightBottom(); ++ } else { ++ p1 = navAreaRectBelow.RightTop(); ++ p2 = navAreaRectBelow.LeftBottom(); ++ } ++ } ++ inNavArea = ++ (p1.y - p2.y) * position.x + (p2.x - p1.x) * position.y ++ + (p1.x - p2.x) * p1.y + (p2.y - p1.y) * p1.x >= 0; ++ } ++ ++ printf("inNavArea: %d\n", inNavArea); ++ ++ if (!inNavArea && !(item != NULL && item->Frame().Contains(ConvertFromScreen(position)))) { ++ printf("reset nav area\n"); ++ navAreaRectAbove = BRect(); ++ navAreaRectBelow = BRect(); ++ } ++ ++ { ++ AutoLocker locker(fTrackState->locker); ++ navAreaRectAbove = fTrackState->navAreaRectAbove = navAreaRectAbove; ++ navAreaRectBelow = fTrackState->navAreaRectBelow = navAreaRectBelow; ++ } ++ ++ return inNavArea; + } + + + void + BMenu::_UpdateStateOpenSelect(BMenuItem* item, BPoint position, +- BRect& navAreaRectAbove, BRect& navAreaRectBelow, bigtime_t& selectedTime, +- bigtime_t& navigationAreaTime) ++ BRect& navAreaRectAbove, BRect& navAreaRectBelow, bool isTimeout) + { +- if (fState == MENU_STATE_CLOSED) ++ if (fLayout != B_ITEMS_IN_COLUMN) { ++ _SelectItem(item, true); + return; +- ++ } + if (item != fSelected) { +- if (navigationAreaTime == 0) +- navigationAreaTime = system_time(); +- + position = ConvertToScreen(position); + + bool inNavAreaRectAbove = navAreaRectAbove.Contains(position); +@@ -2215,11 +2376,13 @@ BMenu::_UpdateStateOpenSelect(BMenuItem* item, BPoint position, + + if (fSelected == NULL + || (!inNavAreaRectAbove && !inNavAreaRectBelow)) { +- _SelectItem(item, false); ++ _SelectItem(item, true); + navAreaRectAbove = BRect(); + navAreaRectBelow = BRect(); +- selectedTime = system_time(); +- navigationAreaTime = 0; ++ { ++ AutoLocker locker(fTrackState->locker); ++ fTrackState->navigationAreaTimer.Unset(); ++ } + return; + } + +@@ -2247,13 +2410,8 @@ BMenu::_UpdateStateOpenSelect(BMenuItem* item, BPoint position, + (p1.y - p2.y) * position.x + (p2.x - p1.x) * position.y + + (p1.x - p2.x) * p1.y + (p2.y - p1.y) * p1.x >= 0; + +- bigtime_t systime = system_time(); +- +- if (!inNavArea || (navigationAreaTime > 0 && systime - +- navigationAreaTime > kNavigationAreaTimeout)) { +- // Don't delay opening of submenu if the user had +- // to wait for the navigation area timeout anyway +- _SelectItem(item, inNavArea); ++ if (!inNavArea || isTimeout) { ++ _SelectItem(item, true); + + if (inNavArea) { + _UpdateNavigationArea(position, navAreaRectAbove, +@@ -2263,11 +2421,18 @@ BMenu::_UpdateStateOpenSelect(BMenuItem* item, BPoint position, + navAreaRectBelow = BRect(); + } + +- selectedTime = system_time(); +- navigationAreaTime = 0; ++ { ++ AutoLocker locker(fTrackState->locker); ++ fTrackState->navigationAreaTimer.Unset(); ++ } + } +- } else if (fSelected->Submenu() != NULL && +- system_time() - selectedTime > kOpenSubmenuDelay) { ++ } else if (fSelected->Submenu() != NULL) { ++ { ++ AutoLocker locker(fTrackState->locker); ++ BMessage message(navigationAreaTimeoutMsg); ++ fTrackState->navigationAreaTimer.SetTo(new(std::nothrow) BMessageRunner(BMessenger(this), BMessage(navigationAreaTimeoutMsg), kNavigationAreaTimeout, 1)); ++ } ++ + _SelectItem(fSelected, true); + + if (!navAreaRectAbove.IsValid() && !navAreaRectBelow.IsValid()) { +@@ -2276,42 +2441,6 @@ BMenu::_UpdateStateOpenSelect(BMenuItem* item, BPoint position, + navAreaRectBelow); + } + } +- +- if (fState != MENU_STATE_TRACKING) +- fState = MENU_STATE_TRACKING; +-} +- +- +-void +-BMenu::_UpdateStateClose(BMenuItem* item, const BPoint& where, +- const uint32& buttons) +-{ +- if (fState == MENU_STATE_CLOSED) +- return; +- +- if (buttons != 0 && _IsStickyMode()) { +- if (item == NULL) { +- if (item != fSelected && LockLooper()) { +- _SelectItem(item, false); +- UnlockLooper(); +- } +- fState = MENU_STATE_CLOSED; +- } else +- _SetStickyMode(false); +- } else if (buttons == 0 && !_IsStickyMode()) { +- if (fExtraRect != NULL && fExtraRect->Contains(where)) { +- _SetStickyMode(true); +- fExtraRect = NULL; +- // Setting this to NULL will prevent this code +- // to be executed next time +- } else { +- if (item != fSelected && LockLooper()) { +- _SelectItem(item, false); +- UnlockLooper(); +- } +- fState = MENU_STATE_CLOSED; +- } +- } + } + + +@@ -2691,7 +2820,7 @@ BMenu::ScreenLocation() + + BPoint point; + if (superMenu->Layout() == B_ITEMS_IN_COLUMN) +- point = superItem->Frame().RightTop() + BPoint(1.0f, 1.0f); ++ point = superItem->Frame().RightTop() + BPoint(1.0f, 0.0f); + else + point = superItem->Frame().LeftBottom() + BPoint(1.0f, 1.0f); + +@@ -2791,29 +2920,41 @@ BMenu::DrawItems(BRect updateRect) + } + + +-int +-BMenu::_State(BMenuItem** item) const +-{ +- if (fState == MENU_STATE_TRACKING || fState == MENU_STATE_CLOSED) +- return fState; +- +- if (fSelected != NULL && fSelected->Submenu() != NULL) +- return fSelected->Submenu()->_State(item); +- +- return fState; +-} +- +- + void + BMenu::_InvokeItem(BMenuItem* item, bool now) + { + if (!item->IsEnabled()) + return; + ++ // called from BWindow for shortcut handling ++ if (now) { ++ // Lock the root menu window before calling BMenuItem::Invoke() ++ BMenu* parent = this; ++ BMenu* rootMenu = NULL; ++ do { ++ rootMenu = parent; ++ parent = rootMenu->Supermenu(); ++ } while (parent != NULL); ++ ++ if (rootMenu->LockLooper()) { ++ item->Invoke(); ++ rootMenu->UnlockLooper(); ++ } ++ return; ++ } ++ ++ { ++ if (fTrackState == NULL) ++ return; ++ AutoLocker locker(fTrackState->locker); ++ if (fTrackState->invokedItem != NULL) ++ return; ++ fTrackState->invokedItem = item; ++ } ++ + // Do the "selected" animation +- // TODO: Doesn't work. This is supposed to highlight +- // and dehighlight the item, works on beos but not on haiku. +- if (!item->Submenu() && LockLooper()) { ++ #if 0 ++ if (LockLooper()) { + snooze(50000); + item->Select(true); + Window()->UpdateIfNeeded(); +@@ -2828,19 +2969,7 @@ BMenu::_InvokeItem(BMenuItem* item, bool now) + Window()->UpdateIfNeeded(); + UnlockLooper(); + } +- +- // Lock the root menu window before calling BMenuItem::Invoke() +- BMenu* parent = this; +- BMenu* rootMenu = NULL; +- do { +- rootMenu = parent; +- parent = rootMenu->Supermenu(); +- } while (parent != NULL); +- +- if (rootMenu->LockLooper()) { +- item->Invoke(); +- rootMenu->UnlockLooper(); +- } ++ #endif + } + + +@@ -2970,8 +3099,7 @@ BMenu::_Uninstall() + + + void +-BMenu::_SelectItem(BMenuItem* item, bool showSubmenu, bool selectFirstItem, +- bool keyDown) ++BMenu::_SelectItem(BMenuItem* item, bool showSubmenu, bool selectFirstItem) + { + // Avoid deselecting and then reselecting the same item + // which would cause flickering +@@ -2984,15 +3112,27 @@ BMenu::_SelectItem(BMenuItem* item, bool showSubmenu, bool selectFirstItem, + } + + fSelected = item; +- if (fSelected != NULL) ++ if (fSelected != NULL) { ++ BMenuWindow* window = dynamic_cast(Window()); ++ if (window != NULL && window->LockLooper()) { ++ BRect frame = ConvertToParent(fSelected->Frame()); ++ float height = Parent()->Bounds().Height(); ++ if (frame.top < 0) ++ window->TryScrollBy(frame.top); ++ else if (frame.bottom > height) ++ window->TryScrollBy(frame.bottom - height); ++ window->UnlockLooper(); ++ } + fSelected->Select(true); ++ } + } + + if (fSelected != NULL && showSubmenu) { + BMenu* subMenu = fSelected->Submenu(); + if (subMenu != NULL && subMenu->Window() == NULL) { +- if (!subMenu->_Show(selectFirstItem, keyDown)) { ++ if (!subMenu->_Show(selectFirstItem)) { + // something went wrong, deselect the item ++ printf("_SelectItem: can't show submenu\n"); + fSelected->Select(false); + fSelected = NULL; + } +@@ -3011,7 +3151,7 @@ BMenu::_SelectNextItem(BMenuItem* item, bool forward) + if (nextItem == NULL) + return false; + +- _SelectItem(nextItem, dynamic_cast(this) != NULL); ++ _SelectItem(nextItem, true, false); + + if (LockLooper()) { + be_app->ObscureCursor(); +@@ -3031,7 +3171,7 @@ BMenu::_NextItem(BMenuItem* item, bool forward) const + + int32 index = fItems.IndexOf(item); + int32 loopCount = numItems; +- while (--loopCount) { ++ while (loopCount--) { + // Cycle through menu items in the given direction... + if (forward) + index++; +@@ -3058,32 +3198,23 @@ BMenu::_NextItem(BMenuItem* item, bool forward) const + void + BMenu::_SetStickyMode(bool sticky) + { +- if (fStickyMode == sticky) ++ if (fTrackState == NULL) { ++ fStickyMode = sticky; + return; +- +- fStickyMode = sticky; +- +- if (fSuper != NULL) { +- // propagate the status to the super menu +- fSuper->_SetStickyMode(sticky); +- } else { +- // TODO: Ugly hack, but it needs to be done in this method +- BMenuBar* menuBar = dynamic_cast(this); +- if (sticky && menuBar != NULL && menuBar->LockLooper()) { +- // If we are switching to sticky mode, +- // steal the focus from the current focus view +- // (needed to handle keyboard navigation) +- menuBar->_StealFocus(); +- menuBar->UnlockLooper(); +- } + } ++ AutoLocker locker(fTrackState->locker); ++ fTrackState->rootMenu->fStickyMode = sticky; + } + + + bool + BMenu::_IsStickyMode() const + { +- return fStickyMode; ++ if (fTrackState == NULL) { ++ return fStickyMode; ++ } ++ AutoLocker locker(fTrackState->locker); ++ return fTrackState->rootMenu->fStickyMode; + } + + +@@ -3226,13 +3357,10 @@ BMenu::_ChooseTrigger(const char* title, int32& index, uint32& trigger, + void + BMenu::_UpdateWindowViewSize(const bool &move) + { +- BMenuWindow* window = static_cast(Window()); ++ BMenuWindow* window = dynamic_cast(Window()); + if (window == NULL) + return; + +- if (dynamic_cast(this) != NULL) +- return; +- + if (!fResizeToFit) + return; + +@@ -3293,15 +3421,17 @@ BMenu::_UpdateWindowViewSize(const bool &move) + + + bool +-BMenu::_AddDynamicItems(bool keyDown) ++BMenu::_AddDynamicItems() + { ++ printf("_AddDynamicItems(%p)\n", this); + bool addAborted = false; + if (AddDynamicItem(B_INITIAL_ADD)) { + BMenuItem* superItem = Superitem(); + BMenu* superMenu = Supermenu(); + do { ++ //printf("_AddDynamicItems: step\n"); + if (superMenu != NULL +- && !superMenu->_OkToProceed(superItem, keyDown)) { ++ && !superMenu->_OkToProceed(superItem)) { + AddDynamicItem(B_ABORT); + addAborted = true; + break; +@@ -3314,66 +3444,41 @@ BMenu::_AddDynamicItems(bool keyDown) + + + bool +-BMenu::_OkToProceed(BMenuItem* item, bool keyDown) +-{ +- BPoint where; +- uint32 buttons; +- GetMouse(&where, &buttons, false); +- bool stickyMode = _IsStickyMode(); +- // Quit if user clicks the mouse button in sticky mode +- // or releases the mouse button in nonsticky mode +- // or moves the pointer over another item +- // TODO: I added the check for BMenuBar to solve a problem with Deskbar. +- // BeOS seems to do something similar. This could also be a bug in +- // Deskbar, though. +- if ((buttons != 0 && stickyMode) +- || ((dynamic_cast(this) == NULL +- && (buttons == 0 && !stickyMode)) +- || ((_HitTestItems(where) != item) && !keyDown))) { +- return false; +- } +- +- return true; ++BMenu::_OkToProceed(BMenuItem* item) ++{ ++ return true; /* !!! */ + } + + +-bool +-BMenu::_CustomTrackingWantsToQuit() ++void ++BMenu::_CallTrackingHook() + { + if (fExtraMenuData != NULL && fExtraMenuData->trackingHook != NULL + && fExtraMenuData->trackingState != NULL) { +- return fExtraMenuData->trackingHook(this, +- fExtraMenuData->trackingState); ++ if (fExtraMenuData->trackingHook(this, fExtraMenuData->trackingState)) ++ _QuitTracking(true); + } +- +- return false; + } + + + void + BMenu::_QuitTracking(bool onlyThis) + { +- _SelectItem(NULL); +- if (BMenuBar* menuBar = dynamic_cast(this)) +- menuBar->_RestoreFocus(); +- +- fState = MENU_STATE_CLOSED; +- +- if (!onlyThis) { +- // Close the whole menu hierarchy +- if (Supermenu() != NULL) +- Supermenu()->fState = MENU_STATE_CLOSED; ++ if (fTrackState == NULL) ++ return; + +- if (_IsStickyMode()) +- _SetStickyMode(false); ++ AutoLocker locker(fTrackState->locker); + +- if (LockLooper()) { +- be_app->ShowCursor(); +- UnlockLooper(); +- } ++ if (onlyThis && Supermenu() != NULL) { ++ _SelectItem(NULL); ++ fTrackState->curMenu = Supermenu(); ++ return; + } + +- _Hide(); ++ if (!fTrackState->quit) { ++ fTrackState->quit = true; ++ send_data(fTrackState->trackThread, MENU_TRACK_CMD_DONE, NULL, 0); ++ } + } + + +diff --git a/src/kits/interface/MenuBar.cpp b/src/kits/interface/MenuBar.cpp +index 6a07dd23c4..91442206f2 100644 +--- a/src/kits/interface/MenuBar.cpp ++++ b/src/kits/interface/MenuBar.cpp +@@ -173,6 +173,9 @@ BMenuBar::AllDetached() + void + BMenuBar::WindowActivated(bool state) + { ++ if (!state) { ++ BPrivate::MenuPrivate(this).QuitTracking(false); ++ } + BView::WindowActivated(state); + } + +@@ -550,152 +553,32 @@ BMenuBar::_TrackTask(void* arg) + BMenuItem* + BMenuBar::_Track(int32* action, int32 startIndex, bool showMenu) + { +- // TODO: Cleanup, merge some "if" blocks if possible + BMenuItem* item = NULL; +- fState = MENU_STATE_TRACKING; +- fChosenItem = NULL; +- // we will use this for keyboard selection + +- BPoint where; +- uint32 buttons; ++ if (startIndex == -1 && showMenu) ++ startIndex = 0; ++ + if (LockLooper()) { +- if (startIndex != -1) { +- be_app->ObscureCursor(); +- _SelectItem(ItemAt(startIndex), true, false); +- } +- GetMouse(&where, &buttons); ++ _StealFocus(); + UnlockLooper(); + } + +- while (fState != MENU_STATE_CLOSED) { +- bigtime_t snoozeAmount = 40000; +- if (!LockLooper()) +- break; +- +- item = dynamic_cast<_BMCMenuBar_*>(this) != NULL ? ItemAt(0) +- : _HitTestItems(where, B_ORIGIN); +- +- if (_OverSubmenu(fSelected, ConvertToScreen(where)) +- || fState == MENU_STATE_KEY_TO_SUBMENU) { +- // call _Track() from the selected sub-menu when the mouse cursor +- // is over its window +- BMenu* submenu = fSelected->Submenu(); +- UnlockLooper(); +- snoozeAmount = 30000; +- submenu->_SetStickyMode(_IsStickyMode()); +- int localAction; +- fChosenItem = submenu->_Track(&localAction); +- +- // The mouse could have meen moved since the last time we +- // checked its position, or buttons might have been pressed. +- // Unfortunately our child menus don't tell +- // us the new position. +- // TODO: Maybe have a shared struct between all menus +- // where to store the current mouse position ? +- // (Or just use the BView mouse hooks) +- BPoint newWhere; +- if (LockLooper()) { +- GetMouse(&newWhere, &buttons); +- UnlockLooper(); +- } +- +- // Needed to make BMenuField child menus "sticky" +- // (see ticket #953) +- if (localAction == MENU_STATE_CLOSED) { +- if (fExtraRect != NULL && fExtraRect->Contains(where) +- && point_distance(newWhere, where) < 9) { +- // 9 = 3 pixels ^ 2 (since point_distance() returns the +- // square of the distance) +- _SetStickyMode(true); +- fExtraRect = NULL; +- } else +- fState = MENU_STATE_CLOSED; +- } +- if (!LockLooper()) +- break; +- } else if (item != NULL) { +- if (item->Submenu() != NULL && item != fSelected) { +- if (item->Submenu()->Window() == NULL) { +- // open the menu if it's not opened yet +- _SelectItem(item); +- } else { +- // Menu was already opened, close it and bail +- _SelectItem(NULL); +- fState = MENU_STATE_CLOSED; +- fChosenItem = NULL; +- } +- } else { +- // No submenu, just select the item +- _SelectItem(item); +- } +- } else if (item == NULL && fSelected != NULL +- && !_IsStickyMode() && Bounds().Contains(where)) { +- _SelectItem(NULL); +- fState = MENU_STATE_TRACKING; +- } +- +- UnlockLooper(); +- +- if (fState != MENU_STATE_CLOSED) { +- BPoint newWhere = where; +- uint32 newButtons = buttons; +- +- do { +- // If user doesn't move the mouse or change buttons loop +- // here so that we don't interfere with keyboard menu +- // navigation +- snooze(snoozeAmount); +- if (!LockLooper()) +- break; +- +- GetMouse(&newWhere, &newButtons); +- UnlockLooper(); +- } while (newWhere == where && newButtons == buttons +- && fState == MENU_STATE_TRACKING); +- +- if (newButtons != 0 && _IsStickyMode()) { +- if (item == NULL || (item->Submenu() != NULL +- && item->Submenu()->Window() != NULL)) { +- // clicked outside the menu bar or on item with already +- // open sub menu +- fState = MENU_STATE_CLOSED; +- } else +- _SetStickyMode(false); +- } else if (newButtons == 0 && !_IsStickyMode()) { +- if ((fSelected != NULL && fSelected->Submenu() == NULL) +- || item == NULL) { +- // clicked on an item without a submenu or clicked and +- // released the mouse button outside the menu bar +- fChosenItem = fSelected; +- fState = MENU_STATE_CLOSED; +- } else +- _SetStickyMode(true); +- } +- where = newWhere; +- buttons = newButtons; +- } +- } ++ item = BMenu::_Track(action, startIndex); + + if (LockLooper()) { + if (fSelected != NULL) + _SelectItem(NULL); + +- if (fChosenItem != NULL) +- fChosenItem->Invoke(); ++ if (item != NULL) ++ item->Invoke(); + + _RestoreFocus(); + UnlockLooper(); + } + +- if (_IsStickyMode()) +- _SetStickyMode(false); +- + _DeleteMenuWindow(); + +- if (action != NULL) +- *action = fState; +- +- return fChosenItem; ++ return item; + } + + +@@ -747,7 +630,6 @@ BMenuBar::_InitData(menu_layout layout) + + fBorders = BControlLook::B_ALL_BORDERS; + fLastBounds = new BRect(Bounds()); +- _SetIgnoreHidden(true); + SetLowUIColor(B_MENU_BACKGROUND_COLOR); + SetViewColor(B_TRANSPARENT_COLOR); + } +diff --git a/src/kits/interface/MenuField.cpp b/src/kits/interface/MenuField.cpp +index 8bf6193010..588ef6818f 100644 +--- a/src/kits/interface/MenuField.cpp ++++ b/src/kits/interface/MenuField.cpp +@@ -507,6 +507,11 @@ BMenuField::KeyDown(const char* bytes, int32 numBytes) + + fMenuBar->StartMenuBar(0, true, true, &bounds); + ++ fMenuTaskID = spawn_thread((thread_func)_thread_entry, ++ "_m_task_", B_NORMAL_PRIORITY, this); ++ if (fMenuTaskID >= 0) ++ resume_thread(fMenuTaskID); ++ + bounds = Bounds(); + bounds.right = fDivider; + +@@ -1087,7 +1092,7 @@ BMenuField::_DrawLabel(BRect updateRect) + rgb_color textColor; + + BPrivate::MenuPrivate menuPrivate(fMenuBar); +- if (menuPrivate.State() != MENU_STATE_CLOSED) { ++ if (menuPrivate.IsTracking()) { + // highlight the background of the label grey (like BeOS R5) + SetLowColor(ui_color(B_MENU_SELECTED_BACKGROUND_COLOR)); + BRect fillRect(rect.InsetByCopy(0, kVMargin)); +diff --git a/src/kits/interface/MenuPrivate.cpp b/src/kits/interface/MenuPrivate.cpp +index 4339654f77..73ea8d70e5 100644 +--- a/src/kits/interface/MenuPrivate.cpp ++++ b/src/kits/interface/MenuPrivate.cpp +@@ -168,10 +168,10 @@ MenuPrivate::SetItemMargins(float left, float top, float right, float bottom) + } + + +-int +-MenuPrivate::State(BMenuItem** item) const ++bool ++MenuPrivate::IsTracking() const + { +- return fMenu->_State(item); ++ return fMenu->fTrackState != NULL; + } + + +diff --git a/src/kits/interface/MenuWindow.cpp b/src/kits/interface/MenuWindow.cpp +index f1b373c087..2a1b735292 100644 +--- a/src/kits/interface/MenuWindow.cpp ++++ b/src/kits/interface/MenuWindow.cpp +@@ -15,6 +15,7 @@ + #include + #include + #include ++#include + + #include + #include +@@ -25,12 +26,24 @@ namespace BPrivate { + class BMenuScroller : public BView { + public: + BMenuScroller(BRect frame); ++ ~BMenuScroller(); + + bool IsEnabled() const; + void SetEnabled(bool enabled); + ++ void MouseMoved(BPoint where, uint32 transit, ++ const BMessage* dragMessage); ++ void MessageReceived(BMessage* msg); ++ ++protected: ++ virtual void DoScroll() = 0; ++ + private: ++ void _StartScrolling(bool doStart); ++ + bool fEnabled; ++ bool fMouseInside; ++ BMessageRunner* fScrollRunner; + }; + + +@@ -53,7 +66,8 @@ class UpperScroller : public BMenuScroller { + public: + UpperScroller(BRect frame); + +- virtual void Draw(BRect updateRect); ++ void DoScroll(); ++ void Draw(BRect updateRect); + }; + + +@@ -61,7 +75,8 @@ class LowerScroller : public BMenuScroller { + public: + LowerScroller(BRect frame); + +- virtual void Draw(BRect updateRect); ++ void DoScroll(); ++ void Draw(BRect updateRect); + }; + + +@@ -73,17 +88,29 @@ using namespace BPrivate; + + const int kScrollerHeight = 12; + ++enum { ++ scrollMsg = 'scrl' ++}; ++ + + BMenuScroller::BMenuScroller(BRect frame) + : + BView(frame, "menu scroller", 0, B_WILL_DRAW | B_FRAME_EVENTS + | B_FULL_UPDATE_ON_RESIZE), +- fEnabled(false) ++ fEnabled(false), ++ fMouseInside(false), ++ fScrollRunner(NULL) + { + SetViewUIColor(B_MENU_BACKGROUND_COLOR); + } + + ++BMenuScroller::~BMenuScroller() ++{ ++ _StartScrolling(false); ++} ++ ++ + bool + BMenuScroller::IsEnabled() const + { +@@ -95,6 +122,51 @@ void + BMenuScroller::SetEnabled(bool enabled) + { + fEnabled = enabled; ++ _StartScrolling(fEnabled && fMouseInside); ++} ++ ++ ++void ++BMenuScroller::MouseMoved(BPoint where, uint32 transit, ++ const BMessage* dragMessage) ++{ ++ switch (transit) { ++ case B_ENTERED_VIEW: ++ fMouseInside = true; ++ if (fEnabled) _StartScrolling(true); ++ break; ++ case B_EXITED_VIEW: ++ fMouseInside = false; ++ if (fEnabled) _StartScrolling(false); ++ break; ++ } ++} ++ ++ ++void ++BMenuScroller::MessageReceived(BMessage* msg) ++{ ++ switch (msg->what) { ++ case scrollMsg: ++ DoScroll(); ++ break; ++ default: ++ BView::MessageReceived(msg); ++ } ++} ++ ++ ++void ++BMenuScroller::_StartScrolling(bool doStart) ++{ ++ if (doStart) { ++ if (fScrollRunner == NULL) ++ fScrollRunner = new (std::nothrow) BMessageRunner(BMessenger(this), new BMessage(scrollMsg), 5000, -1); ++ } else { ++ if (fScrollRunner != NULL) { ++ delete fScrollRunner; fScrollRunner = NULL; ++ } ++ } + } + + +@@ -108,6 +180,16 @@ UpperScroller::UpperScroller(BRect frame) + } + + ++void ++UpperScroller::DoScroll() ++{ ++ BMenuWindow* window = dynamic_cast(Window()); ++ float smallStep; ++ window->GetSteps(&smallStep, NULL); ++ window->TryScrollBy(-smallStep); ++} ++ ++ + void + UpperScroller::Draw(BRect updateRect) + { +@@ -140,6 +222,16 @@ LowerScroller::LowerScroller(BRect frame) + } + + ++void ++LowerScroller::DoScroll() ++{ ++ BMenuWindow* window = dynamic_cast(Window()); ++ float smallStep; ++ window->GetSteps(&smallStep, NULL); ++ window->TryScrollBy(smallStep); ++} ++ ++ + void + LowerScroller::Draw(BRect updateRect) + { +@@ -391,16 +483,6 @@ BMenuWindow::HasScrollers() const + } + + +-bool +-BMenuWindow::CheckForScrolling(const BPoint &cursor) +-{ +- if (!fMenuFrame || !fUpperScroller || !fLowerScroller) +- return false; +- +- return _Scroll(cursor); +-} +- +- + bool + BMenuWindow::TryScrollBy(const float& step) + { +@@ -423,35 +505,6 @@ BMenuWindow::TryScrollTo(const float& where) + } + + +-bool +-BMenuWindow::_Scroll(const BPoint& where) +-{ +- ASSERT((fLowerScroller != NULL)); +- ASSERT((fUpperScroller != NULL)); +- +- const BPoint cursor = ConvertFromScreen(where); +- const BRect &lowerFrame = fLowerScroller->Frame(); +- const BRect &upperFrame = fUpperScroller->Frame(); +- +- int32 delta = 0; +- if (fLowerScroller->IsEnabled() && lowerFrame.Contains(cursor)) +- delta = 1; +- else if (fUpperScroller->IsEnabled() && upperFrame.Contains(cursor)) +- delta = -1; +- +- if (delta == 0) +- return false; +- +- float smallStep; +- GetSteps(&smallStep, NULL); +- _ScrollBy(smallStep * delta); +- +- snooze(5000); +- +- return true; +-} +- +- + void + BMenuWindow::_ScrollBy(const float& step) + { +diff --git a/src/kits/interface/PopUpMenu.cpp b/src/kits/interface/PopUpMenu.cpp +index 7b94b380ab..892d938c9b 100644 +--- a/src/kits/interface/PopUpMenu.cpp ++++ b/src/kits/interface/PopUpMenu.cpp +@@ -429,20 +429,10 @@ BPopUpMenu::_StartTrack(BPoint where, bool autoInvoke, bool startOpened, + fWhere = where; + fUseWhere = true; + +- // Determine when mouse-down-up will be taken as a 'press', +- // rather than a 'click' +- bigtime_t clickMaxTime = 0; +- get_click_speed(&clickMaxTime); +- clickMaxTime += system_time(); +- + // Show the menu's window + Show(); +- snooze(50000); + BMenuItem* result = Track(startOpened, _specialRect); + +- // If it was a click, keep the menu open and tracking +- if (system_time() <= clickMaxTime) +- result = Track(true, _specialRect); + if (result != NULL && autoInvoke) + result->Invoke(); + +-- +2.30.2 + diff --git a/patchset-hrev55144/0017-Interface-Kit-fix-button-mouse-behavior-now-button-c.patch b/patchset-hrev55144/0017-Interface-Kit-fix-button-mouse-behavior-now-button-c.patch new file mode 100644 index 0000000..563321e --- /dev/null +++ b/patchset-hrev55144/0017-Interface-Kit-fix-button-mouse-behavior-now-button-c.patch @@ -0,0 +1,67 @@ +From b48e1881609cce24fc56977a1947a86c2ddeae6e Mon Sep 17 00:00:00 2001 +From: X512 +Date: Thu, 29 Oct 2020 13:45:43 +0900 +Subject: Interface Kit: fix button mouse behavior, now button can be pressed + only by primary mouse button + +Change-Id: I162ff981ac2993a7845bb71dbd4c623b812b987d +--- + src/kits/interface/Button.cpp | 21 ++++++++++++++++++--- + 1 file changed, 18 insertions(+), 3 deletions(-) + +diff --git a/src/kits/interface/Button.cpp b/src/kits/interface/Button.cpp +index 635052434a..2c5bb24906 100644 +--- a/src/kits/interface/Button.cpp ++++ b/src/kits/interface/Button.cpp +@@ -170,7 +170,15 @@ BButton::Draw(BRect updateRect) + void + BButton::MouseDown(BPoint where) + { +- if (!IsEnabled()) ++ if (!IsEnabled() || IsTracking()) ++ return; ++ ++ uint32 buttons = 0; ++ ++ if (Looper() != NULL && Looper()->CurrentMessage() != NULL) ++ Looper()->CurrentMessage()->FindInt32("buttons", &(int32&)buttons); ++ ++ if (buttons != B_PRIMARY_MOUSE_BUTTON) + return; + + if (fBehavior == B_POP_UP_BEHAVIOR && _PopUpRect().Contains(where)) { +@@ -193,7 +201,6 @@ BButton::MouseDown(BPoint where) + SetMouseEventMask(B_POINTER_EVENTS, B_LOCK_WINDOW_FOCUS); + } else { + BRect bounds = Bounds(); +- uint32 buttons; + bool inside = false; + + do { +@@ -210,7 +217,7 @@ BButton::MouseDown(BPoint where) + if ((Value() == B_CONTROL_ON) != inside) + SetValue(inside ? B_CONTROL_ON : B_CONTROL_OFF); + } +- } while (buttons != 0); ++ } while ((buttons & B_PRIMARY_MOUSE_BUTTON) != 0); + + if (inside) { + if (toggleBehavior) { +@@ -400,6 +407,14 @@ BButton::MouseUp(BPoint where) + if (!IsTracking()) + return; + ++ uint32 buttons = 0; ++ ++ if (Looper() != NULL && Looper()->CurrentMessage() != NULL) ++ Looper()->CurrentMessage()->FindInt32("buttons", &(int32&)buttons); ++ ++ if ((buttons & B_PRIMARY_MOUSE_BUTTON) != 0) ++ return; ++ + if (Bounds().Contains(where)) { + if (fBehavior == B_TOGGLE_BEHAVIOR) + SetValue(_Flag(FLAG_WAS_PRESSED) ? B_CONTROL_OFF : B_CONTROL_ON); +-- +2.30.2 + diff --git a/patchset-hrev55144/0018-device_manager-WIP-set-driver-name.patch b/patchset-hrev55144/0018-device_manager-WIP-set-driver-name.patch new file mode 100644 index 0000000..a993216 --- /dev/null +++ b/patchset-hrev55144/0018-device_manager-WIP-set-driver-name.patch @@ -0,0 +1,92 @@ +From 89ae8a7cca7543e4c63c25326fbd8d44cf831e3a Mon Sep 17 00:00:00 2001 +From: X512 +Date: Tue, 10 Nov 2020 21:34:15 +0900 +Subject: device_manager: [WIP] set driver name + +* Set driver module name of device_node. + +* Set device module name and VFS path for Device. + +This helps to understand that driver is used and its VFS path from Devices utility. + +Change-Id: Ibd902a322da7e4276052bd4429a7b869a56a592b +--- + .../kernel/device_manager/device_manager.cpp | 48 +++++++++++++++++++ + 1 file changed, 48 insertions(+) + +diff --git a/src/system/kernel/device_manager/device_manager.cpp b/src/system/kernel/device_manager/device_manager.cpp +index 9b87496f09..3c1b1d74d0 100644 +--- a/src/system/kernel/device_manager/device_manager.cpp ++++ b/src/system/kernel/device_manager/device_manager.cpp +@@ -753,6 +753,29 @@ publish_device(device_node *node, const char *path, const char *moduleName) + } + + node->AddDevice(device); ++ ++ device_attr_private* attr; ++ ++ attr = new(std::nothrow) device_attr_private(); ++ if (attr != NULL) { ++ char buf[256]; ++ sprintf(buf, "dev/%ld/path", device->ID()); ++ attr->name = strdup(buf); ++ attr->type = B_STRING_TYPE; ++ attr->value.string = strdup(path); ++ node->Attributes().Add(attr); ++ } ++ ++ attr = new(std::nothrow) device_attr_private(); ++ if (attr != NULL) { ++ char buf[256]; ++ sprintf(buf, "dev/%ld/driver", device->ID()); ++ attr->name = strdup(buf); ++ attr->type = B_STRING_TYPE; ++ attr->value.string = strdup(moduleName); ++ node->Attributes().Add(attr); ++ } ++ + return B_OK; + } + +@@ -1259,6 +1282,14 @@ device_node::device_node(const char* moduleName, const device_attr* attrs) + attrs++; + } + ++ device_attr_private* attr = new(std::nothrow) device_attr_private(); ++ if (attr != NULL) { ++ attr->name = strdup("device/driver"); ++ attr->type = B_STRING_TYPE; ++ attr->value.string = strdup(fModuleName); ++ fAttributes.Add(attr); ++ } ++ + get_attr_uint32(this, B_DEVICE_FLAGS, &fFlags, false); + fFlags &= NODE_FLAG_PUBLIC_MASK; + } +@@ -2169,6 +2200,23 @@ device_node::AddDevice(Device* device) + void + device_node::RemoveDevice(Device* device) + { ++ char attrName[256]; ++ device_attr_private* attr; ++ ++ sprintf(attrName, "dev/%ld/path", device->ID()); ++ attr = find_attr(this, attrName, false, B_STRING_TYPE); ++ if (attr != NULL) { ++ fAttributes.Remove(attr); ++ delete attr; ++ } ++ ++ sprintf(attrName, "dev/%ld/driver", device->ID()); ++ attr = find_attr(this, attrName, false, B_STRING_TYPE); ++ if (attr != NULL) { ++ fAttributes.Remove(attr); ++ delete attr; ++ } ++ + fDevices.Remove(device); + } + +-- +2.30.2 + diff --git a/patchset-hrev55144/0019-Revert-Icon-O-Matic-use-BMenuFied-for-secondary-menu.patch b/patchset-hrev55144/0019-Revert-Icon-O-Matic-use-BMenuFied-for-secondary-menu.patch new file mode 100644 index 0000000..11ae3f2 --- /dev/null +++ b/patchset-hrev55144/0019-Revert-Icon-O-Matic-use-BMenuFied-for-secondary-menu.patch @@ -0,0 +1,154 @@ +From 372ce37eb8560c69b502745156efafa0fe220450 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Thu, 26 Nov 2020 17:37:13 +0900 +Subject: Revert "Icon-O-Matic: use BMenuFied for secondary menus" + +This reverts commit c2151600ed58babf94de89e942a3b83a792488f7. +--- + src/apps/icon-o-matic/MainWindow.cpp | 93 +++++++++++++++------------- + 1 file changed, 50 insertions(+), 43 deletions(-) + +diff --git a/src/apps/icon-o-matic/MainWindow.cpp b/src/apps/icon-o-matic/MainWindow.cpp +index 70b14b1514..501122fe04 100644 +--- a/src/apps/icon-o-matic/MainWindow.cpp ++++ b/src/apps/icon-o-matic/MainWindow.cpp +@@ -18,11 +18,9 @@ + #include + #include + #include +-#include + #include + #include + #include +-#include + #include + #include + #include +@@ -1042,42 +1040,53 @@ MainWindow::_CreateGUI() + layout->AddView(leftSideView, 0, 1); + leftSideView->SetExplicitMaxSize(BSize(splitWidth, B_SIZE_UNSET)); + ++ // path menu and list view ++ BMenuBar* menuBar = new BMenuBar("path menu bar"); ++ menuBar->AddItem(fPathMenu); ++ leftSideView->AddChild(menuBar); ++ + fPathListView = new PathListView(BRect(0, 0, splitWidth, 100), + "path list view", new BMessage(MSG_PATH_SELECTED), this); ++ ++ BView* scrollView = new BScrollView("path list scroll view", ++ fPathListView, B_FOLLOW_NONE, 0, false, true, B_NO_BORDER); ++ leftSideView->AddChild(scrollView); ++ ++ // shape list view ++ menuBar = new BMenuBar("shape menu bar"); ++ menuBar->AddItem(fShapeMenu); ++ leftSideView->AddChild(menuBar); ++ + fShapeListView = new ShapeListView(BRect(0, 0, splitWidth, 100), + "shape list view", new BMessage(MSG_SHAPE_SELECTED), this); ++ scrollView = new BScrollView("shape list scroll view", ++ fShapeListView, B_FOLLOW_NONE, 0, false, true, B_NO_BORDER); ++ leftSideView->AddChild(scrollView); ++ ++ // transformer list view ++ menuBar = new BMenuBar("transformer menu bar"); ++ menuBar->AddItem(fTransformerMenu); ++ leftSideView->AddChild(menuBar); ++ + fTransformerListView = new TransformerListView(BRect(0, 0, splitWidth, 100), + "transformer list view"); ++ scrollView = new BScrollView("transformer list scroll view", ++ fTransformerListView, B_FOLLOW_NONE, 0, false, true, B_NO_BORDER); ++ leftSideView->AddChild(scrollView); ++ ++ // property list view ++ menuBar = new BMenuBar("property menu bar"); ++ menuBar->AddItem(fPropertyMenu); ++ leftSideView->AddChild(menuBar); ++ + fPropertyListView = new IconObjectListView(); + +- BLayoutBuilder::Group<>(leftSideView) +- .AddGroup(B_VERTICAL, 0) +- .SetInsets(-2, -1, -1, -1) +- .Add(new BMenuField(NULL, fPathMenu)) +- .End() +- .Add(new BScrollView("path scroll view", fPathListView, +- B_FOLLOW_NONE, 0, false, true, B_NO_BORDER)) +- .AddGroup(B_VERTICAL, 0) +- .SetInsets(-2, -2, -1, -1) +- .Add(new BMenuField(NULL, fShapeMenu)) +- .End() +- .Add(new BScrollView("shape scroll view", fShapeListView, +- B_FOLLOW_NONE, 0, false, true, B_NO_BORDER)) +- .AddGroup(B_VERTICAL, 0) +- .SetInsets(-2, -2, -1, -1) +- .Add(new BMenuField(NULL, fTransformerMenu)) +- .End() +- .Add(new BScrollView("transformer scroll view", +- fTransformerListView, B_FOLLOW_NONE, 0, false, true, B_NO_BORDER)) +- .AddGroup(B_VERTICAL, 0) +- .SetInsets(-2, -2, -1, -1) +- .Add(new BMenuField(NULL, fPropertyMenu)) +- .End() +- .Add(new ScrollView(fPropertyListView, SCROLL_VERTICAL, +- BRect(0, 0, splitWidth, 100), "property scroll view", +- B_FOLLOW_NONE, B_WILL_DRAW | B_FRAME_EVENTS, B_PLAIN_BORDER, +- BORDER_RIGHT)) +- .End(); ++ // scroll view around property list view ++ ScrollView* propScrollView = new ScrollView(fPropertyListView, ++ SCROLL_VERTICAL, BRect(0, 0, splitWidth, 100), "property scroll view", ++ B_FOLLOW_NONE, B_WILL_DRAW | B_FRAME_EVENTS, B_PLAIN_BORDER, ++ BORDER_RIGHT); ++ leftSideView->AddChild(propScrollView); + + BGroupLayout* topSide = new BGroupLayout(B_HORIZONTAL); + topSide->SetSpacing(0); +@@ -1099,23 +1108,21 @@ MainWindow::_CreateGUI() + + // views along the top + +- BGroupView* styleGroupView = new BGroupView(B_VERTICAL, 0); ++ BGroupLayout* styleGroup = new BGroupLayout(B_VERTICAL, 0); ++ BView* styleGroupView = new BView("style group", 0, styleGroup); + topSide->AddView(styleGroupView); + ++ // style list view ++ menuBar = new BMenuBar("style menu bar"); ++ menuBar->AddItem(fStyleMenu); ++ styleGroup->AddView(menuBar); ++ + fStyleListView = new StyleListView(BRect(0, 0, splitWidth, 100), + "style list view", new BMessage(MSG_STYLE_SELECTED), this); +- +- BScrollView* scrollView = new BScrollView("style list scroll view", +- fStyleListView, B_FOLLOW_NONE, 0, false, true, B_NO_BORDER); ++ scrollView = new BScrollView("style list scroll view", fStyleListView, ++ B_FOLLOW_NONE, 0, false, true, B_NO_BORDER); + scrollView->SetExplicitMaxSize(BSize(splitWidth, B_SIZE_UNLIMITED)); +- +- BLayoutBuilder::Group<>(styleGroupView) +- .AddGroup(B_VERTICAL, 0) +- .SetInsets(-2, -2, -1, -1) +- .Add(new BMenuField(NULL, fStyleMenu)) +- .End() +- .Add(scrollView) +- .End(); ++ styleGroup->AddView(scrollView); + + // style view + fStyleView = new StyleView(BRect(0, 0, 200, 100)); +@@ -1127,7 +1134,7 @@ MainWindow::_CreateGUI() + BView* swatchGroupView = new BView("swatch group", 0, swatchGroup); + topSide->AddView(swatchGroupView); + +- BMenuBar* menuBar = new BMenuBar("swatches menu bar"); ++ menuBar = new BMenuBar("swatches menu bar"); + menuBar->AddItem(fSwatchMenu); + swatchGroup->AddView(menuBar); + +-- +2.30.2 + diff --git a/patchset-hrev55144/0020-device_manager-WIP-set-driver-name-fix-format-warnin.patch b/patchset-hrev55144/0020-device_manager-WIP-set-driver-name-fix-format-warnin.patch new file mode 100644 index 0000000..23fa724 --- /dev/null +++ b/patchset-hrev55144/0020-device_manager-WIP-set-driver-name-fix-format-warnin.patch @@ -0,0 +1,69 @@ +From e784f010f633d8923f970ffad5334cd73aed5ce6 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sat, 28 Nov 2020 20:38:33 +0900 +Subject: device_manager: [WIP] set driver name (fix format warnings) + +Change-Id: Id92280f4ce32b4634eb0d516a1803cb1ba7ee9fe +--- + .../kernel/device_manager/device_manager.cpp | 16 ++++++++-------- + 1 file changed, 8 insertions(+), 8 deletions(-) + +diff --git a/src/system/kernel/device_manager/device_manager.cpp b/src/system/kernel/device_manager/device_manager.cpp +index 3c1b1d74d0..ab6dbe85da 100644 +--- a/src/system/kernel/device_manager/device_manager.cpp ++++ b/src/system/kernel/device_manager/device_manager.cpp +@@ -753,13 +753,13 @@ publish_device(device_node *node, const char *path, const char *moduleName) + } + + node->AddDevice(device); +- ++ + device_attr_private* attr; + + attr = new(std::nothrow) device_attr_private(); + if (attr != NULL) { + char buf[256]; +- sprintf(buf, "dev/%ld/path", device->ID()); ++ sprintf(buf, "dev/%" B_PRIdINO "/path", device->ID()); + attr->name = strdup(buf); + attr->type = B_STRING_TYPE; + attr->value.string = strdup(path); +@@ -769,7 +769,7 @@ publish_device(device_node *node, const char *path, const char *moduleName) + attr = new(std::nothrow) device_attr_private(); + if (attr != NULL) { + char buf[256]; +- sprintf(buf, "dev/%ld/driver", device->ID()); ++ sprintf(buf, "dev/%" B_PRIdINO "/driver", device->ID()); + attr->name = strdup(buf); + attr->type = B_STRING_TYPE; + attr->value.string = strdup(moduleName); +@@ -2202,21 +2202,21 @@ device_node::RemoveDevice(Device* device) + { + char attrName[256]; + device_attr_private* attr; +- +- sprintf(attrName, "dev/%ld/path", device->ID()); ++ ++ sprintf(attrName, "dev/%" B_PRIdINO "/path", device->ID()); + attr = find_attr(this, attrName, false, B_STRING_TYPE); + if (attr != NULL) { + fAttributes.Remove(attr); + delete attr; + } +- +- sprintf(attrName, "dev/%ld/driver", device->ID()); ++ ++ sprintf(attrName, "dev/%" B_PRIdINO "/driver", device->ID()); + attr = find_attr(this, attrName, false, B_STRING_TYPE); + if (attr != NULL) { + fAttributes.Remove(attr); + delete attr; + } +- ++ + fDevices.Remove(device); + } + +-- +2.30.2 + diff --git a/patchset-hrev55144/0021-ColumnTypes-use-BString-SetToFormat-to-avoid-additio.patch b/patchset-hrev55144/0021-ColumnTypes-use-BString-SetToFormat-to-avoid-additio.patch new file mode 100644 index 0000000..8a59571 --- /dev/null +++ b/patchset-hrev55144/0021-ColumnTypes-use-BString-SetToFormat-to-avoid-additio.patch @@ -0,0 +1,82 @@ +From a3ef5324c3e07c64f2566b691f7c556d3b8f14ac Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 29 Nov 2020 12:55:52 +0900 +Subject: ColumnTypes: use BString::SetToFormat to avoid additional buffer + +Change-Id: I750eadae7c3598cde1949d61491da7b91ed01b61 +--- + src/kits/interface/ColumnTypes.cpp | 18 +++++++----------- + 1 file changed, 7 insertions(+), 11 deletions(-) + +diff --git a/src/kits/interface/ColumnTypes.cpp b/src/kits/interface/ColumnTypes.cpp +index c06149a3cc..b563e827ed 100644 +--- a/src/kits/interface/ColumnTypes.cpp ++++ b/src/kits/interface/ColumnTypes.cpp +@@ -414,7 +414,6 @@ BSizeColumn::BSizeColumn(const char* title, float width, float minWidth, + void + BSizeColumn::DrawField(BField* _field, BRect rect, BView* parent) + { +- char str[256]; + float width = rect.Width() - (2 * kTEXT_MARGIN); + BFont font; + BString string; +@@ -422,9 +421,9 @@ BSizeColumn::DrawField(BField* _field, BRect rect, BView* parent) + + parent->GetFont(&font); + if (size < kKB_SIZE) { +- sprintf(str, "%" B_PRId64 " bytes", size); +- if (font.StringWidth(str) > width) +- sprintf(str, "%" B_PRId64 " B", size); ++ string.SetToFormat("%" B_PRId64 " bytes", size); ++ if (font.StringWidth(string) > width) ++ string.SetToFormat("%" B_PRId64 " B", size); + } else { + const char* suffix; + float float_value; +@@ -446,12 +445,12 @@ BSizeColumn::DrawField(BField* _field, BRect rect, BView* parent) + if (!kSIZE_FORMATS[index]) + break; + +- sprintf(str, kSIZE_FORMATS[index], float_value, suffix); ++ string.SetToFormat(kSIZE_FORMATS[index], float_value, suffix); + // strip off an insignificant zero so we don't get readings + // such as 1.00 + char *period = 0; + char *tmp (NULL); +- for (tmp = str; *tmp; tmp++) { ++ for (tmp = (char*)string.String(); *tmp; tmp++) { + if (*tmp == '.') + period = tmp; + } +@@ -460,12 +459,11 @@ BSizeColumn::DrawField(BField* _field, BRect rect, BView* parent) + for (tmp = &period[2]; *tmp; tmp++) + *tmp = tmp[1]; + } +- if (font.StringWidth(str) <= width) ++ if (font.StringWidth(string) <= width) + break; + } + } + +- string = str; + parent->TruncateString(&string, B_TRUNCATE_MIDDLE, width + 2); + DrawString(string.String(), parent, rect); + } +@@ -521,13 +519,11 @@ BIntegerColumn::BIntegerColumn(const char* title, float width, float minWidth, + void + BIntegerColumn::DrawField(BField *field, BRect rect, BView* parent) + { +- char formatted[256]; + float width = rect.Width() - (2 * kTEXT_MARGIN); + BString string; + +- sprintf(formatted, "%d", (int)((BIntegerField*)field)->Value()); ++ string.SetToFormat("%d", (int)((BIntegerField*)field)->Value()); + +- string = formatted; + parent->TruncateString(&string, B_TRUNCATE_MIDDLE, width + 2); + DrawString(string.String(), parent, rect); + } +-- +2.30.2 + diff --git a/patchset-hrev55144/0022-libbe_test-fix-build.patch b/patchset-hrev55144/0022-libbe_test-fix-build.patch new file mode 100644 index 0000000..7ab296f --- /dev/null +++ b/patchset-hrev55144/0022-libbe_test-fix-build.patch @@ -0,0 +1,26 @@ +From 39a8bfc590d0965a931d1b412f8ca4a301dba8f8 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 30 Nov 2020 11:33:45 +0900 +Subject: libbe_test: fix build + +Change-Id: Ib864df378b403266c614941c0dedcb4cdae9a0e3 +--- + src/apps/processcontroller/Jamfile | 2 ++ + 1 file changed, 2 insertions(+) + +diff --git a/src/apps/processcontroller/Jamfile b/src/apps/processcontroller/Jamfile +index 8d98329a5d..2bbd118224 100644 +--- a/src/apps/processcontroller/Jamfile ++++ b/src/apps/processcontroller/Jamfile +@@ -1,6 +1,8 @@ + SubDir HAIKU_TOP src apps processcontroller ; + ++if $(TARGET_PLATFORM) = libbe_test { + SetSubDirSupportedPlatforms libbe_test ; ++} + + UsePrivateSystemHeaders ; + UsePrivateHeaders app interface shared ; +-- +2.30.2 + diff --git a/patchset-hrev55144/0023-Revert-Tracker-make-desktop-color-selection-try-user.patch b/patchset-hrev55144/0023-Revert-Tracker-make-desktop-color-selection-try-user.patch new file mode 100644 index 0000000..ae35c95 --- /dev/null +++ b/patchset-hrev55144/0023-Revert-Tracker-make-desktop-color-selection-try-user.patch @@ -0,0 +1,68 @@ +From 37a7d11330d68266ea5c9b7a255e81a4de3a55a0 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Thu, 3 Dec 2020 11:41:28 +0900 +Subject: Revert "Tracker: make desktop color selection try user color first" + +This reverts commit 7377c398550edc1fc8176ee4dbcd09d70f80d454. +--- + src/kits/tracker/PoseView.cpp | 42 ++++++++++------------------------- + 1 file changed, 12 insertions(+), 30 deletions(-) + +diff --git a/src/kits/tracker/PoseView.cpp b/src/kits/tracker/PoseView.cpp +index 6eebdaf178..b337d779ed 100644 +--- a/src/kits/tracker/PoseView.cpp ++++ b/src/kits/tracker/PoseView.cpp +@@ -9036,38 +9036,20 @@ BPoseView::DrawPose(BPose* pose, int32 index, bool fullDraw) + rgb_color + BPoseView::DeskTextColor() const + { +- // The desktop color is chosen independently for the desktop. +- // The text color is chosen globally for all directories. +- // It's fairly easy to get something unreadable (even with the default +- // settings, it's expected that text will be black on white in Tracker +- // folders, but white on blue on the desktop). +- // So here we check if the colors are different enough, and otherwise, +- // force the text to be either white or black. +- rgb_color textColor = ui_color(B_DOCUMENT_TEXT_COLOR); +- rgb_color viewColor; +- if (IsDesktopWindow()) +- viewColor = ViewColor(); +- else +- viewColor = ui_color(B_DOCUMENT_BACKGROUND_COLOR); +- +- int textBrightness = BPrivate::perceptual_brightness(textColor); +- int viewBrightness = BPrivate::perceptual_brightness(viewColor); +- if (abs(viewBrightness - textBrightness) > 127) { +- // The colors are different enough, we can use them as is +- return textColor; +- } else { +- if (viewBrightness > 127) { +- textColor.red = 0; +- textColor.green = 0; +- textColor.blue = 0; +- } else { +- textColor.red = 255; +- textColor.green = 255; +- textColor.blue = 255; +- } ++ rgb_color color = ViewColor(); ++ float thresh = color.red + (color.green * 1.25f) + (color.blue * 0.45f); + +- return textColor; ++ if (thresh >= 360) { ++ color.red = 0; ++ color.green = 0; ++ color.blue = 0; ++ } else { ++ color.red = 255; ++ color.green = 255; ++ color.blue = 255; + } ++ ++ return color; + } + + +-- +2.30.2 + diff --git a/patchset-hrev55144/0024-Revert-Tracker-remove-desktop-check-for-text-colors-.patch b/patchset-hrev55144/0024-Revert-Tracker-remove-desktop-check-for-text-colors-.patch new file mode 100644 index 0000000..1eedb74 --- /dev/null +++ b/patchset-hrev55144/0024-Revert-Tracker-remove-desktop-check-for-text-colors-.patch @@ -0,0 +1,42 @@ +From 2ae8902f314003c5a1cd75847b531c107df3d347 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Thu, 3 Dec 2020 11:41:49 +0900 +Subject: Revert "Tracker: remove desktop check for text colors in poseview" + +This reverts commit 7866835b41ba6b523ec42de0c266fed0019f8ad0. +--- + src/kits/tracker/TextWidget.cpp | 17 ++++++++--------- + 1 file changed, 8 insertions(+), 9 deletions(-) + +diff --git a/src/kits/tracker/TextWidget.cpp b/src/kits/tracker/TextWidget.cpp +index 0b5f6c1551..5211e771fb 100644 +--- a/src/kits/tracker/TextWidget.cpp ++++ b/src/kits/tracker/TextWidget.cpp +@@ -544,16 +544,15 @@ BTextWidget::Draw(BRect eraseRect, BRect textRect, float, BPoseView* view, + + // set high color + rgb_color highColor; +- // for active views, the selection is drawn as inverse text (background color for the text, +- // solid black for the background). +- // For inactive windows, the text is drawn normally, then the selection rect is +- // alpha-blended on top of it. +- // This all happens in BPose::Draw before and after calling this function, here we are +- // only concerned with setting the correct color for the text. +- if (selected && view->Window()->IsActive()) ++ if (view->IsDesktopWindow()) { ++ if (selected) ++ highColor = ui_color(B_DOCUMENT_BACKGROUND_COLOR); ++ else ++ highColor = view->DeskTextColor(); ++ } else if (selected && view->Window()->IsActive()) { + highColor = ui_color(B_DOCUMENT_BACKGROUND_COLOR); +- else +- highColor = view->DeskTextColor(); ++ } else ++ highColor = kBlack; + + if (clipboardMode == kMoveSelectionTo && !selected) { + drawView->SetDrawingMode(B_OP_ALPHA); +-- +2.30.2 + diff --git a/patchset-hrev55144/0025-AutoDeleter-introduce-FieldFunctionDeleter.patch b/patchset-hrev55144/0025-AutoDeleter-introduce-FieldFunctionDeleter.patch new file mode 100644 index 0000000..b80eb89 --- /dev/null +++ b/patchset-hrev55144/0025-AutoDeleter-introduce-FieldFunctionDeleter.patch @@ -0,0 +1,69 @@ +From fd031b411dc83a60d4bd652dda9f60064d2519ee Mon Sep 17 00:00:00 2001 +From: X512 +Date: Wed, 9 Dec 2020 18:33:38 +0900 +Subject: AutoDeleter: introduce FieldFunctionDeleter + +It allows to call destructor function stored in struct field such as +device_manager_info::put_node. + +Change-Id: If9162f2f449d2b1c52c39509fa8732f21debf04a +--- + headers/private/shared/AutoDeleter.h | 28 ++++++++++++++++++++++++++++ + 1 file changed, 28 insertions(+) + +diff --git a/headers/private/shared/AutoDeleter.h b/headers/private/shared/AutoDeleter.h +index 2d24368f2b..092e6770fd 100644 +--- a/headers/private/shared/AutoDeleter.h ++++ b/headers/private/shared/AutoDeleter.h +@@ -11,6 +11,8 @@ + ArrayDeleter - deletes an array + MemoryDeleter - free()s malloc()ed memory + CObjectDeleter - calls an arbitrary specified destructor function ++ FieldFunctionDeleter - calls an arbitrary field function in given struct ++ pointer + HandleDeleter - use arbitrary handle type and destructor function + FileDescriptorCloser - closes a file descriptor, based on HandleDeleter + */ +@@ -218,6 +220,31 @@ struct MethodDeleter + }; + + ++// FieldFunctionDeleter ++ ++template ++struct FieldFunctionDelete { ++ inline void operator()(Type *object) ++ { ++ if (object != NULL) ++ ((**table).*Deleter)(object); ++ } ++}; ++ ++template ++struct FieldFunctionDeleter ++ : AutoDeleter > ++{ ++ typedef AutoDeleter > Base; ++ ++ FieldFunctionDeleter() : Base() {} ++ FieldFunctionDeleter(Type *object) : Base(object) {} ++}; ++ ++ + // HandleDeleter + + struct StatusHandleChecker +@@ -308,6 +335,7 @@ using ::BPrivate::ArrayDeleter; + using ::BPrivate::MemoryDeleter; + using ::BPrivate::CObjectDeleter; + using ::BPrivate::MethodDeleter; ++using ::BPrivate::FieldFunctionDeleter; + using ::BPrivate::HandleDeleter; + using ::BPrivate::FileDescriptorCloser; + +-- +2.30.2 + diff --git a/patchset-hrev55144/0026-use-.IsSet-instead-if-.Get-NULL.patch b/patchset-hrev55144/0026-use-.IsSet-instead-if-.Get-NULL.patch new file mode 100644 index 0000000..9eca515 --- /dev/null +++ b/patchset-hrev55144/0026-use-.IsSet-instead-if-.Get-NULL.patch @@ -0,0 +1,35 @@ +From f2d22909aae37d1dc6d3841faf6eafdbb77c14ef Mon Sep 17 00:00:00 2001 +From: X512 +Date: Thu, 10 Dec 2020 04:02:02 +0900 +Subject: use .IsSet() instead if .Get() != NULL + +Change-Id: Ia2b7a719fd398e78cc3b11d4f7b02cb81179f65f +--- + src/kits/interface/Menu.cpp | 4 ++-- + 1 file changed, 2 insertions(+), 2 deletions(-) + +diff --git a/src/kits/interface/Menu.cpp b/src/kits/interface/Menu.cpp +index 9235564acd..d9158bd0d2 100644 +--- a/src/kits/interface/Menu.cpp ++++ b/src/kits/interface/Menu.cpp +@@ -618,7 +618,7 @@ BMenu::MessageReceived(BMessage* message) + fTrackState->navigationAreaTimer.Unset(); + _SelectItem(item, true); + } else { +- if (fTrackState->navigationAreaTimer.Get() != NULL) ++ if (fTrackState->navigationAreaTimer.IsSet()) + fTrackState->navigationAreaTimer.SetTo(new(std::nothrow) BMessageRunner(BMessenger(this), BMessage(navigationAreaTimeoutMsg), kNavigationAreaTimeout, 1)); + } + } +@@ -638,7 +638,7 @@ BMenu::MessageReceived(BMessage* message) + } + + case navigationAreaTimeoutMsg: { +- if (fTrackState->navigationAreaTimer.Get() != NULL) { ++ if (fTrackState->navigationAreaTimer.IsSet()) { + fTrackState->navigationAreaTimer.Unset(); + BPoint where; + GetMouse(&where, NULL); +-- +2.30.2 + diff --git a/patchset-hrev55144/0027-integrate-AutoDeleter-s-into-pointers.patch b/patchset-hrev55144/0027-integrate-AutoDeleter-s-into-pointers.patch new file mode 100644 index 0000000..85f69e7 --- /dev/null +++ b/patchset-hrev55144/0027-integrate-AutoDeleter-s-into-pointers.patch @@ -0,0 +1,1630 @@ +From 4301ef1790058aeb984307a9ffce6cb8e0b01b3b Mon Sep 17 00:00:00 2001 +From: X512 +Date: Thu, 10 Dec 2020 05:06:33 +0900 +Subject: integrate AutoDeleter's into pointers + +Change-Id: I6c3925a7aec4d0647c76c2a03aad7b08985d7166 +--- + src/add-ons/disk_systems/bfs/BFSAddOn.cpp | 12 ++--- + .../disk/virtual/ram_disk/ram_disk.cpp | 33 +++++++------ + .../kernel/file_systems/bindfs/Volume.cpp | 9 ++-- + .../packagefs/volume/PackageSettings.cpp | 8 ++-- + .../file_systems/packagefs/volume/Volume.cpp | 47 +++++++++---------- + src/apps/aboutsystem/AboutSystem.cpp | 8 ++-- + src/apps/drivesetup/MainWindow.cpp | 7 ++- + src/bin/fstrim.cpp | 8 ++-- + src/bin/i2c/i2c.cpp | 9 ++-- + src/bin/multiuser/multiuser_utils.cpp | 11 ++--- + src/bin/package/PackageWritingUtils.cpp | 7 ++- + src/bin/ramdisk.cpp | 29 +++++------- + src/kits/network/libnetapi/NetworkDevice.cpp | 34 ++++++-------- + .../network/libnetapi/NetworkInterface.cpp | 44 +++++++---------- + src/kits/network/libnetapi/NetworkRoster.cpp | 34 +++++--------- + src/kits/network/libnetapi/NetworkRoute.cpp | 10 ++-- + src/kits/package/RepositoryInfo.cpp | 34 ++++++++------ + src/kits/package/hpkg/PackageWriterImpl.cpp | 28 +++++------ + .../package/manager/RepositoryBuilder.cpp | 7 ++- + src/preferences/virtualmemory/Settings.cpp | 32 +++++++------ + src/servers/net/NetServer.cpp | 9 ++-- + .../package/CommitTransactionHandler.cpp | 11 ++--- + src/servers/package/PackageFile.cpp | 7 ++- + src/servers/package/Volume.cpp | 22 ++++----- + .../registrar/AuthenticationManager.cpp | 42 +++++++---------- + .../packagefs/PackageSettingsItem.cpp | 13 +++-- + src/system/boot/loader/package_support.cpp | 11 ++--- + src/system/libnetwork/getifaddrs.cpp | 37 +++++++-------- + src/system/libroot/os/image.cpp | 9 ++-- + src/tools/generate_boot_screen.cpp | 27 ++--------- + 30 files changed, 260 insertions(+), 339 deletions(-) + +diff --git a/src/add-ons/disk_systems/bfs/BFSAddOn.cpp b/src/add-ons/disk_systems/bfs/BFSAddOn.cpp +index 7b5a5e5fbf..274f148395 100644 +--- a/src/add-ons/disk_systems/bfs/BFSAddOn.cpp ++++ b/src/add-ons/disk_systems/bfs/BFSAddOn.cpp +@@ -226,12 +226,10 @@ BFSPartitionHandle::Repair(bool checkOnly) + BPath path; + path.SetTo(&directory, "."); + +- int fd = open(path.Path(), O_RDONLY); +- if (fd < 0) ++ FileDescriptorCloser fd(open(path.Path(), O_RDONLY)); ++ if (!fd.IsSet()) + return errno; + +- FileDescriptorCloser closer(fd); +- + struct check_control result; + memset(&result, 0, sizeof(result)); + result.magic = BFS_IOCTL_CHECK_MAGIC; +@@ -243,7 +241,7 @@ BFSPartitionHandle::Repair(bool checkOnly) + } + + // start checking +- if (ioctl(fd, BFS_IOCTL_START_CHECKING, &result, sizeof(result)) < 0) ++ if (ioctl(fd.Get(), BFS_IOCTL_START_CHECKING, &result, sizeof(result)) < 0) + return errno; + + uint64 attributeDirectories = 0, attributes = 0; +@@ -252,7 +250,7 @@ BFSPartitionHandle::Repair(bool checkOnly) + uint32 previousPass = result.pass; + + // check all files and report errors +- while (ioctl(fd, BFS_IOCTL_CHECK_NEXT_NODE, &result, ++ while (ioctl(fd.Get(), BFS_IOCTL_CHECK_NEXT_NODE, &result, + sizeof(result)) == 0) { + if (++counter % 50 == 0) + printf("%9" B_PRIu64 " nodes processed\x1b[1A\n", counter); +@@ -297,7 +295,7 @@ BFSPartitionHandle::Repair(bool checkOnly) + } + + // stop checking +- if (ioctl(fd, BFS_IOCTL_STOP_CHECKING, &result, sizeof(result)) != 0) ++ if (ioctl(fd.Get(), BFS_IOCTL_STOP_CHECKING, &result, sizeof(result)) != 0) + return errno; + + printf(" %" B_PRIu64 " nodes checked,\n\t%" B_PRIu64 " blocks not " +diff --git a/src/add-ons/kernel/drivers/disk/virtual/ram_disk/ram_disk.cpp b/src/add-ons/kernel/drivers/disk/virtual/ram_disk/ram_disk.cpp +index 280e370abb..a219a84dcd 100644 +--- a/src/add-ons/kernel/drivers/disk/virtual/ram_disk/ram_disk.cpp ++++ b/src/add-ons/kernel/drivers/disk/virtual/ram_disk/ram_disk.cpp +@@ -395,10 +395,9 @@ struct RawDevice : Device, DoublyLinkedListLinkImpl { + static const size_t kPageCountPerIteration = 1024; + static const size_t kMaxGapSize = 15; + +- int fd = open(fFilePath, O_WRONLY); +- if (fd < 0) ++ FileDescriptorCloser fd(open(fFilePath, O_WRONLY)); ++ if (!fd.IsSet()) + return errno; +- FileDescriptorCloser fdCloser(fd); + + vm_page** pages = new(std::nothrow) vm_page*[kPageCountPerIteration]; + ArrayDeleter pagesDeleter(pages); +@@ -491,7 +490,7 @@ struct RawDevice : Device, DoublyLinkedListLinkImpl { + + // write the buffer + if (error == B_OK) { +- ssize_t bytesWritten = pwrite(fd, buffer, ++ ssize_t bytesWritten = pwrite(fd.Get(), buffer, + pagesToWrite * B_PAGE_SIZE, offset); + if (bytesWritten < 0) { + dprintf("ramdisk: error writing pages to file: %s\n", +@@ -793,21 +792,20 @@ private: + { + static const size_t kPageCountPerIteration = 1024; + +- int fd = open(fFilePath, O_RDONLY); +- if (fd < 0) ++ FileDescriptorCloser fd(open(fFilePath, O_RDONLY)); ++ if (!fd.IsSet()) + return errno; +- FileDescriptorCloser fdCloser(fd); + +- vm_page** pages = new(std::nothrow) vm_page*[kPageCountPerIteration]; +- ArrayDeleter pagesDeleter(pages); ++ ArrayDeleter pages( ++ new(std::nothrow) vm_page*[kPageCountPerIteration]); + +- uint8* buffer = (uint8*)malloc(kPageCountPerIteration * B_PAGE_SIZE); +- MemoryDeleter bufferDeleter(buffer); ++ ArrayDeleter buffer( ++ new(std::nothrow) uint8[kPageCountPerIteration * B_PAGE_SIZE]); + // TODO: Ideally we wouldn't use a buffer to read the file content, + // but read into the pages we allocated directly. Unfortunately + // there's no API to do that yet. + +- if (pages == NULL || buffer == NULL) ++ if (!pages.IsSet() || !buffer.IsSet()) + return B_NO_MEMORY; + + status_t error = B_OK; +@@ -836,7 +834,8 @@ private: + + // read from the file + size_t bytesToRead = pagesToRead * B_PAGE_SIZE; +- ssize_t bytesRead = pread(fd, buffer, bytesToRead, offset); ++ ssize_t bytesRead = pread(fd.Get(), buffer.Get(), bytesToRead, ++ offset); + if (bytesRead < 0) { + error = bytesRead; + break; +@@ -849,7 +848,7 @@ private: + + // clear the last read page, if partial + if ((size_t)bytesRead < pagesRead * B_PAGE_SIZE) { +- memset(buffer + bytesRead, 0, ++ memset(buffer.Get() + bytesRead, 0, + pagesRead * B_PAGE_SIZE - bytesRead); + } + +@@ -858,7 +857,7 @@ private: + vm_page* page = pages[i]; + error = vm_memcpy_to_physical( + page->physical_page_number * B_PAGE_SIZE, +- buffer + i * B_PAGE_SIZE, B_PAGE_SIZE, false); ++ buffer.Get() + i * B_PAGE_SIZE, B_PAGE_SIZE, false); + if (error != B_OK) + break; + } +@@ -873,7 +872,7 @@ private: + + size_t clearPages = 0; + for (size_t i = 0; i < pagesRead; i++) { +- uint64* pageData = (uint64*)(buffer + i * B_PAGE_SIZE); ++ uint64* pageData = (uint64*)(buffer.Get() + i * B_PAGE_SIZE); + bool isClear = true; + for (size_t k = 0; isClear && k < B_PAGE_SIZE / 8; k++) + isClear = pageData[k] == 0; +@@ -892,7 +891,7 @@ private: + // and compute the new allocated pages count. + if (pagesRead < allocatedPages) { + size_t count = allocatedPages - pagesRead; +- memcpy(pages + clearPages, pages + pagesRead, ++ memcpy(pages.Get() + clearPages, pages.Get() + pagesRead, + count * sizeof(vm_page*)); + clearPages += count; + } +diff --git a/src/add-ons/kernel/file_systems/bindfs/Volume.cpp b/src/add-ons/kernel/file_systems/bindfs/Volume.cpp +index 5f53bd074a..7f468a0fe1 100644 +--- a/src/add-ons/kernel/file_systems/bindfs/Volume.cpp ++++ b/src/add-ons/kernel/file_systems/bindfs/Volume.cpp +@@ -50,10 +50,11 @@ status_t + Volume::Mount(const char* parameterString) + { + const char* source = NULL; +- void* parameterHandle = parse_driver_settings_string(parameterString); +- DriverSettingsUnloader parameterDeleter(parameterHandle); +- if (parameterHandle != NULL) +- source = get_driver_parameter(parameterHandle, "source", NULL, NULL); ++ DriverSettingsUnloader parametersHandle( ++ parse_driver_settings_string(parameterString)); ++ if (parametersHandle.IsSet()) ++ source = get_driver_parameter( ++ parametersHandle.Get(), "source", NULL, NULL); + if (source == NULL || source[0] == '\0') { + ERROR("need source folder ('source' parameter)!\n"); + RETURN_ERROR(B_BAD_VALUE); +diff --git a/src/add-ons/kernel/file_systems/packagefs/volume/PackageSettings.cpp b/src/add-ons/kernel/file_systems/packagefs/volume/PackageSettings.cpp +index 10d8f77ebf..4284693a2a 100644 +--- a/src/add-ons/kernel/file_systems/packagefs/volume/PackageSettings.cpp ++++ b/src/add-ons/kernel/file_systems/packagefs/volume/PackageSettings.cpp +@@ -216,12 +216,12 @@ PackageSettings::Load(dev_t mountPointDeviceID, ino_t mountPointNodeID, + return error; + + // load the driver settings +- void* settingsHandle = load_driver_settings(path.Path()); +- if (settingsHandle == NULL) ++ DriverSettingsUnloader settingsHandle(load_driver_settings(path.Path())); ++ if (!settingsHandle.IsSet()) + return B_ENTRY_NOT_FOUND; +- DriverSettingsUnloader settingsDeleter(settingsHandle); + +- const driver_settings* settings = get_driver_settings(settingsHandle); ++ const driver_settings* settings ++ = get_driver_settings(settingsHandle.Get()); + for (int i = 0; i < settings->parameter_count; i++) { + const driver_parameter& parameter = settings->parameters[i]; + if (strcmp(parameter.name, "Package") != 0 +diff --git a/src/add-ons/kernel/file_systems/packagefs/volume/Volume.cpp b/src/add-ons/kernel/file_systems/packagefs/volume/Volume.cpp +index eecfa5390a..595eb04713 100644 +--- a/src/add-ons/kernel/file_systems/packagefs/volume/Volume.cpp ++++ b/src/add-ons/kernel/file_systems/packagefs/volume/Volume.cpp +@@ -318,21 +318,21 @@ Volume::Mount(const char* parameterString) + const char* shineThrough = NULL; + const char* packagesState = NULL; + +- void* parameterHandle = parse_driver_settings_string(parameterString); +- if (parameterHandle != NULL) { +- packages = get_driver_parameter(parameterHandle, "packages", NULL, +- NULL); +- volumeName = get_driver_parameter(parameterHandle, "volume-name", NULL, +- NULL); +- mountType = get_driver_parameter(parameterHandle, "type", NULL, NULL); +- shineThrough = get_driver_parameter(parameterHandle, "shine-through", ++ DriverSettingsUnloader parameterHandle( ++ parse_driver_settings_string(parameterString)); ++ if (parameterHandle.IsSet()) { ++ packages = get_driver_parameter(parameterHandle.Get(), "packages", ++ NULL, NULL); ++ volumeName = get_driver_parameter(parameterHandle.Get(), "volume-name", + NULL, NULL); +- packagesState = get_driver_parameter(parameterHandle, "state", NULL, ++ mountType = get_driver_parameter(parameterHandle.Get(), "type", NULL, + NULL); ++ shineThrough = get_driver_parameter(parameterHandle.Get(), ++ "shine-through", NULL, NULL); ++ packagesState = get_driver_parameter(parameterHandle.Get(), "state", ++ NULL, NULL); + } + +- DriverSettingsUnloader parameterHandleDeleter(parameterHandle); +- + if (packages != NULL && packages[0] == '\0') { + FATAL("invalid package folder ('packages' parameter)!\n"); + RETURN_ERROR(B_BAD_VALUE); +@@ -707,14 +707,13 @@ Volume::_LoadOldPackagesStates(const char* packagesState) + } + + // iterate through the "administrative" dir +- DIR* dir = fdopendir(fd); +- if (dir == NULL) { ++ DirCloser dir(fdopendir(fd)); ++ if (!dir.IsSet()) { + ERROR("Failed to open administrative directory: %s\n", strerror(errno)); + RETURN_ERROR(errno); + } +- DirCloser dirCloser(dir); + +- while (dirent* entry = readdir(dir)) { ++ while (dirent* entry = readdir(dir.Get())) { + if (strncmp(entry->d_name, "state_", 6) != 0 + || strcmp(entry->d_name, packagesState) < 0) { + continue; +@@ -813,20 +812,19 @@ Volume::_AddInitialPackagesFromActivationFile( + PackagesDirectory* packagesDirectory) + { + // try reading the activation file +- int fd = openat(packagesDirectory->DirectoryFD(), ++ FileDescriptorCloser fd(openat(packagesDirectory->DirectoryFD(), + packagesDirectory == fPackagesDirectory + ? kActivationFilePath : kActivationFileName, +- O_RDONLY); +- if (fd < 0) { ++ O_RDONLY)); ++ if (!fd.IsSet()) { + INFORM("Failed to open packages activation file: %s\n", + strerror(errno)); + RETURN_ERROR(errno); + } +- FileDescriptorCloser fdCloser(fd); + + // read the whole file into memory to simplify things + struct stat st; +- if (fstat(fd, &st) != 0) { ++ if (fstat(fd.Get(), &st) != 0) { + ERROR("Failed to stat packages activation file: %s\n", + strerror(errno)); + RETURN_ERROR(errno); +@@ -842,7 +840,7 @@ Volume::_AddInitialPackagesFromActivationFile( + RETURN_ERROR(B_NO_MEMORY); + MemoryDeleter fileContentDeleter(fileContent); + +- ssize_t bytesRead = read(fd, fileContent, st.st_size); ++ ssize_t bytesRead = read(fd.Get(), fileContent, st.st_size); + if (bytesRead < 0) { + ERROR("Failed to read packages activation file: %s\n", strerror(errno)); + RETURN_ERROR(errno); +@@ -898,15 +896,14 @@ Volume::_AddInitialPackagesFromDirectory() + RETURN_ERROR(errno); + } + +- DIR* dir = fdopendir(fd); +- if (dir == NULL) { ++ DirCloser dir(fdopendir(fd)); ++ if (!dir.IsSet()) { + ERROR("Failed to open packages directory \"%s\": %s\n", + fPackagesDirectory->Path(), strerror(errno)); + RETURN_ERROR(errno); + } +- DirCloser dirCloser(dir); + +- while (dirent* entry = readdir(dir)) { ++ while (dirent* entry = readdir(dir.Get())) { + // skip "." and ".." + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) + continue; +diff --git a/src/apps/aboutsystem/AboutSystem.cpp b/src/apps/aboutsystem/AboutSystem.cpp +index 804766d268..b39f236736 100644 +--- a/src/apps/aboutsystem/AboutSystem.cpp ++++ b/src/apps/aboutsystem/AboutSystem.cpp +@@ -1466,19 +1466,19 @@ AboutView::_AddCopyrightsFromAttribute() + return; + + // attach it to a FILE +- FILE* attrFile = fdopen(attrFD, "r"); +- if (attrFile == NULL) { ++ FileCloser attrFile(fdopen(attrFD, "r")); ++ if (!attrFile.IsSet()) { + close(attrFD); + return; + } +- FileCloser _(attrFile); + + // read and parse the copyrights + BMessage package; + BString fieldName; + BString fieldValue; + char lineBuffer[LINE_MAX]; +- while (char* line = fgets(lineBuffer, sizeof(lineBuffer), attrFile)) { ++ while (char* line ++ = fgets(lineBuffer, sizeof(lineBuffer), attrFile.Get())) { + // chop off line break + size_t lineLen = strlen(line); + if (lineLen > 0 && line[lineLen - 1] == '\n') +diff --git a/src/apps/drivesetup/MainWindow.cpp b/src/apps/drivesetup/MainWindow.cpp +index a35748ade5..bc2630afb0 100644 +--- a/src/apps/drivesetup/MainWindow.cpp ++++ b/src/apps/drivesetup/MainWindow.cpp +@@ -1529,16 +1529,15 @@ MainWindow::_CreateRamDisk() + request.path[0] = '\0'; + request.id = -1; + +- int fd = open(ctrlDevPath, O_RDONLY); +- if (fd < 0) { ++ FileDescriptorCloser fd(open(ctrlDevPath, O_RDONLY)); ++ if (!fd.IsSet()) { + fprintf(stderr, "Error: Failed to open RAM disk control device \"%s\": " + "%s\n", ctrlDevPath, strerror(errno)); + return; + } +- FileDescriptorCloser fdCloser(fd); + + // issue the request +- if (ioctl(fd, RAM_DISK_IOCTL_REGISTER, &request) < 0) ++ if (ioctl(fd.Get(), RAM_DISK_IOCTL_REGISTER, &request) < 0) + fprintf(stderr, "Error: Failed to create RAM disk device: %s\n", + strerror(errno)); + } +diff --git a/src/bin/fstrim.cpp b/src/bin/fstrim.cpp +index b09cd41184..a956d16b8c 100644 +--- a/src/bin/fstrim.cpp ++++ b/src/bin/fstrim.cpp +@@ -56,22 +56,20 @@ main(int argc, char** argv) + usage(1); + const char* path = argv[optind++]; + +- int fd = open(path, O_RDONLY); +- if (fd < 0) { ++ FileDescriptorCloser fd(open(path, O_RDONLY)); ++ if (!fd.IsSet()) { + fprintf(stderr, "%s: Could not access path: %s\n", kProgramName, + strerror(errno)); + return EXIT_FAILURE; + } + +- FileDescriptorCloser closer(fd); +- + fs_trim_data trimData; + trimData.range_count = 1; + trimData.ranges[0].offset = 0; + trimData.ranges[0].size = UINT64_MAX; + trimData.trimmed_size = 0; + +- if (ioctl(fd, B_TRIM_DEVICE, &trimData, sizeof(fs_trim_data)) != 0) { ++ if (ioctl(fd.Get(), B_TRIM_DEVICE, &trimData, sizeof(fs_trim_data)) != 0) { + fprintf(stderr, "%s: Trimming failed: %s\n", kProgramName, + strerror(errno)); + return EXIT_FAILURE; +diff --git a/src/bin/i2c/i2c.cpp b/src/bin/i2c/i2c.cpp +index 6b4c7c00c0..95d11a2326 100644 +--- a/src/bin/i2c/i2c.cpp ++++ b/src/bin/i2c/i2c.cpp +@@ -41,8 +41,8 @@ static int + scan_bus(const char *path) + { + int err = EXIT_SUCCESS; +- int fd = open(path, O_RDONLY); +- if (fd < 0) { ++ FileDescriptorCloser fd(open(path, O_RDONLY)); ++ if (!fd.IsSet()) { + fprintf(stderr, "%s: Could not access path: %s\n", kProgramName, + strerror(errno)); + return EXIT_FAILURE; +@@ -50,7 +50,6 @@ scan_bus(const char *path) + + setbuf(stdout, NULL); + printf("Scanning I2C bus: %s\n", path); +- FileDescriptorCloser closer(fd); + + printf(" 0 1 2 3 4 5 6 7 8 9 a b c d e f\n"); + for (int i = 0; i < 128; i+=16) { +@@ -66,7 +65,7 @@ scan_bus(const char *path) + exec.cmdLength = sizeof(cmd); + exec.buffer = &data; + exec.bufferLength = sizeof(data); +- if (ioctl(fd, I2CEXEC, &exec, sizeof(exec)) == 0) ++ if (ioctl(fd.Get(), I2CEXEC, &exec, sizeof(exec)) == 0) + printf("%02x ", addr); + else + printf("-- "); +@@ -74,8 +73,6 @@ scan_bus(const char *path) + printf("\n"); + } + +- close(fd); +- + return err; + } + +diff --git a/src/bin/multiuser/multiuser_utils.cpp b/src/bin/multiuser/multiuser_utils.cpp +index 54838ebcaa..1b0b5cade0 100644 +--- a/src/bin/multiuser/multiuser_utils.cpp ++++ b/src/bin/multiuser/multiuser_utils.cpp +@@ -25,20 +25,19 @@ read_password(const char* prompt, char* password, size_t bufferSize, + FILE* out = stdout; + + // open tty +- FILE* tty = NULL; ++ FileCloser tty; + if (!useStdio) { + // TODO: Open tty with O_NOCTTY! +- tty = fopen("/dev/tty", "w+"); +- if (tty == NULL) { ++ tty.SetTo(fopen("/dev/tty", "w+")); ++ if (!tty.IsSet()) { + fprintf(stderr, "Error: Failed to open tty: %s\n", + strerror(errno)); + return errno; + } + +- in = tty; +- out = tty; ++ in = tty.Get(); ++ out = tty.Get(); + } +- FileCloser ttyCloser(tty); + + // disable echo + int inFD = fileno(in); +diff --git a/src/bin/package/PackageWritingUtils.cpp b/src/bin/package/PackageWritingUtils.cpp +index 88aa9850a1..5ce871d6e1 100644 +--- a/src/bin/package/PackageWritingUtils.cpp ++++ b/src/bin/package/PackageWritingUtils.cpp +@@ -22,15 +22,14 @@ add_current_directory_entries(BPackageWriter& packageWriter, + BPackageWriterListener& listener, bool skipPackageInfo) + { + // open the current directory +- DIR* dir = opendir("."); +- if (dir == NULL) { ++ DirCloser dir(opendir(".")); ++ if (!dir.IsSet()) { + listener.PrintError("Error: Failed to opendir '.': %s\n", + strerror(errno)); + return errno; + } +- DirCloser dirCloser(dir); + +- while (dirent* entry = readdir(dir)) { ++ while (dirent* entry = readdir(dir.Get())) { + // skip "." and ".." + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) + continue; +diff --git a/src/bin/ramdisk.cpp b/src/bin/ramdisk.cpp +index b851025a39..ad90383483 100644 +--- a/src/bin/ramdisk.cpp ++++ b/src/bin/ramdisk.cpp +@@ -99,16 +99,15 @@ static status_t + execute_control_device_ioctl(int operation, void* request) + { + // open the ram disk control device +- int fd = open(kRamDiskControlDevicePath, O_RDONLY); +- if (fd < 0) { ++ FileDescriptorCloser fd(open(kRamDiskControlDevicePath, O_RDONLY)); ++ if (!fd.IsSet()) { + fprintf(stderr, "Error: Failed to open RAM disk control device \"%s\": " + "%s\n", kRamDiskControlDevicePath, strerror(errno)); + return errno; + } +- FileDescriptorCloser fdCloser(fd); + + // issue the request +- if (ioctl(fd, operation, request) < 0) ++ if (ioctl(fd.Get(), operation, request) < 0) + return errno; + + return B_OK; +@@ -331,16 +330,15 @@ command_flush(int argc, const char* const* argv) + // open the raw device + BString path; + path.SetToFormat("%s/%s/raw", kRamDiskRawDeviceBasePath, idString); +- int fd = open(path, O_RDONLY); +- if (fd < 0) { ++ FileDescriptorCloser fd(open(path, O_RDONLY)); ++ if (!fd.IsSet()) { + fprintf(stderr, "Error: Failed to open RAM disk device \"%s\"\n", + path.String()); + return 1; + } +- FileDescriptorCloser fdCloser(fd); + + // issue the request +- if (ioctl(fd, RAM_DISK_IOCTL_FLUSH, NULL) < 0) { ++ if (ioctl(fd.Get(), RAM_DISK_IOCTL_FLUSH, NULL) < 0) { + fprintf(stderr, "Error: Failed to flush RAM disk device: %s\n", + strerror(errno)); + return 1; +@@ -382,20 +380,19 @@ command_list(int argc, const char* const* argv) + print_usage_and_exit(true); + + // iterate through the RAM disk device directory and search for raw devices +- DIR* dir = opendir(kRamDiskRawDeviceBasePath); +- if (dir == NULL) { ++ DirCloser dir(opendir(kRamDiskRawDeviceBasePath)); ++ if (!dir.IsSet()) { + fprintf(stderr, "Error: Failed to open RAM disk device directory: %s\n", + strerror(errno)); + return 1; + } +- DirCloser dirCloser(dir); + + TextTable table; + table.AddColumn("ID", B_ALIGN_RIGHT); + table.AddColumn("Size", B_ALIGN_RIGHT); + table.AddColumn("Associated file"); + +- while (dirent* entry = readdir(dir)) { ++ while (dirent* entry = readdir(dir.Get())) { + // check, if the entry name could be an ID + const char* idString = entry->d_name; + char* end; +@@ -406,14 +403,14 @@ command_list(int argc, const char* const* argv) + // open the raw device + BString path; + path.SetToFormat("%s/%s/raw", kRamDiskRawDeviceBasePath, idString); +- int fd = open(path, O_RDONLY); +- if (fd < 0) ++ FileDescriptorCloser fd(open(path, O_RDONLY)); ++ if (!fd.IsSet()) + continue; +- FileDescriptorCloser fdCloser(fd); + + // issue the request + ram_disk_ioctl_info request; +- if (ioctl(fd, RAM_DISK_IOCTL_INFO, &request, sizeof(request)) < 0) ++ if (ioctl(fd.Get(), RAM_DISK_IOCTL_INFO, &request, sizeof(request)) ++ < 0) + continue; + + int32 rowIndex = table.CountRows(); +diff --git a/src/kits/network/libnetapi/NetworkDevice.cpp b/src/kits/network/libnetapi/NetworkDevice.cpp +index 7cd7b46fbd..a4a5eddc62 100644 +--- a/src/kits/network/libnetapi/NetworkDevice.cpp ++++ b/src/kits/network/libnetapi/NetworkDevice.cpp +@@ -50,12 +50,10 @@ struct ie_data { + static status_t + get_80211(const char* name, int32 type, void* data, int32& length) + { +- int socket = ::socket(AF_INET, SOCK_DGRAM, 0); +- if (socket < 0) ++ FileDescriptorCloser socket(::socket(AF_INET, SOCK_DGRAM, 0)); ++ if (!socket.IsSet()) + return errno; + +- FileDescriptorCloser closer(socket); +- + struct ieee80211req ireq; + strlcpy(ireq.i_name, name, IF_NAMESIZE); + ireq.i_type = type; +@@ -63,7 +61,8 @@ get_80211(const char* name, int32 type, void* data, int32& length) + ireq.i_len = length; + ireq.i_data = data; + +- if (ioctl(socket, SIOCG80211, &ireq, sizeof(struct ieee80211req)) < 0) ++ if (ioctl(socket.Get(), SIOCG80211, &ireq, sizeof(struct ieee80211req)) ++ < 0) + return errno; + + length = ireq.i_len; +@@ -75,12 +74,10 @@ static status_t + set_80211(const char* name, int32 type, void* data, + int32 length = 0, int32 value = 0) + { +- int socket = ::socket(AF_INET, SOCK_DGRAM, 0); +- if (socket < 0) ++ FileDescriptorCloser socket(::socket(AF_INET, SOCK_DGRAM, 0)); ++ if (!socket.IsSet()) + return errno; + +- FileDescriptorCloser closer(socket); +- + struct ieee80211req ireq; + strlcpy(ireq.i_name, name, IF_NAMESIZE); + ireq.i_type = type; +@@ -88,7 +85,8 @@ set_80211(const char* name, int32 type, void* data, + ireq.i_len = length; + ireq.i_data = data; + +- if (ioctl(socket, SIOCS80211, &ireq, sizeof(struct ieee80211req)) < 0) ++ if (ioctl(socket.Get(), SIOCS80211, &ireq, sizeof(struct ieee80211req)) ++ < 0) + return errno; + + return B_OK; +@@ -98,15 +96,13 @@ set_80211(const char* name, int32 type, void* data, + template status_t + do_request(T& request, const char* name, int option) + { +- int socket = ::socket(AF_LINK, SOCK_DGRAM, 0); +- if (socket < 0) ++ FileDescriptorCloser socket(::socket(AF_LINK, SOCK_DGRAM, 0)); ++ if (!socket.IsSet()) + return errno; + +- FileDescriptorCloser closer(socket); +- + strlcpy(((struct ifreq&)request).ifr_name, name, IF_NAMESIZE); + +- if (ioctl(socket, option, &request, sizeof(T)) < 0) ++ if (ioctl(socket.Get(), option, &request, sizeof(T)) < 0) + return errno; + + return B_OK; +@@ -116,15 +112,13 @@ do_request(T& request, const char* name, int option) + template<> status_t + do_request(ieee80211req& request, const char* name, int option) + { +- int socket = ::socket(AF_INET, SOCK_DGRAM, 0); +- if (socket < 0) ++ FileDescriptorCloser socket(::socket(AF_INET, SOCK_DGRAM, 0)); ++ if (!socket.IsSet()) + return errno; + +- FileDescriptorCloser closer(socket); +- + strlcpy(((struct ieee80211req&)request).i_name, name, IFNAMSIZ); + +- if (ioctl(socket, option, &request, sizeof(request)) < 0) ++ if (ioctl(socket.Get(), option, &request, sizeof(request)) < 0) + return errno; + + return B_OK; +diff --git a/src/kits/network/libnetapi/NetworkInterface.cpp b/src/kits/network/libnetapi/NetworkInterface.cpp +index 9d9ab8e505..d557adfaf0 100644 +--- a/src/kits/network/libnetapi/NetworkInterface.cpp ++++ b/src/kits/network/libnetapi/NetworkInterface.cpp +@@ -37,12 +37,10 @@ do_ifaliasreq(const char* name, int32 option, BNetworkInterfaceAddress& address, + if (!readBack) + family = family_from_interface_address(address); + +- int socket = ::socket(family, SOCK_DGRAM, 0); +- if (socket < 0) ++ FileDescriptorCloser socket(::socket(family, SOCK_DGRAM, 0)); ++ if (!socket.IsSet()) + return errno; + +- FileDescriptorCloser closer(socket); +- + ifaliasreq request; + strlcpy(request.ifra_name, name, IF_NAMESIZE); + request.ifra_index = address.Index(); +@@ -55,7 +53,7 @@ do_ifaliasreq(const char* name, int32 option, BNetworkInterfaceAddress& address, + memcpy(&request.ifra_broadaddr, &address.Broadcast().SockAddr(), + address.Broadcast().Length()); + +- if (ioctl(socket, option, &request, sizeof(struct ifaliasreq)) < 0) ++ if (ioctl(socket.Get(), option, &request, sizeof(struct ifaliasreq)) < 0) + return errno; + + if (readBack) { +@@ -81,15 +79,13 @@ do_ifaliasreq(const char* name, int32 option, + template status_t + do_request(int family, T& request, const char* name, int option) + { +- int socket = ::socket(family, SOCK_DGRAM, 0); +- if (socket < 0) ++ FileDescriptorCloser socket(::socket(family, SOCK_DGRAM, 0)); ++ if (!socket.IsSet()) + return errno; + +- FileDescriptorCloser closer(socket); +- + strlcpy(((struct ifreq&)request).ifr_name, name, IF_NAMESIZE); + +- if (ioctl(socket, option, &request, sizeof(T)) < 0) ++ if (ioctl(socket.Get(), option, &request, sizeof(T)) < 0) + return errno; + + return B_OK; +@@ -371,12 +367,10 @@ BNetworkInterface::GetAddressAt(int32 index, BNetworkInterfaceAddress& address) + int32 + BNetworkInterface::FindAddress(const BNetworkAddress& address) + { +- int socket = ::socket(address.Family(), SOCK_DGRAM, 0); +- if (socket < 0) ++ FileDescriptorCloser socket(::socket(address.Family(), SOCK_DGRAM, 0)); ++ if (!socket.IsSet()) + return -1; + +- FileDescriptorCloser closer(socket); +- + ifaliasreq request; + memset(&request, 0, sizeof(ifaliasreq)); + +@@ -384,8 +378,8 @@ BNetworkInterface::FindAddress(const BNetworkAddress& address) + request.ifra_index = -1; + memcpy(&request.ifra_addr, &address.SockAddr(), address.Length()); + +- if (ioctl(socket, B_SOCKET_GET_ALIAS, &request, sizeof(struct ifaliasreq)) +- < 0) { ++ if (ioctl(socket.Get(), B_SOCKET_GET_ALIAS, &request, ++ sizeof(struct ifaliasreq)) < 0) { + return -1; + } + +@@ -396,12 +390,10 @@ BNetworkInterface::FindAddress(const BNetworkAddress& address) + int32 + BNetworkInterface::FindFirstAddress(int family) + { +- int socket = ::socket(family, SOCK_DGRAM, 0); +- if (socket < 0) ++ FileDescriptorCloser socket(::socket(family, SOCK_DGRAM, 0)); ++ if (!socket.IsSet()) + return -1; + +- FileDescriptorCloser closer(socket); +- + ifaliasreq request; + memset(&request, 0, sizeof(ifaliasreq)); + +@@ -409,8 +401,8 @@ BNetworkInterface::FindFirstAddress(int family) + request.ifra_index = -1; + request.ifra_addr.ss_family = AF_UNSPEC; + +- if (ioctl(socket, B_SOCKET_GET_ALIAS, &request, sizeof(struct ifaliasreq)) +- < 0) { ++ if (ioctl(socket.Get(), B_SOCKET_GET_ALIAS, &request, ++ sizeof(struct ifaliasreq)) < 0) { + return -1; + } + +@@ -479,16 +471,14 @@ BNetworkInterface::RemoveAddressAt(int32 index) + status_t + BNetworkInterface::GetHardwareAddress(BNetworkAddress& address) + { +- int socket = ::socket(AF_LINK, SOCK_DGRAM, 0); +- if (socket < 0) ++ FileDescriptorCloser socket(::socket(AF_LINK, SOCK_DGRAM, 0)); ++ if (!socket.IsSet()) + return errno; + +- FileDescriptorCloser closer(socket); +- + ifreq request; + strlcpy(request.ifr_name, Name(), IF_NAMESIZE); + +- if (ioctl(socket, SIOCGIFADDR, &request, sizeof(struct ifreq)) < 0) ++ if (ioctl(socket.Get(), SIOCGIFADDR, &request, sizeof(struct ifreq)) < 0) + return errno; + + address.SetTo(request.ifr_addr); +diff --git a/src/kits/network/libnetapi/NetworkRoster.cpp b/src/kits/network/libnetapi/NetworkRoster.cpp +index 8f840b5d28..b090be85b9 100644 +--- a/src/kits/network/libnetapi/NetworkRoster.cpp ++++ b/src/kits/network/libnetapi/NetworkRoster.cpp +@@ -37,15 +37,13 @@ BNetworkRoster::Default() + size_t + BNetworkRoster::CountInterfaces() const + { +- int socket = ::socket(AF_INET, SOCK_DGRAM, 0); +- if (socket < 0) ++ FileDescriptorCloser socket(::socket(AF_INET, SOCK_DGRAM, 0)); ++ if (!socket.IsSet()) + return 0; + +- FileDescriptorCloser closer(socket); +- + ifconf config; + config.ifc_len = sizeof(config.ifc_value); +- if (ioctl(socket, SIOCGIFCOUNT, &config, sizeof(struct ifconf)) != 0) ++ if (ioctl(socket.Get(), SIOCGIFCOUNT, &config, sizeof(struct ifconf)) != 0) + return 0; + + return (size_t)config.ifc_value; +@@ -63,15 +61,13 @@ BNetworkRoster::GetNextInterface(uint32* cookie, + + // get a list of all interfaces + +- int socket = ::socket(AF_INET, SOCK_DGRAM, 0); +- if (socket < 0) ++ FileDescriptorCloser socket (::socket(AF_INET, SOCK_DGRAM, 0)); ++ if (!socket.IsSet()) + return errno; + +- FileDescriptorCloser closer(socket); +- + ifconf config; + config.ifc_len = sizeof(config.ifc_value); +- if (ioctl(socket, SIOCGIFCOUNT, &config, sizeof(struct ifconf)) < 0) ++ if (ioctl(socket.Get(), SIOCGIFCOUNT, &config, sizeof(struct ifconf)) < 0) + return errno; + + size_t count = (size_t)config.ifc_value; +@@ -86,7 +82,7 @@ BNetworkRoster::GetNextInterface(uint32* cookie, + + config.ifc_len = count * sizeof(struct ifreq); + config.ifc_buf = buffer; +- if (ioctl(socket, SIOCGIFCONF, &config, sizeof(struct ifconf)) < 0) ++ if (ioctl(socket.Get(), SIOCGIFCONF, &config, sizeof(struct ifconf)) < 0) + return errno; + + ifreq* interfaces = (ifreq*)buffer; +@@ -110,17 +106,15 @@ BNetworkRoster::GetNextInterface(uint32* cookie, + status_t + BNetworkRoster::AddInterface(const char* name) + { +- int socket = ::socket(AF_INET, SOCK_DGRAM, 0); +- if (socket < 0) ++ FileDescriptorCloser socket (::socket(AF_INET, SOCK_DGRAM, 0)); ++ if (!socket.IsSet()) + return errno; + +- FileDescriptorCloser closer(socket); +- + ifaliasreq request; + memset(&request, 0, sizeof(ifaliasreq)); + strlcpy(request.ifra_name, name, IF_NAMESIZE); + +- if (ioctl(socket, SIOCAIFADDR, &request, sizeof(request)) != 0) ++ if (ioctl(socket.Get(), SIOCAIFADDR, &request, sizeof(request)) != 0) + return errno; + + return B_OK; +@@ -137,18 +131,16 @@ BNetworkRoster::AddInterface(const BNetworkInterface& interface) + status_t + BNetworkRoster::RemoveInterface(const char* name) + { +- int socket = ::socket(AF_INET, SOCK_DGRAM, 0); +- if (socket < 0) ++ FileDescriptorCloser socket(::socket(AF_INET, SOCK_DGRAM, 0)); ++ if (!socket.IsSet()) + return errno; + +- FileDescriptorCloser closer(socket); +- + ifreq request; + strlcpy(request.ifr_name, name, IF_NAMESIZE); + + request.ifr_addr.sa_family = AF_UNSPEC; + +- if (ioctl(socket, SIOCDIFADDR, &request, sizeof(request)) != 0) ++ if (ioctl(socket.Get(), SIOCDIFADDR, &request, sizeof(request)) != 0) + return errno; + + return B_OK; +diff --git a/src/kits/network/libnetapi/NetworkRoute.cpp b/src/kits/network/libnetapi/NetworkRoute.cpp +index 7d32f26ec3..6ebe6a55fe 100644 +--- a/src/kits/network/libnetapi/NetworkRoute.cpp ++++ b/src/kits/network/libnetapi/NetworkRoute.cpp +@@ -256,15 +256,13 @@ status_t + BNetworkRoute::GetRoutes(int family, const char* interfaceName, + uint32 filterFlags, BObjectList& routes) + { +- int socket = ::socket(family, SOCK_DGRAM, 0); +- if (socket < 0) ++ FileDescriptorCloser socket(::socket(family, SOCK_DGRAM, 0)); ++ if (!socket.IsSet()) + return errno; + +- FileDescriptorCloser fdCloser(socket); +- + ifconf config; + config.ifc_len = sizeof(config.ifc_value); +- if (ioctl(socket, SIOCGRTSIZE, &config, sizeof(struct ifconf)) < 0) ++ if (ioctl(socket.Get(), SIOCGRTSIZE, &config, sizeof(struct ifconf)) < 0) + return errno; + + uint32 size = (uint32)config.ifc_value; +@@ -279,7 +277,7 @@ BNetworkRoute::GetRoutes(int family, const char* interfaceName, + config.ifc_len = size; + config.ifc_buf = buffer; + +- if (ioctl(socket, SIOCGRTTABLE, &config, sizeof(struct ifconf)) < 0) ++ if (ioctl(socket.Get(), SIOCGRTTABLE, &config, sizeof(struct ifconf)) < 0) + return errno; + + ifreq* interface = (ifreq*)buffer; +diff --git a/src/kits/package/RepositoryInfo.cpp b/src/kits/package/RepositoryInfo.cpp +index f2120f7282..dc41b81309 100644 +--- a/src/kits/package/RepositoryInfo.cpp ++++ b/src/kits/package/RepositoryInfo.cpp +@@ -358,25 +358,29 @@ BRepositoryInfo::_SetTo(const BEntry& entry) + buffer[size] = '\0'; + configString.UnlockBuffer(size); + +- void* settingsHandle = parse_driver_settings_string(configString.String()); +- if (settingsHandle == NULL) ++ DriverSettingsUnloader settingsHandle( ++ parse_driver_settings_string(configString.String())); ++ if (!settingsHandle.IsSet()) + return B_BAD_DATA; +- DriverSettingsUnloader settingsHandleDeleter(settingsHandle); + +- const char* name = get_driver_parameter(settingsHandle, "name", NULL, NULL); +- const char* identifier = get_driver_parameter(settingsHandle, "identifier", NULL, NULL); ++ const char* name = get_driver_parameter(settingsHandle.Get(), "name", NULL, ++ NULL); ++ const char* identifier = get_driver_parameter(settingsHandle.Get(), ++ "identifier", NULL, NULL); + // Also handle the old name if the new one isn't found + if (identifier == NULL || *identifier == '\0') +- identifier = get_driver_parameter(settingsHandle, "url", NULL, NULL); +- const char* baseUrl = get_driver_parameter(settingsHandle, "baseurl", NULL, NULL); +- const char* vendor +- = get_driver_parameter(settingsHandle, "vendor", NULL, NULL); +- const char* summary +- = get_driver_parameter(settingsHandle, "summary", NULL, NULL); +- const char* priorityString +- = get_driver_parameter(settingsHandle, "priority", NULL, NULL); +- const char* architectureString +- = get_driver_parameter(settingsHandle, "architecture", NULL, NULL); ++ identifier = get_driver_parameter(settingsHandle.Get(), ++ "url", NULL, NULL); ++ const char* baseUrl = get_driver_parameter(settingsHandle.Get(), ++ "baseurl", NULL, NULL); ++ const char* vendor = get_driver_parameter(settingsHandle.Get(), ++ "vendor", NULL, NULL); ++ const char* summary = get_driver_parameter(settingsHandle.Get(), ++ "summary", NULL, NULL); ++ const char* priorityString = get_driver_parameter(settingsHandle.Get(), ++ "priority", NULL, NULL); ++ const char* architectureString = get_driver_parameter(settingsHandle.Get(), ++ "architecture", NULL, NULL); + + if (name == NULL || *name == '\0' + || identifier == NULL || *identifier == '\0' +diff --git a/src/kits/package/hpkg/PackageWriterImpl.cpp b/src/kits/package/hpkg/PackageWriterImpl.cpp +index 301e2d4bfd..d21ba18d37 100644 +--- a/src/kits/package/hpkg/PackageWriterImpl.cpp ++++ b/src/kits/package/hpkg/PackageWriterImpl.cpp +@@ -1138,10 +1138,9 @@ PackageWriterImpl::_UpdateCheckEntryCollisions(Attribute* parentAttribute, + // explicitly specified directory -- we need to read the directory + + // first we check for colliding node attributes, though +- if (DIR* attrDir = fs_fopen_attr_dir(fd)) { +- AttrDirCloser attrDirCloser(attrDir); +- +- while (dirent* entry = fs_read_attr_dir(attrDir)) { ++ AttrDirCloser attrDir(fs_fopen_attr_dir(fd)); ++ if (attrDir.IsSet()) { ++ while (dirent* entry = fs_read_attr_dir(attrDir.Get())) { + attr_info attrInfo; + if (fs_stat_attr(fd, entry->d_name, &attrInfo) < 0) { + fListener->PrintError( +@@ -1177,17 +1176,16 @@ PackageWriterImpl::_UpdateCheckEntryCollisions(Attribute* parentAttribute, + throw status_t(errno); + } + +- DIR* dir = fdopendir(clonedFD); +- if (dir == NULL) { ++ DirCloser dir(fdopendir(clonedFD)); ++ if (!dir.IsSet()) { + fListener->PrintError( + "Failed to open directory \"%s\": %s\n", pathBuffer, + strerror(errno)); + close(clonedFD); + throw status_t(errno); + } +- DirCloser dirCloser(dir); + +- while (dirent* entry = readdir(dir)) { ++ while (dirent* entry = readdir(dir.Get())) { + // skip "." and ".." + if (strcmp(entry->d_name, ".") == 0 + || strcmp(entry->d_name, "..") == 0) { +@@ -1525,10 +1523,9 @@ PackageWriterImpl::_AddEntry(int dirFD, Entry* entry, const char* fileName, + } + + // add attributes +- if (DIR* attrDir = fs_fopen_attr_dir(fd)) { +- AttrDirCloser attrDirCloser(attrDir); +- +- while (dirent* entry = fs_read_attr_dir(attrDir)) { ++ AttrDirCloser attrDir(fs_fopen_attr_dir(fd)); ++ if (attrDir.IsSet()) { ++ while (dirent* entry = fs_read_attr_dir(attrDir.Get())) { + attr_info attrInfo; + if (fs_stat_attr(fd, entry->d_name, &attrInfo) < 0) { + fListener->PrintError( +@@ -1579,17 +1576,16 @@ PackageWriterImpl::_AddDirectoryChildren(Entry* entry, int fd, char* pathBuffer) + throw status_t(errno); + } + +- DIR* dir = fdopendir(clonedFD); +- if (dir == NULL) { ++ DirCloser dir(fdopendir(clonedFD)); ++ if (!dir.IsSet()) { + fListener->PrintError( + "Failed to open directory \"%s\": %s\n", pathBuffer, + strerror(errno)); + close(clonedFD); + throw status_t(errno); + } +- DirCloser dirCloser(dir); + +- while (dirent* entry = readdir(dir)) { ++ while (dirent* entry = readdir(dir.Get())) { + // skip "." and ".." + if (strcmp(entry->d_name, ".") == 0 + || strcmp(entry->d_name, "..") == 0) { +diff --git a/src/kits/package/manager/RepositoryBuilder.cpp b/src/kits/package/manager/RepositoryBuilder.cpp +index fe9bbe395d..236c0b25c4 100644 +--- a/src/kits/package/manager/RepositoryBuilder.cpp ++++ b/src/kits/package/manager/RepositoryBuilder.cpp +@@ -208,13 +208,12 @@ BRepositoryBuilder& + BRepositoryBuilder::AddPackagesDirectory(const char* path) + { + // open directory +- DIR* dir = opendir(path); +- if (dir == NULL) ++ DirCloser dir(opendir(path)); ++ if (!dir.IsSet()) + DIE(errno, "failed to open package directory \"%s\"", path); +- DirCloser dirCloser(dir); + + // iterate through directory entries +- while (dirent* entry = readdir(dir)) { ++ while (dirent* entry = readdir(dir.Get())) { + // skip "." and ".." + const char* name = entry->d_name; + if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) +diff --git a/src/preferences/virtualmemory/Settings.cpp b/src/preferences/virtualmemory/Settings.cpp +index 270defd88e..6752f65024 100644 +--- a/src/preferences/virtualmemory/Settings.cpp ++++ b/src/preferences/virtualmemory/Settings.cpp +@@ -137,22 +137,24 @@ Settings::WriteWindowSettings() + status_t + Settings::ReadSwapSettings() + { +- void* settings = load_driver_settings(kVirtualMemorySettings); +- if (settings == NULL) ++ DriverSettingsUnloader settings( ++ load_driver_settings(kVirtualMemorySettings)); ++ if (!settings.IsSet()) + return kErrorSettingsNotFound; +- DriverSettingsUnloader settingDeleter(settings); +- +- const char* enabled = get_driver_parameter(settings, "vm", NULL, NULL); +- const char* automatic = get_driver_parameter(settings, "swap_auto", +- NULL, NULL); +- const char* size = get_driver_parameter(settings, "swap_size", NULL, NULL); +- const char* volume = get_driver_parameter(settings, "swap_volume_name", +- NULL, NULL); +- const char* device = get_driver_parameter(settings, ++ ++ const char* enabled = get_driver_parameter(settings.Get(), ++ "vm", NULL, NULL); ++ const char* automatic = get_driver_parameter(settings.Get(), ++ "swap_auto", NULL, NULL); ++ const char* size = get_driver_parameter(settings.Get(), ++ "swap_size", NULL, NULL); ++ const char* volume = get_driver_parameter(settings.Get(), ++ "swap_volume_name", NULL, NULL); ++ const char* device = get_driver_parameter(settings.Get(), + "swap_volume_device", NULL, NULL); +- const char* filesystem = get_driver_parameter(settings, ++ const char* filesystem = get_driver_parameter(settings.Get(), + "swap_volume_filesystem", NULL, NULL); +- const char* capacity = get_driver_parameter(settings, ++ const char* capacity = get_driver_parameter(settings.Get(), + "swap_volume_capacity", NULL, NULL); + + if (enabled == NULL || automatic == NULL || size == NULL || device == NULL +@@ -161,9 +163,9 @@ Settings::ReadSwapSettings() + + off_t volCapacity = atoll(capacity); + +- SetSwapEnabled(get_driver_boolean_parameter(settings, ++ SetSwapEnabled(get_driver_boolean_parameter(settings.Get(), + "vm", true, false)); +- SetSwapAutomatic(get_driver_boolean_parameter(settings, ++ SetSwapAutomatic(get_driver_boolean_parameter(settings.Get(), + "swap_auto", true, false)); + SetSwapSize(atoll(size)); + +diff --git a/src/servers/net/NetServer.cpp b/src/servers/net/NetServer.cpp +index 167379d3c5..289f5bf6ce 100644 +--- a/src/servers/net/NetServer.cpp ++++ b/src/servers/net/NetServer.cpp +@@ -118,12 +118,10 @@ static status_t + set_80211(const char* name, int32 type, void* data, + int32 length = 0, int32 value = 0) + { +- int socket = ::socket(AF_INET, SOCK_DGRAM, 0); +- if (socket < 0) ++ FileDescriptorCloser socket(::socket(AF_INET, SOCK_DGRAM, 0)); ++ if (!socket.IsSet()) + return errno; + +- FileDescriptorCloser closer(socket); +- + struct ieee80211req ireq; + strlcpy(ireq.i_name, name, IF_NAMESIZE); + ireq.i_type = type; +@@ -131,7 +129,8 @@ set_80211(const char* name, int32 type, void* data, + ireq.i_len = length; + ireq.i_data = data; + +- if (ioctl(socket, SIOCS80211, &ireq, sizeof(struct ieee80211req)) < 0) ++ if (ioctl(socket.Get(), SIOCS80211, &ireq, sizeof(struct ieee80211req)) ++ < 0) + return errno; + + return B_OK; +diff --git a/src/servers/package/CommitTransactionHandler.cpp b/src/servers/package/CommitTransactionHandler.cpp +index aa3dbfb66b..1cbfbe117f 100644 +--- a/src/servers/package/CommitTransactionHandler.cpp ++++ b/src/servers/package/CommitTransactionHandler.cpp +@@ -1863,18 +1863,17 @@ CommitTransactionHandler::_ChangePackageActivationIOCtl( + } + + // issue the request +- int fd = fVolume->OpenRootDirectory(); +- if (fd < 0) { ++ FileDescriptorCloser fd(fVolume->OpenRootDirectory()); ++ if (!fd.IsSet()) { + throw Exception(B_TRANSACTION_FAILED_TO_OPEN_DIRECTORY) + .SetPath1(_GetPath( + FSUtils::Entry(fVolume->RootDirectoryRef()), + "")) +- .SetSystemError(fd); ++ .SetSystemError(fd.Get()); + } +- FileDescriptorCloser fdCloser(fd); + +- if (ioctl(fd, PACKAGE_FS_OPERATION_CHANGE_ACTIVATION, request, requestSize) +- != 0) { ++ if (ioctl(fd.Get(), PACKAGE_FS_OPERATION_CHANGE_ACTIVATION, request, ++ requestSize) != 0) { + // TODO: We need more error information and error handling! + throw Exception(B_TRANSACTION_FAILED_TO_CHANGE_PACKAGE_ACTIVATION) + .SetSystemError(errno); +diff --git a/src/servers/package/PackageFile.cpp b/src/servers/package/PackageFile.cpp +index 26f5f6ff3c..df8e8def5a 100644 +--- a/src/servers/package/PackageFile.cpp ++++ b/src/servers/package/PackageFile.cpp +@@ -61,12 +61,11 @@ PackageFile::Init(const entry_ref& entryRef, PackageFileManager* owner) + RETURN_ERROR(error); + + // get the package info +- int fd = file.Dup(); +- if (fd < 0) ++ FileDescriptorCloser fd(file.Dup()); ++ if (!fd.IsSet()) + RETURN_ERROR(error); +- FileDescriptorCloser fdCloser(fd); + +- error = fInfo.ReadFromPackageFile(fd); ++ error = fInfo.ReadFromPackageFile(fd.Get()); + if (error != B_OK) + RETURN_ERROR(error); + +diff --git a/src/servers/package/Volume.cpp b/src/servers/package/Volume.cpp +index d2cb6704b8..3065314039 100644 +--- a/src/servers/package/Volume.cpp ++++ b/src/servers/package/Volume.cpp +@@ -230,13 +230,12 @@ Volume::Init(const node_ref& rootDirectoryRef, node_ref& _packageRootRef) + RETURN_ERROR(B_NO_MEMORY); + + // get a volume info from the FS +- int fd = directory.Dup(); +- if (fd < 0) { ++ FileDescriptorCloser fd(directory.Dup()); ++ if (!fd.IsSet()) { + ERROR("Volume::Init(): failed to get root directory FD: %s\n", +- strerror(fd)); +- RETURN_ERROR(fd); ++ strerror(fd.Get())); ++ RETURN_ERROR(fd.Get()); + } +- FileDescriptorCloser fdCloser(fd); + + // get the volume info from packagefs + uint32 maxPackagesDirCount = 16; +@@ -251,7 +250,7 @@ Volume::Init(const node_ref& rootDirectoryRef, node_ref& _packageRootRef) + RETURN_ERROR(B_NO_MEMORY); + infoDeleter.SetTo(info); + +- if (ioctl(fd, PACKAGE_FS_OPERATION_GET_VOLUME_INFO, info, ++ if (ioctl(fd.Get(), PACKAGE_FS_OPERATION_GET_VOLUME_INFO, info, + bufferSize) != 0) { + ERROR("Volume::Init(): failed to get volume info: %s\n", + strerror(errno)); +@@ -310,13 +309,12 @@ Volume::InitPackages(Listener* listener) + } + + // read the packages directory and get the active packages +- int fd = OpenRootDirectory(); +- if (fd < 0) { ++ FileDescriptorCloser fd(OpenRootDirectory()); ++ if (!fd.IsSet()) { + ERROR("Volume::InitPackages(): failed to open root directory: %s\n", +- strerror(fd)); +- RETURN_ERROR(fd); ++ strerror(fd.Get())); ++ RETURN_ERROR(fd.Get()); + } +- FileDescriptorCloser fdCloser(fd); + + error = _ReadPackagesDirectory(); + if (error != B_OK) +@@ -326,7 +324,7 @@ Volume::InitPackages(Listener* listener) + if (error != B_OK) + RETURN_ERROR(error); + +- error = _GetActivePackages(fd); ++ error = _GetActivePackages(fd.Get()); + if (error != B_OK) + RETURN_ERROR(error); + +diff --git a/src/servers/registrar/AuthenticationManager.cpp b/src/servers/registrar/AuthenticationManager.cpp +index ddc6ef9fb6..355b36d920 100644 +--- a/src/servers/registrar/AuthenticationManager.cpp ++++ b/src/servers/registrar/AuthenticationManager.cpp +@@ -564,26 +564,24 @@ public: + // Don't check errors. We can't do anything anyway. + + // open files +- FILE* passwdFile = fopen(kPasswdFile, "w"); +- if (passwdFile == NULL) { ++ FileCloser passwdFile(fopen(kPasswdFile, "w")); ++ if (!passwdFile.IsSet()) { + debug_printf("REG: Failed to open passwd file \"%s\" for " + "writing: %s\n", kPasswdFile, strerror(errno)); + } +- FileCloser _1(passwdFile); + +- FILE* shadowFile = fopen(kShadowPwdFile, "w"); +- if (shadowFile == NULL) { ++ FileCloser shadowFile(fopen(kShadowPwdFile, "w")); ++ if (!shadowFile.IsSet()) { + debug_printf("REG: Failed to open shadow passwd file \"%s\" for " + "writing: %s\n", kShadowPwdFile, strerror(errno)); + } +- FileCloser _2(shadowFile); + + // write users + for (map::const_iterator it = fUsersByID.begin(); + it != fUsersByID.end(); ++it) { + User* user = it->second; +- user->WritePasswdLine(passwdFile); +- user->WriteShadowPwdLine(shadowFile); ++ user->WritePasswdLine(passwdFile.Get()); ++ user->WriteShadowPwdLine(shadowFile.Get()); + } + } + +@@ -690,18 +688,17 @@ public: + // Don't check errors. We can't do anything anyway. + + // open file +- FILE* groupFile = fopen(kGroupFile, "w"); +- if (groupFile == NULL) { ++ FileCloser groupFile(fopen(kGroupFile, "w")); ++ if (!groupFile.IsSet()) { + debug_printf("REG: Failed to open group file \"%s\" for " + "writing: %s\n", kGroupFile, strerror(errno)); + } +- FileCloser _1(groupFile); + + // write groups + for (map::const_iterator it = fGroupsByID.begin(); + it != fGroupsByID.end(); ++it) { + Group* group = it->second; +- group->WriteGroupLine(groupFile); ++ group->WriteGroupLine(groupFile.Get()); + } + } + +@@ -1240,16 +1237,15 @@ AuthenticationManager::_RequestThread() + status_t + AuthenticationManager::_InitPasswdDB() + { +- FILE* file = fopen(kPasswdFile, "r"); +- if (file == NULL) { ++ FileCloser file(fopen(kPasswdFile, "r")); ++ if (!file.IsSet()) { + debug_printf("REG: Failed to open passwd DB file \"%s\": %s\n", + kPasswdFile, strerror(errno)); + return errno; + } +- FileCloser _(file); + + char lineBuffer[LINE_MAX]; +- while (char* line = fgets(lineBuffer, sizeof(lineBuffer), file)) { ++ while (char* line = fgets(lineBuffer, sizeof(lineBuffer), file.Get())) { + if (strlen(line) == 0) + continue; + +@@ -1289,16 +1285,15 @@ AuthenticationManager::_InitPasswdDB() + status_t + AuthenticationManager::_InitGroupDB() + { +- FILE* file = fopen(kGroupFile, "r"); +- if (file == NULL) { ++ FileCloser file(fopen(kGroupFile, "r")); ++ if (!file.IsSet()) { + debug_printf("REG: Failed to open group DB file \"%s\": %s\n", + kGroupFile, strerror(errno)); + return errno; + } +- FileCloser _(file); + + char lineBuffer[LINE_MAX]; +- while (char* line = fgets(lineBuffer, sizeof(lineBuffer), file)) { ++ while (char* line = fgets(lineBuffer, sizeof(lineBuffer), file.Get())) { + if (strlen(line) == 0) + continue; + +@@ -1337,16 +1332,15 @@ AuthenticationManager::_InitGroupDB() + status_t + AuthenticationManager::_InitShadowPwdDB() + { +- FILE* file = fopen(kShadowPwdFile, "r"); +- if (file == NULL) { ++ FileCloser file(fopen(kShadowPwdFile, "r")); ++ if (!file.IsSet()) { + debug_printf("REG: Failed to open shadow passwd DB file \"%s\": %s\n", + kShadowPwdFile, strerror(errno)); + return errno; + } +- FileCloser _(file); + + char lineBuffer[LINE_MAX]; +- while (char* line = fgets(lineBuffer, sizeof(lineBuffer), file)) { ++ while (char* line = fgets(lineBuffer, sizeof(lineBuffer), file.Get())) { + if (strlen(line) == 0) + continue; + +diff --git a/src/system/boot/loader/file_systems/packagefs/PackageSettingsItem.cpp b/src/system/boot/loader/file_systems/packagefs/PackageSettingsItem.cpp +index 85e9f4be38..f62115fcf4 100644 +--- a/src/system/boot/loader/file_systems/packagefs/PackageSettingsItem.cpp ++++ b/src/system/boot/loader/file_systems/packagefs/PackageSettingsItem.cpp +@@ -45,18 +45,17 @@ PackageSettingsItem::Load(::Directory* systemDirectory, const char* name) + const char* settingsFilePath + = &(kSystemSettingsDirectory "/packages")[strlen(kSystemDirectory) + 1]; + +- int fd = open_from(systemDirectory, settingsFilePath, B_READ_ONLY, 0); +- if (fd < 0) ++ FileDescriptorCloser fd(open_from(systemDirectory, settingsFilePath, ++ B_READ_ONLY, 0)); ++ if (!fd.IsSet()) + return NULL; +- FileDescriptorCloser fdCloser(fd); + + // load the driver settings +- void* settingsHandle = load_driver_settings_file(fd); +- if (settingsHandle == NULL) ++ DriverSettingsUnloader settingsHandle(load_driver_settings_file(fd.Get())); ++ if (!settingsHandle.IsSet()) + return NULL; +- DriverSettingsUnloader settingsDeleter(settingsHandle); + +- const driver_settings* settings = get_driver_settings(settingsHandle); ++ const driver_settings* settings = get_driver_settings(settingsHandle.Get()); + for (int i = 0; i < settings->parameter_count; i++) { + const driver_parameter& parameter = settings->parameters[i]; + if (strcmp(parameter.name, "Package") != 0 +diff --git a/src/system/boot/loader/package_support.cpp b/src/system/boot/loader/package_support.cpp +index 12ab7c77b6..7a60f212fb 100644 +--- a/src/system/boot/loader/package_support.cpp ++++ b/src/system/boot/loader/package_support.cpp +@@ -326,13 +326,12 @@ PackageVolumeInfo::_ParseActivatedPackagesFile(Directory* packagesDirectory, + snprintf(path, sizeof(path), "%s/%s/%s", + kAdministrativeDirectory, state->Name() != NULL ? state->Name() : "", + kActivatedPackagesFile); +- int fd = open_from(packagesDirectory, path, O_RDONLY); +- if (fd < 0) +- return fd; +- FileDescriptorCloser fdCloser(fd); ++ FileDescriptorCloser fd(open_from(packagesDirectory, path, O_RDONLY)); ++ if (!fd.IsSet()) ++ return fd.Get(); + + struct stat st; +- if (fstat(fd, &st) != 0) ++ if (fstat(fd.Get(), &st) != 0) + return errno; + if (!S_ISREG(st.st_mode)) + return B_ENTRY_NOT_FOUND; +@@ -340,7 +339,7 @@ PackageVolumeInfo::_ParseActivatedPackagesFile(Directory* packagesDirectory, + // read the file until we find the system package line + size_t remainingBytes = 0; + for (;;) { +- ssize_t bytesRead = read(fd, path + remainingBytes, ++ ssize_t bytesRead = read(fd.Get(), path + remainingBytes, + sizeof(path) - remainingBytes - 1); + if (bytesRead <= 0) + return B_ENTRY_NOT_FOUND; +diff --git a/src/system/libnetwork/getifaddrs.cpp b/src/system/libnetwork/getifaddrs.cpp +index 005bc082f9..34493056f3 100644 +--- a/src/system/libnetwork/getifaddrs.cpp ++++ b/src/system/libnetwork/getifaddrs.cpp +@@ -53,16 +53,15 @@ copy_address(const sockaddr& address) + static int + _getifaddrs(int domain, char* buffer, size_t len, struct ifaddrs** previous) + { +- int socket = ::socket(domain, SOCK_DGRAM, 0); +- if (socket < 0) ++ FileDescriptorCloser socket (::socket(domain, SOCK_DGRAM, 0)); ++ if (!socket.IsSet()) + return -1; +- FileDescriptorCloser closer(socket); + + // Get interfaces configuration + ifconf config; + config.ifc_buf = buffer; + config.ifc_len = len; +- if (ioctl(socket, SIOCGIFCONF, &config, sizeof(struct ifconf)) < 0) ++ if (ioctl(socket.Get(), SIOCGIFCONF, &config, sizeof(struct ifconf)) < 0) + return -1; + + ifreq* interfaces = (ifreq*)buffer; +@@ -88,13 +87,14 @@ _getifaddrs(int domain, char* buffer, size_t len, struct ifaddrs** previous) + ifreq request; + strlcpy(request.ifr_name, interfaces[0].ifr_name, IF_NAMESIZE); + +- if (ioctl(socket, SIOCGIFFLAGS, &request, sizeof(struct ifreq)) == 0) ++ if (ioctl(socket.Get(), SIOCGIFFLAGS, &request, sizeof(struct ifreq)) ++ == 0) + current->ifa_flags = request.ifr_flags; +- if (ioctl(socket, SIOCGIFNETMASK, &request, sizeof(struct ifreq)) ++ if (ioctl(socket.Get(), SIOCGIFNETMASK, &request, sizeof(struct ifreq)) + == 0) { + current->ifa_netmask = copy_address(request.ifr_mask); + } +- if (ioctl(socket, SIOCGIFDSTADDR, &request, sizeof(struct ifreq)) ++ if (ioctl(socket.Get(), SIOCGIFDSTADDR, &request, sizeof(struct ifreq)) + == 0) { + current->ifa_dstaddr = copy_address(request.ifr_dstaddr); + } +@@ -117,20 +117,17 @@ getifaddrs(struct ifaddrs** _ifaddrs) + return -1; + } + +- int socket = ::socket(AF_INET, SOCK_DGRAM, 0); +- if (socket < 0) ++ FileDescriptorCloser socket(::socket(AF_INET, SOCK_DGRAM, 0)); ++ if (!socket.IsSet()) + return -1; + +- FileDescriptorCloser closer(socket); +- + // Get interface count + ifconf config; + config.ifc_len = sizeof(config.ifc_value); +- if (ioctl(socket, SIOCGIFCOUNT, &config, sizeof(struct ifconf)) < 0) ++ if (ioctl(socket.Get(), SIOCGIFCOUNT, &config, sizeof(struct ifconf)) < 0) + return -1; + +- socket = -1; +- closer.Unset(); ++ socket.Unset(); + + size_t count = (size_t)config.ifc_value; + if (count == 0) { +@@ -141,27 +138,25 @@ getifaddrs(struct ifaddrs** _ifaddrs) + + // Allocate a buffer for ifreqs for all interfaces + size_t buflen = count * sizeof(struct ifreq); +- char* buffer = (char*)malloc(buflen); +- if (buffer == NULL) { ++ ArrayDeleter buffer(new(std::nothrow) char[buflen]); ++ if (!buffer.IsSet()) { + errno = B_NO_MEMORY; + return -1; + } + +- MemoryDeleter deleter(buffer); +- + struct ifaddrs* previous = NULL; + int serrno = errno; +- if (_getifaddrs(AF_INET, buffer, buflen, &previous) < 0 && ++ if (_getifaddrs(AF_INET, buffer.Get(), buflen, &previous) < 0 && + errno != B_UNSUPPORTED) { + freeifaddrs(previous); + return -1; + } +- if (_getifaddrs(AF_INET6, buffer, buflen, &previous) < 0 && ++ if (_getifaddrs(AF_INET6, buffer.Get(), buflen, &previous) < 0 && + errno != B_UNSUPPORTED) { + freeifaddrs(previous); + return -1; + } +- if (_getifaddrs(AF_LINK, buffer, buflen, &previous) < 0 && ++ if (_getifaddrs(AF_LINK, buffer.Get(), buflen, &previous) < 0 && + errno != B_UNSUPPORTED) { + freeifaddrs(previous); + return -1; +diff --git a/src/system/libroot/os/image.cpp b/src/system/libroot/os/image.cpp +index caf4adb873..428636b4a1 100644 +--- a/src/system/libroot/os/image.cpp ++++ b/src/system/libroot/os/image.cpp +@@ -43,17 +43,16 @@ struct EnvironmentFilter { + + void Init(const char* path, const char* const* env, size_t envCount) + { +- int fd = open(path, O_RDONLY); +- if (fd < 0) ++ FileDescriptorCloser fd(open(path, O_RDONLY)); ++ if (!fd.IsSet()) + return; +- FileDescriptorCloser fdCloser(fd); + + static const char* const kEnvAttribute = "SYS:ENV"; + attr_info info; +- if (fs_stat_attr(fd, kEnvAttribute, &info) < 0) ++ if (fs_stat_attr(fd.Get(), kEnvAttribute, &info) < 0) + return; + +- _Init(fd, kEnvAttribute, info.size, env, envCount); ++ _Init(fd.Get(), kEnvAttribute, info.size, env, envCount); + } + + size_t AdditionalSlotsNeeded() const +diff --git a/src/tools/generate_boot_screen.cpp b/src/tools/generate_boot_screen.cpp +index 5869ad26d3..264a94062e 100644 +--- a/src/tools/generate_boot_screen.cpp ++++ b/src/tools/generate_boot_screen.cpp +@@ -56,23 +56,6 @@ new_line_if_required() + // #pragma mark - + + +-class AutoFileCloser { +-public: +- AutoFileCloser(FILE* file) +- : fFile(file) +- {} +- ~AutoFileCloser() +- { +- fclose(fFile); +- } +-private: +- FILE* fFile; +-}; +- +- +-// #pragma mark - +- +- + class ZlibCompressor { + public: + ZlibCompressor(FILE* output); +@@ -162,13 +145,11 @@ read_png(const char* filename, int& width, int& height, png_bytep*& rowPtrs, + png_structp& pngPtr, png_infop& infoPtr) + { + char header[8]; +- FILE* input = fopen(filename, "rb"); +- if (!input) ++ FileCloser input(fopen(filename, "rb")); ++ if (!input.IsSet()) + error("[read_png] File %s could not be opened for reading", filename); + +- AutoFileCloser _(input); +- +- fread(header, 1, 8, input); ++ fread(header, 1, 8, input.Get()); + if (png_sig_cmp((png_byte *)header, 0, 8 )) + error("[read_png] File %s is not recognized as a PNG file", filename); + +@@ -187,7 +168,7 @@ read_png(const char* filename, int& width, int& height, png_bytep*& rowPtrs, + error("[read_png] Error during init_io"); + #endif + +- png_init_io(pngPtr, input); ++ png_init_io(pngPtr, input.Get()); + png_set_sig_bytes(pngPtr, 8); + + // make sure we automatically get RGB data with 8 bits per channel +-- +2.30.2 + diff --git a/patchset-hrev55144/0028-libbe_test-add-StyledEdit.patch b/patchset-hrev55144/0028-libbe_test-add-StyledEdit.patch new file mode 100644 index 0000000..a3bb9cb --- /dev/null +++ b/patchset-hrev55144/0028-libbe_test-add-StyledEdit.patch @@ -0,0 +1,36 @@ +From 28ee978c18b22b2b0142234cfb7f2467a0ccfd60 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sat, 12 Dec 2020 08:41:49 +0900 +Subject: libbe_test: add StyledEdit + +Change-Id: I8253c54627ff31f2e846a7060cf9d5ed8a5fdb93 +--- + src/apps/stylededit/Jamfile | 6 +++++- + 1 file changed, 5 insertions(+), 1 deletion(-) + +diff --git a/src/apps/stylededit/Jamfile b/src/apps/stylededit/Jamfile +index 7954a0c16f..409076300b 100644 +--- a/src/apps/stylededit/Jamfile ++++ b/src/apps/stylededit/Jamfile +@@ -1,5 +1,9 @@ + SubDir HAIKU_TOP src apps stylededit ; + ++if $(TARGET_PLATFORM) = libbe_test { ++ SetSubDirSupportedPlatforms libbe_test ; ++} ++ + UsePrivateHeaders textencoding ; + UsePrivateSystemHeaders ; + UsePrivateHeaders tracker shared ; +@@ -26,7 +30,7 @@ Application StyledEdit : + StyledEditView.cpp + StyledEditWindow.cpp + : shared be translation tracker libtextencoding.so localestub +- [ TargetLibsupc++ ] ++ [ TargetLibstdc++ ] [ TargetLibsupc++ ] + : $(styled_edit_rsrc) + ; + +-- +2.30.2 + diff --git a/patchset-hrev55144/0029-app_server-fix-integer-overflow-in-ServerBitmap.patch b/patchset-hrev55144/0029-app_server-fix-integer-overflow-in-ServerBitmap.patch new file mode 100644 index 0000000..326fbfd --- /dev/null +++ b/patchset-hrev55144/0029-app_server-fix-integer-overflow-in-ServerBitmap.patch @@ -0,0 +1,47 @@ +From 03e09185f81cd24d0fb3d0b0fe97805d552bdb64 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Thu, 14 Jan 2021 06:04:30 +0900 +Subject: app_server: fix integer overflow in ServerBitmap + +Integer overflow caused bitmap buffer creation of wrong size and out of +bounds access when large bitmap was created. Now allocation failure is +reported for large bitmaps. + +Change-Id: I297aa6e3b79b32a486d297f1239a1fd4397a8a36 +--- + src/servers/app/ServerBitmap.h | 12 +++++++++--- + 1 file changed, 9 insertions(+), 3 deletions(-) + +diff --git a/src/servers/app/ServerBitmap.h b/src/servers/app/ServerBitmap.h +index 83be161e9b..f329a03f98 100644 +--- a/src/servers/app/ServerBitmap.h ++++ b/src/servers/app/ServerBitmap.h +@@ -40,9 +40,7 @@ public: + + inline uint8* Bits() const + { return fBuffer; } +- inline uint32 BitsLength() const +- { return (uint32)(fBytesPerRow * fHeight); } +- ++ inline uint32 BitsLength() const; + inline BRect Bounds() const + { return BRect(0, 0, fWidth - 1, fHeight - 1); } + inline int32 Width() const +@@ -126,6 +124,14 @@ public: + }; + + ++uint32 ++ServerBitmap::BitsLength() const ++{ ++ int64 length = fBytesPerRow * fHeight; ++ return (length > 0 && length <= UINT32_MAX) ? (uint32)length : 0; ++} ++ ++ + //! (only for server bitmaps) + void + ServerBitmap::ShallowCopy(const ServerBitmap* from) +-- +2.30.2 + diff --git a/patchset-hrev55144/0030-runtime_loader-export-loaded-module-list.patch b/patchset-hrev55144/0030-runtime_loader-export-loaded-module-list.patch new file mode 100644 index 0000000..47744fd --- /dev/null +++ b/patchset-hrev55144/0030-runtime_loader-export-loaded-module-list.patch @@ -0,0 +1,54 @@ +From 90c3e96c4e1571671b87d380fe84f7e5e21275b7 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Fri, 15 Jan 2021 11:22:29 +0900 +Subject: runtime_loader: export loaded module list + +Change-Id: I51cd3193960cf927ce9538c4d5ad0e80338c8979 +--- + headers/private/runtime_loader/runtime_loader.h | 2 ++ + src/system/runtime_loader/export.cpp | 2 ++ + 2 files changed, 4 insertions(+) + +diff --git a/headers/private/runtime_loader/runtime_loader.h b/headers/private/runtime_loader/runtime_loader.h +index 2cf0a271e8..590936ff12 100644 +--- a/headers/private/runtime_loader/runtime_loader.h ++++ b/headers/private/runtime_loader/runtime_loader.h +@@ -23,6 +23,7 @@ + + struct user_space_program_args; + struct SymbolLookupInfo; ++struct image_queue_t; + + struct rld_export { + // runtime loader API export +@@ -59,6 +60,7 @@ struct rld_export { + const void* commpage_address; + int abi_version; + int api_version; ++ struct image_queue_t *loaded_images; + }; + + extern struct rld_export *__gRuntimeLoader; +diff --git a/src/system/runtime_loader/export.cpp b/src/system/runtime_loader/export.cpp +index 70c742d006..1dfdf2f9f0 100644 +--- a/src/system/runtime_loader/export.cpp ++++ b/src/system/runtime_loader/export.cpp +@@ -9,6 +9,7 @@ + + #include "runtime_loader_private.h" + #include "elf_tls.h" ++#include "images.h" + + + // exported via the rld_export structure in user space program arguments +@@ -90,6 +91,7 @@ rldexport_init(void) + { + gRuntimeLoader.program_args = gProgramArgs; + gRuntimeLoader.commpage_address = __gCommPageAddress; ++ gRuntimeLoader.loaded_images = &get_loaded_images(); + } + + +-- +2.30.2 + diff --git a/patchset-hrev55144/0031-kernel-add-IO-statistics-support.patch b/patchset-hrev55144/0031-kernel-add-IO-statistics-support.patch new file mode 100644 index 0000000..aae1cbf --- /dev/null +++ b/patchset-hrev55144/0031-kernel-add-IO-statistics-support.patch @@ -0,0 +1,294 @@ +From 96ed04469f0d6707c01e9e93b01f46858d0326d7 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sat, 16 Jan 2021 12:06:46 +0900 +Subject: kernel: add IO statistics support + +scsi_disk and usb_disk are supported. + +Helps with #16255. + +Change-Id: I1f7205141c52069c4e6db9cc885fbb001d3a9b32 +--- + headers/os/drivers/Drivers.h | 8 ++++++ + .../drivers/disk/scsi/scsi_disk/scsi_disk.cpp | 14 +++++++++++ + .../drivers/disk/usb/usb_disk/usb_disk.cpp | 17 +++++++++++++ + .../drivers/disk/usb/usb_disk/usb_disk.h | 4 +++ + src/system/kernel/device_manager/IOCache.cpp | 25 ++++++++++++++++++- + src/system/kernel/device_manager/IOCache.h | 5 ++++ + .../kernel/device_manager/IOScheduler.h | 3 +++ + .../device_manager/IOSchedulerSimple.cpp | 21 ++++++++++++++++ + .../kernel/device_manager/IOSchedulerSimple.h | 5 ++++ + 9 files changed, 101 insertions(+), 1 deletion(-) + +diff --git a/headers/os/drivers/Drivers.h b/headers/os/drivers/Drivers.h +index a8b4d7f788..319223d6b8 100644 +--- a/headers/os/drivers/Drivers.h ++++ b/headers/os/drivers/Drivers.h +@@ -107,6 +107,7 @@ enum { + B_GET_VECTOR_ICON, /* retrieves the device's vector icon */ + B_GET_DEVICE_NAME, /* get name, string buffer */ + B_TRIM_DEVICE, /* trims blocks, see fs_trim_data */ ++ B_GET_IO_STATS, /* get IO statistics, see device_io_stats */ + + B_GET_NEXT_OPEN_DEVICE = 1000, /* obsolete, will be removed */ + B_ADD_FIXED_DRIVER, /* obsolete, will be removed */ +@@ -181,6 +182,13 @@ typedef struct { + } fs_trim_data; + + ++/* B_GET_IO_STATS data structure */ ++typedef struct { ++ uint64 read_bytes; ++ uint64 write_bytes; ++} device_io_stats; ++ ++ + #ifdef __cplusplus + } + #endif +diff --git a/src/add-ons/kernel/drivers/disk/scsi/scsi_disk/scsi_disk.cpp b/src/add-ons/kernel/drivers/disk/scsi/scsi_disk/scsi_disk.cpp +index 0d6b1188df..69e3fcf504 100644 +--- a/src/add-ons/kernel/drivers/disk/scsi/scsi_disk/scsi_disk.cpp ++++ b/src/add-ons/kernel/drivers/disk/scsi/scsi_disk/scsi_disk.cpp +@@ -405,6 +405,20 @@ das_ioctl(void* cookie, uint32 op, void* buffer, size_t length) + return user_memcpy(buffer, &iconData, sizeof(device_icon)); + } + ++ case B_GET_IO_STATS: ++ { ++ if (length > sizeof(device_io_stats)) ++ return B_BAD_VALUE; ++ ++ device_io_stats stats; ++ status_t status ++ = handle->info->io_scheduler->GetStats(&stats, length); ++ if (status < B_OK) ++ return status; ++ ++ return user_memcpy(buffer, &stats, length); ++ } ++ + case B_EJECT_DEVICE: + case B_SCSI_EJECT: + return load_eject(info, false); +diff --git a/src/add-ons/kernel/drivers/disk/usb/usb_disk/usb_disk.cpp b/src/add-ons/kernel/drivers/disk/usb/usb_disk/usb_disk.cpp +index 4660a87d1f..351f791a4c 100644 +--- a/src/add-ons/kernel/drivers/disk/usb/usb_disk/usb_disk.cpp ++++ b/src/add-ons/kernel/drivers/disk/usb/usb_disk/usb_disk.cpp +@@ -1403,6 +1403,9 @@ usb_disk_device_added(usb_device newDevice, void **cookie) + memset(lun->product_name, 0, sizeof(lun->product_name)); + memset(lun->product_revision, 0, sizeof(lun->product_revision)); + ++ lun->read_bytes = 0; ++ lun->write_bytes = 0; ++ + usb_disk_reset_capacity(lun); + + // initialize this lun +@@ -1974,6 +1977,18 @@ usb_disk_ioctl(void *cookie, uint32 op, void *buffer, size_t length) + strerror(result)); + return result; + } ++ ++ case B_GET_IO_STATS: ++ { ++ if (length > sizeof(device_io_stats)) ++ return B_BAD_VALUE; ++ ++ device_io_stats stats; ++ stats.read_bytes = lun->read_bytes; ++ stats.write_bytes = lun->write_bytes; ++ ++ return user_memcpy(buffer, &stats, length); ++ } + } + + TRACE_ALWAYS("unhandled ioctl %" B_PRId32 "\n", op); +@@ -2021,6 +2036,7 @@ usb_disk_read(void *cookie, off_t position, void *buffer, size_t *length) + + mutex_unlock(&device->lock); + if (result == B_OK) { ++ lun->read_bytes += *length; + TRACE("read successful with %ld bytes\n", *length); + return B_OK; + } +@@ -2077,6 +2093,7 @@ usb_disk_write(void *cookie, off_t position, const void *buffer, + + mutex_unlock(&device->lock); + if (result == B_OK) { ++ lun->write_bytes += *length; + TRACE("write successful with %ld bytes\n", *length); + return B_OK; + } +diff --git a/src/add-ons/kernel/drivers/disk/usb/usb_disk/usb_disk.h b/src/add-ons/kernel/drivers/disk/usb/usb_disk/usb_disk.h +index 8008032251..6209ee14de 100644 +--- a/src/add-ons/kernel/drivers/disk/usb/usb_disk/usb_disk.h ++++ b/src/add-ons/kernel/drivers/disk/usb/usb_disk/usb_disk.h +@@ -77,6 +77,10 @@ struct device_lun_s { + char vendor_name[8]; + char product_name[16]; + char product_revision[4]; ++ ++ // statistics ++ uint64 read_bytes; ++ uint64 write_bytes; + }; + + +diff --git a/src/system/kernel/device_manager/IOCache.cpp b/src/system/kernel/device_manager/IOCache.cpp +index 050cf2bc7f..8e24c4ac94 100644 +--- a/src/system/kernel/device_manager/IOCache.cpp ++++ b/src/system/kernel/device_manager/IOCache.cpp +@@ -47,7 +47,9 @@ IOCache::IOCache(DMAResource* resource, size_t cacheLineSize) + fArea(-1), + fCache(NULL), + fPages(NULL), +- fVecs(NULL) ++ fVecs(NULL), ++ fReadBytes(0), ++ fWriteBytes(0) + { + ASSERT(resource != NULL); + TRACE("%p->IOCache::IOCache(%p, %" B_PRIuSIZE ")\n", this, resource, +@@ -204,6 +206,14 @@ IOCache::OperationCompleted(IOOperation* operation, status_t status, + generic_size_t transferredBytes) + { + if (status == B_OK) { ++ // statistics ++ if (transferredBytes == operation->Length()) { ++ if (operation->IsRead()) ++ fReadBytes += transferredBytes; ++ else ++ fWriteBytes += transferredBytes; ++ } ++ + // always fail in case of partial transfers + ((Operation*)operation)->finishedCondition.NotifyAll( + transferredBytes == operation->Length() ? B_OK : B_ERROR); +@@ -212,6 +222,19 @@ IOCache::OperationCompleted(IOOperation* operation, status_t status, + } + + ++status_t ++IOCache::GetStats(device_io_stats* stats, size_t statsSize) const ++{ ++ if (stats == NULL || statsSize != sizeof(device_io_stats)) ++ return B_BAD_VALUE; ++ ++ stats->read_bytes = fReadBytes; ++ stats->write_bytes = fWriteBytes; ++ ++ return B_OK; ++} ++ ++ + void + IOCache::Dump() const + { +diff --git a/src/system/kernel/device_manager/IOCache.h b/src/system/kernel/device_manager/IOCache.h +index 32a617724b..cbbbe88868 100644 +--- a/src/system/kernel/device_manager/IOCache.h ++++ b/src/system/kernel/device_manager/IOCache.h +@@ -36,6 +36,9 @@ public: + status_t status, + generic_size_t transferredBytes); + ++ virtual status_t GetStats(device_io_stats* stats, ++ size_t statsSize) const; ++ + virtual void Dump() const; + + private: +@@ -78,6 +81,8 @@ private: + VMCache* fCache; + vm_page** fPages; + generic_io_vec* fVecs; ++ uint64 fReadBytes; ++ uint64 fWriteBytes; + }; + + +diff --git a/src/system/kernel/device_manager/IOScheduler.h b/src/system/kernel/device_manager/IOScheduler.h +index 7cfe27a68d..3a08ae3075 100644 +--- a/src/system/kernel/device_manager/IOScheduler.h ++++ b/src/system/kernel/device_manager/IOScheduler.h +@@ -59,6 +59,9 @@ public: + // has been completed successfully or failed + // for some reason + ++ virtual status_t GetStats(device_io_stats* stats, ++ size_t statsSize) const = 0; ++ + virtual void Dump() const = 0; + + protected: +diff --git a/src/system/kernel/device_manager/IOSchedulerSimple.cpp b/src/system/kernel/device_manager/IOSchedulerSimple.cpp +index 1edaf5e08d..63e0045b35 100644 +--- a/src/system/kernel/device_manager/IOSchedulerSimple.cpp ++++ b/src/system/kernel/device_manager/IOSchedulerSimple.cpp +@@ -94,6 +94,8 @@ IOSchedulerSimple::IOSchedulerSimple(DMAResource* resource) + fRequestOwners(NULL), + fBlockSize(0), + fPendingOperations(0), ++ fReadBytes(0), ++ fWriteBytes(0), + fTerminating(false) + { + mutex_init(&fLock, "I/O scheduler"); +@@ -299,11 +301,30 @@ IOSchedulerSimple::OperationCompleted(IOOperation* operation, status_t status, + operation->SetTransferredBytes( + transferredBytes > partialBegin ? transferredBytes - partialBegin : 0); + ++ // statistics ++ if (operation->IsRead()) ++ fReadBytes += transferredBytes; ++ else ++ fWriteBytes += transferredBytes; ++ + fCompletedOperations.Add(operation); + fFinishedOperationCondition.NotifyAll(); + } + + ++status_t ++IOSchedulerSimple::GetStats(device_io_stats* stats, size_t statsSize) const ++{ ++ if (stats == NULL || statsSize != sizeof(device_io_stats)) ++ return B_BAD_VALUE; ++ ++ stats->read_bytes = fReadBytes; ++ stats->write_bytes = fWriteBytes; ++ ++ return B_OK; ++} ++ ++ + void + IOSchedulerSimple::Dump() const + { +diff --git a/src/system/kernel/device_manager/IOSchedulerSimple.h b/src/system/kernel/device_manager/IOSchedulerSimple.h +index 662b7b888e..f525992109 100644 +--- a/src/system/kernel/device_manager/IOSchedulerSimple.h ++++ b/src/system/kernel/device_manager/IOSchedulerSimple.h +@@ -35,6 +35,9 @@ public: + // has been completed successfully or failed + // for some reason + ++ virtual status_t GetStats(device_io_stats* stats, ++ size_t statsSize) const; ++ + virtual void Dump() const; + + private: +@@ -90,6 +93,8 @@ private: + off_t fIterationBandwidth; + off_t fMinOwnerBandwidth; + off_t fMaxOwnerBandwidth; ++ uint64 fReadBytes; ++ uint64 fWriteBytes; + volatile bool fTerminating; + }; + +-- +2.30.2 + diff --git a/patchset-hrev55144/0032-BTextView-Fix-scrolling-in-text-view.patch b/patchset-hrev55144/0032-BTextView-Fix-scrolling-in-text-view.patch new file mode 100644 index 0000000..a148554 --- /dev/null +++ b/patchset-hrev55144/0032-BTextView-Fix-scrolling-in-text-view.patch @@ -0,0 +1,130 @@ +From f58c470cb9e6c8eb735e83f13c832dab7ef09a53 Mon Sep 17 00:00:00 2001 +From: John Scipione +Date: Sun, 17 Jan 2021 14:57:07 -0500 +Subject: BTextView: Fix scrolling in text view + +Prevent scrolling out of bounds horizontally. The algorithm to keep +cursor in text view bounds was taken from _PerformAutoScrolling() +(mouse scrolling method) and was fixed to account for the left +margin which is not always 0. + +Fix left and top margin scrolling not always 0 in +_PerformAutoScrolling() as well, this fixes a similar bug that +was present when scrolling the text with the mouse instead. + +Remove extraSpace variable, no longer needed. + +This makes text views behave properly when overflow occurs i.e. when +you type text off the end of the text view. Instead of scrolling an +entire page over, it nudges the text over as you'd expect. + +Replace xDiff and yDiff float variables with a single scrollTo BPoint +in ScrollToOffset(). This was also copied from _PerformAutoScrolling(). + +Remove floorf() calls, we know that we are dealing with integers. + +Take top and bottom margins into account when scrolling with keyboard +in ScrollToOffset(). This allows you to scroll past the margins all the +way to the top and bottom using the up and down arrow keys (1 more px.) + +Fixes #16642, #16476 + +Change-Id: I2d32d6039944d2dc3218ce4de71f2966cc98c866 +--- + src/kits/interface/TextView.cpp | 53 +++++++++++++++++++-------------- + 1 file changed, 31 insertions(+), 22 deletions(-) + +diff --git a/src/kits/interface/TextView.cpp b/src/kits/interface/TextView.cpp +index 695688c411..b51c4b7796 100644 +--- a/src/kits/interface/TextView.cpp ++++ b/src/kits/interface/TextView.cpp +@@ -2164,30 +2164,38 @@ BTextView::ScrollToOffset(int32 offset) + { + BRect bounds = Bounds(); + float lineHeight = 0.0; +- float xDiff = 0.0; +- float yDiff = 0.0; + BPoint point = PointAt(offset, &lineHeight); ++ BPoint scrollBy(B_ORIGIN); + + // horizontal +- float extraSpace = ceilf(bounds.IntegerWidth() / 2); + if (point.x < bounds.left) +- xDiff = point.x - bounds.right + extraSpace; ++ scrollBy.x = point.x - bounds.right; + else if (point.x > bounds.right) +- xDiff = point.x - bounds.left - extraSpace; ++ scrollBy.x = point.x - bounds.left; + +- // vertical +- if (point.y < bounds.top) +- yDiff = point.y - bounds.top; +- else if (point.y + lineHeight > bounds.bottom +- && point.y - lineHeight > bounds.top) { +- yDiff = point.y + lineHeight - bounds.bottom; ++ // prevent from scrolling out of view ++ if (scrollBy.x != 0.0) { ++ float rightMax = fTextRect.right + fLayoutData->rightInset; ++ if (bounds.right + scrollBy.x > rightMax) ++ scrollBy.x = rightMax - bounds.right; ++ float leftMin = fTextRect.left - fLayoutData->leftInset; ++ if (bounds.left + scrollBy.x < leftMin) ++ scrollBy.x = leftMin - bounds.left; + } + +- // prevent negative scroll offset in y +- if (bounds.top + yDiff < 0.0) +- yDiff = -bounds.top; ++ // vertical ++ if (CountLines() > 1) { ++ // scroll in Y only if multiple lines! ++ if (point.y < bounds.top - fLayoutData->topInset) ++ scrollBy.y = point.y - bounds.top - fLayoutData->topInset; ++ else if (point.y + lineHeight > bounds.bottom ++ + fLayoutData->bottomInset) { ++ scrollBy.y = point.y + lineHeight - bounds.bottom ++ + fLayoutData->bottomInset; ++ } ++ } + +- ScrollBy(xDiff, yDiff); ++ ScrollBy(scrollBy.x, scrollBy.y); + } + + +@@ -4939,11 +4947,12 @@ BTextView::_PerformAutoScrolling() + + // prevent from scrolling out of view + if (scrollBy.x != 0.0) { +- float rightMax = floorf(fTextRect.right + fLayoutData->rightInset); ++ float rightMax = fTextRect.right + fLayoutData->rightInset; + if (bounds.right + scrollBy.x > rightMax) + scrollBy.x = rightMax - bounds.right; +- if (bounds.left + scrollBy.x < 0) +- scrollBy.x = -bounds.left; ++ float leftMin = fTextRect.left - fLayoutData->leftInset; ++ if (bounds.left + scrollBy.x < leftMin) ++ scrollBy.x = leftMin - bounds.left; + } + + if (CountLines() > 1) { +@@ -4955,12 +4964,12 @@ BTextView::_PerformAutoScrolling() + + // prevent from scrolling out of view + if (scrollBy.y != 0.0) { +- float bottomMax = floorf(fTextRect.bottom +- + fLayoutData->bottomInset); ++ float bottomMax = fTextRect.bottom + fLayoutData->bottomInset; + if (bounds.bottom + scrollBy.y > bottomMax) + scrollBy.y = bottomMax - bounds.bottom; +- if (bounds.top + scrollBy.y < 0) +- scrollBy.y = -bounds.top; ++ float topMin = fTextRect.top - fLayoutData->topInset; ++ if (bounds.top + scrollBy.y < topMin) ++ scrollBy.y = topMin - bounds.top; + } + } + +-- +2.30.2 + diff --git a/patchset-hrev55144/0033-usb_disk-more-use-of-MutexLocker.patch b/patchset-hrev55144/0033-usb_disk-more-use-of-MutexLocker.patch new file mode 100644 index 0000000..ce7a118 --- /dev/null +++ b/patchset-hrev55144/0033-usb_disk-more-use-of-MutexLocker.patch @@ -0,0 +1,286 @@ +From d914ee5ca8972960a9714d83b2bda5b7d6359cee Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 24 Jan 2021 11:40:33 +0900 +Subject: usb_disk: more use of MutexLocker + +Change-Id: Ifa0ae2a858c7878606c05212389fd45da88b1422 +--- + .../drivers/disk/usb/usb_disk/usb_disk.cpp | 163 +++++++++--------- + 1 file changed, 77 insertions(+), 86 deletions(-) + +diff --git a/src/add-ons/kernel/drivers/disk/usb/usb_disk/usb_disk.cpp b/src/add-ons/kernel/drivers/disk/usb/usb_disk/usb_disk.cpp +index 351f791a4c..526783380e 100644 +--- a/src/add-ons/kernel/drivers/disk/usb/usb_disk/usb_disk.cpp ++++ b/src/add-ons/kernel/drivers/disk/usb/usb_disk/usb_disk.cpp +@@ -1459,23 +1459,24 @@ usb_disk_device_added(usb_device newDevice, void **cookie) + return result; + } + +- mutex_lock(&gDeviceListLock); +- device->device_number = 0; +- disk_device *other = gDeviceList; +- while (other != NULL) { +- if (other->device_number >= device->device_number) +- device->device_number = other->device_number + 1; +- +- other = (disk_device *)other->link; ++ { ++ MutexLocker locker(&gDeviceListLock); ++ device->device_number = 0; ++ disk_device *other = gDeviceList; ++ while (other != NULL) { ++ if (other->device_number >= device->device_number) ++ device->device_number = other->device_number + 1; ++ ++ other = (disk_device *)other->link; ++ } ++ ++ device->link = (void *)gDeviceList; ++ gDeviceList = device; ++ gLunCount += device->lun_count; ++ for (uint8 i = 0; i < device->lun_count; i++) ++ sprintf(device->luns[i]->name, DEVICE_NAME, device->device_number, i); + } + +- device->link = (void *)gDeviceList; +- gDeviceList = device; +- gLunCount += device->lun_count; +- for (uint8 i = 0; i < device->lun_count; i++) +- sprintf(device->luns[i]->name, DEVICE_NAME, device->device_number, i); +- mutex_unlock(&gDeviceListLock); +- + TRACE("new device: 0x%p\n", device); + *cookie = (void *)device; + return B_OK; +@@ -1488,7 +1489,7 @@ usb_disk_device_removed(void *cookie) + TRACE("device_removed(0x%p)\n", cookie); + disk_device *device = (disk_device *)cookie; + +- mutex_lock(&gDeviceListLock); ++ MutexLocker locker(&gDeviceListLock); + if (gDeviceList == device) { + gDeviceList = (disk_device *)device->link; + } else { +@@ -1511,7 +1512,6 @@ usb_disk_device_removed(void *cookie) + if (device->open_count == 0) + usb_disk_free_device_and_luns(device); + +- mutex_unlock(&gDeviceListLock); + return B_OK; + } + +@@ -1689,21 +1689,18 @@ usb_disk_open(const char *name, uint32 flags, void **cookie) + strcat(rawName, "raw"); + TRACE("opening raw device %s for %s\n", rawName, name); + +- mutex_lock(&gDeviceListLock); ++ MutexLocker locker(&gDeviceListLock); + disk_device *device = gDeviceList; + while (device) { + for (uint8 i = 0; i < device->lun_count; i++) { + device_lun *lun = device->luns[i]; + if (strncmp(rawName, lun->name, 32) == 0) { + // found the matching device/lun +- if (device->removed) { +- mutex_unlock(&gDeviceListLock); ++ if (device->removed) + return B_ERROR; +- } + + device->open_count++; + *cookie = lun; +- mutex_unlock(&gDeviceListLock); + return B_OK; + } + } +@@ -1711,7 +1708,6 @@ usb_disk_open(const char *name, uint32 flags, void **cookie) + device = (disk_device *)device->link; + } + +- mutex_unlock(&gDeviceListLock); + return B_NAME_NOT_FOUND; + } + +@@ -1723,10 +1719,9 @@ usb_disk_close(void *cookie) + device_lun *lun = (device_lun *)cookie; + disk_device *device = lun->device; + +- mutex_lock(&device->lock); ++ MutexLocker locker(&device->lock); + if (!device->removed) + usb_disk_synchronize(lun, false); +- mutex_unlock(&device->lock); + + return B_OK; + } +@@ -1736,7 +1731,7 @@ static status_t + usb_disk_free(void *cookie) + { + TRACE("free()\n"); +- mutex_lock(&gDeviceListLock); ++ MutexLocker locker(&gDeviceListLock); + + device_lun *lun = (device_lun *)cookie; + disk_device *device = lun->device; +@@ -1747,7 +1742,6 @@ usb_disk_free(void *cookie) + usb_disk_free_device_and_luns(device); + } + +- mutex_unlock(&gDeviceListLock); + return B_OK; + } + +@@ -2005,36 +1999,35 @@ usb_disk_read(void *cookie, off_t position, void *buffer, size_t *length) + TRACE("read(%" B_PRIdOFF ", %ld)\n", position, *length); + device_lun *lun = (device_lun *)cookie; + disk_device *device = lun->device; +- mutex_lock(&device->lock); +- if (device->removed) { +- *length = 0; +- mutex_unlock(&device->lock); +- return B_DEV_NOT_READY; +- } +- + status_t result = B_ERROR; +- uint32 blockPosition = 0; +- uint16 blockCount = 0; +- bool needsPartial = usb_disk_needs_partial_buffer(lun, position, *length, +- blockPosition, blockCount); +- if (needsPartial) { +- void *partialBuffer = NULL; +- void *blockBuffer = NULL; +- result = usb_disk_prepare_partial_buffer(lun, position, *length, +- partialBuffer, blockBuffer, blockPosition, blockCount); +- if (result == B_OK) { +- if (IS_USER_ADDRESS(buffer)) +- result = user_memcpy(buffer, partialBuffer, *length); +- else +- memcpy(buffer, partialBuffer, *length); +- free(blockBuffer); ++ { ++ MutexLocker locker(&device->lock); ++ if (device->removed) { ++ *length = 0; ++ return B_DEV_NOT_READY; ++ } ++ ++ uint32 blockPosition = 0; ++ uint16 blockCount = 0; ++ bool needsPartial = usb_disk_needs_partial_buffer(lun, position, *length, ++ blockPosition, blockCount); ++ if (needsPartial) { ++ void *partialBuffer = NULL; ++ void *blockBuffer = NULL; ++ result = usb_disk_prepare_partial_buffer(lun, position, *length, ++ partialBuffer, blockBuffer, blockPosition, blockCount); ++ if (result == B_OK) { ++ if (IS_USER_ADDRESS(buffer)) ++ result = user_memcpy(buffer, partialBuffer, *length); ++ else ++ memcpy(buffer, partialBuffer, *length); ++ free(blockBuffer); ++ } ++ } else { ++ result = usb_disk_block_read(lun, blockPosition, blockCount, buffer, ++ length); + } +- } else { +- result = usb_disk_block_read(lun, blockPosition, blockCount, buffer, +- length); + } +- +- mutex_unlock(&device->lock); + if (result == B_OK) { + lun->read_bytes += *length; + TRACE("read successful with %ld bytes\n", *length); +@@ -2057,41 +2050,40 @@ usb_disk_write(void *cookie, off_t position, const void *buffer, + TRACE("write(%" B_PRIdOFF", %ld)\n", position, *length); + device_lun *lun = (device_lun *)cookie; + disk_device *device = lun->device; +- mutex_lock(&device->lock); +- if (device->removed) { +- *length = 0; +- mutex_unlock(&device->lock); +- return B_DEV_NOT_READY; +- } +- + status_t result = B_ERROR; +- uint32 blockPosition = 0; +- uint16 blockCount = 0; +- bool needsPartial = usb_disk_needs_partial_buffer(lun, position, +- *length, blockPosition, blockCount); +- if (needsPartial) { +- void *partialBuffer = NULL; +- void *blockBuffer = NULL; +- result = usb_disk_prepare_partial_buffer(lun, position, *length, +- partialBuffer, blockBuffer, blockPosition, blockCount); +- if (result == B_OK) { +- if (IS_USER_ADDRESS(buffer)) +- result = user_memcpy(partialBuffer, buffer, *length); +- else +- memcpy(partialBuffer, buffer, *length); ++ { ++ MutexLocker locker(&device->lock); ++ if (device->removed) { ++ *length = 0; ++ return B_DEV_NOT_READY; + } +- if (result == B_OK) { +- size_t blockLength = blockCount * lun->block_size; ++ ++ uint32 blockPosition = 0; ++ uint16 blockCount = 0; ++ bool needsPartial = usb_disk_needs_partial_buffer(lun, position, ++ *length, blockPosition, blockCount); ++ if (needsPartial) { ++ void *partialBuffer = NULL; ++ void *blockBuffer = NULL; ++ result = usb_disk_prepare_partial_buffer(lun, position, *length, ++ partialBuffer, blockBuffer, blockPosition, blockCount); ++ if (result == B_OK) { ++ if (IS_USER_ADDRESS(buffer)) ++ result = user_memcpy(partialBuffer, buffer, *length); ++ else ++ memcpy(partialBuffer, buffer, *length); ++ } ++ if (result == B_OK) { ++ size_t blockLength = blockCount * lun->block_size; ++ result = usb_disk_block_write(lun, blockPosition, blockCount, ++ blockBuffer, &blockLength); ++ free(blockBuffer); ++ } ++ } else { + result = usb_disk_block_write(lun, blockPosition, blockCount, +- blockBuffer, &blockLength); +- free(blockBuffer); ++ (void *)buffer, length); + } +- } else { +- result = usb_disk_block_write(lun, blockPosition, blockCount, +- (void *)buffer, length); + } +- +- mutex_unlock(&device->lock); + if (result == B_OK) { + lun->write_bytes += *length; + TRACE("write successful with %ld bytes\n", *length); +@@ -2188,7 +2180,7 @@ publish_devices() + return NULL; + + int32 index = 0; +- mutex_lock(&gDeviceListLock); ++ MutexLocker locker(&gDeviceListLock); + disk_device *device = gDeviceList; + while (device) { + for (uint8 i = 0; i < device->lun_count; i++) +@@ -2198,7 +2190,6 @@ publish_devices() + } + + gDeviceNames[index++] = NULL; +- mutex_unlock(&gDeviceListLock); + return (const char **)gDeviceNames; + } + +-- +2.30.2 + diff --git a/patchset-hrev55144/0034-BTextView-Fix-Tracker-edit-name.patch b/patchset-hrev55144/0034-BTextView-Fix-Tracker-edit-name.patch new file mode 100644 index 0000000..1d0d222 --- /dev/null +++ b/patchset-hrev55144/0034-BTextView-Fix-Tracker-edit-name.patch @@ -0,0 +1,430 @@ +From 0b3e9e5ddb161c3a236f2106e38fc82acb9b3d9e Mon Sep 17 00:00:00 2001 +From: John Scipione +Date: Sun, 17 Jan 2021 14:57:07 -0500 +Subject: BTextView: Fix Tracker edit name + +Don't resize text view in FrameResized() if resizable, this is done +in _AutoResize() instead. Scroll to 0 after resizing in _AutoResize(). + +Set TextRect width to max line width when word-wrap is off. +Make _ValidateTextRect() method and call it to ensure fTextRect +does not reach 0 width. This change means that the text rect width is +always the width of the text inside matching BeOS R5 behavior. It is +necessary to allow the Edit Name text view to shrink as text is +deleted. + +TODO highlighting only goes to edge of text, it should go to the edge +of text view when wrap is off (e.g. in StyledEdit). + +Prevent scrolling out of bounds horizontally with the keyboard. +The algorithm to keep cursor in text view bounds was taken from +_PerformAutoScrolling() (mouse scrolling method) and was updated +to account for the left margin which is not always 0. + +Make left and top margin not always 0 when scrolling in +_PerformAutoScrolling() as well, this fixes the same bug when +scrolling the text with the mouse. + +Remove extraSpace variable, no longer needed. This means that we +always scroll according to the text width without any extra space. + +The above makes text views behave properly when overflow occurs i.e. +when you type text off the end of the text view. Instead of scrolling +an entire page of text over, it nudges the text over slightly as +you'd expect it to. + +Take top and bottom margins into account when scrolling with keyboard +in ScrollToOffset(). This allows you to scroll past the margins all the +way to the top and bottom using the up and down arrow keys (1 more px.) + +Fix drawing issues when typing off the edge: + +When word-wrap is turned on for a multi-line text view and you insert, +backspace or delete the position of text rect changes as you type off +the end of the BTextView area. Call FrameResized() in ScrollToOffset() +to reposition the text rect and redraw. This can also happen as a result +of the word-wrap setting changing too so call FrameResized() in that +case too. + +Use Window()->DisableUpdates() and Window()->EnableUpdates() and +remove a call to Window()->UpdateIfNeeded() to prevent the text +from flashing when it draw then the text rect position is moved +and it draws again. This coalesces multiple consecutive draw calls. + +Replace xDiff and yDiff float variables with a single scrollTo BPoint +in ScrollToOffset(). This was also copied from _PerformAutoScrolling(). +(no functional change intended here) + +Remove floorf() calls, we know that we are dealing with integers. +(no functional change intended here) + +Fixes #16642, #16476 + +Change-Id: I2d32d6039944d2dc3218ce4de71f2966cc98c866 +--- + headers/os/interface/TextView.h | 1 + + src/kits/interface/TextView.cpp | 125 +++++++++++++++++++++----------- + src/kits/tracker/TextWidget.cpp | 44 +++++------ + 3 files changed, 102 insertions(+), 68 deletions(-) + +diff --git a/headers/os/interface/TextView.h b/headers/os/interface/TextView.h +index 3757bb1862..951948a092 100644 +--- a/headers/os/interface/TextView.h ++++ b/headers/os/interface/TextView.h +@@ -302,6 +302,7 @@ private: + int32 scrollTo = INT32_MIN); + void _RecalculateLineBreaks(int32* startLine, + int32* endLine); ++ void _ValidateTextRect(); + int32 _FindLineBreak(int32 fromOffset, + float* _ascent, float* _descent, + float* inOutWidth); +diff --git a/src/kits/interface/TextView.cpp b/src/kits/interface/TextView.cpp +index b51c4b7796..fde4b1174a 100644 +--- a/src/kits/interface/TextView.cpp ++++ b/src/kits/interface/TextView.cpp +@@ -509,12 +509,7 @@ BTextView::AttachedToWindow() + fDragOffset = -1; + fActive = false; + +- // text rect right must be greater than left +- if (fTextRect.right <= fTextRect.left) +- fTextRect.right = fTextRect.left + 1; +- // text rect bottom must be greater than top +- if (fTextRect.bottom <= fTextRect.top) +- fTextRect.bottom = fTextRect.top + 1; ++ _ValidateTextRect(); + + _AutoResize(true); + +@@ -808,8 +803,13 @@ BTextView::FrameResized(float newWidth, float newHeight) + { + BView::FrameResized(newWidth, newHeight); + ++ // frame resized in _AutoResize() instead ++ if (fResizable) ++ return; ++ + if (fWrap) { + // recalculate line breaks ++ // will update scroll bars if text rect changes + _ResetTextRect(); + } else { + // don't recalculate line breaks, +@@ -852,9 +852,9 @@ BTextView::FrameResized(float newWidth, float newHeight) + BRegion dirty(oldTextRect | fTextRect); + Invalidate(&dirty); + } +- } + +- _UpdateScrollbars(); ++ _UpdateScrollbars(); ++ } + } + + +@@ -2196,6 +2196,10 @@ BTextView::ScrollToOffset(int32 offset) + } + + ScrollBy(scrollBy.x, scrollBy.y); ++ ++ // Update text rect position and scroll bars ++ if (CountLines() > 1 && !fWrap) ++ FrameResized(Bounds().Width(), Bounds().Height()); + } + + +@@ -2417,6 +2421,8 @@ BTextView::SetWordWrap(bool wrap) + _HideCaret(); + } + ++ BRect savedBounds = Bounds(); ++ + fWrap = wrap; + if (wrap) + _ResetTextRect(); // calls _Refresh +@@ -2426,6 +2432,10 @@ BTextView::SetWordWrap(bool wrap) + if (fEditable) + ScrollToOffset(fCaretOffset); + ++ // redraw text rect and update scroll bars if bounds have changed ++ if (Bounds() != savedBounds) ++ FrameResized(Bounds().Width(), Bounds().Height()); ++ + if (updateOnScreen) { + // show the caret, hilite the selection + if (fSelStart != fSelEnd) { +@@ -2565,7 +2575,7 @@ BTextView::MakeResizable(bool resize, BView* resizeView) + } + // We need to reset the right inset, as otherwise the auto-resize would + // get confused about just how wide the textview needs to be. +- // This seems to be an artefact of how Tracker creates the textview ++ // This seems to be an artifact of how Tracker creates the textview + // during a rename action. + fLayoutData->rightInset = fLayoutData->leftInset; + } else { +@@ -3193,10 +3203,8 @@ BTextView::_InitObject(BRect textRect, const BFont* initialFont, + // if needed. + fTextRect = textRect; + // NOTE: The only places where text rect is changed: +- // * width is possibly adjusted in _AutoResize(), +- // * height is adjusted in _RecalculateLineBreaks(). +- // When used within the layout management framework, the +- // text rect is changed to maintain constant insets. ++ // * width and height are adjusted in _RecalculateLineBreaks(), ++ // text rect maintains constant insets, use SetInsets() to change. + fMinTextRectWidth = fTextRect.Width(); + // see SetTextRect() + fSelStart = fSelEnd = 0; +@@ -3266,6 +3274,10 @@ BTextView::_HandleBackspace(int32 modifiers) + undoBuffer->BackwardErase(); + } + ++ // we may draw twice, so turn updates off for now ++ if (Window() != NULL) ++ Window()->DisableUpdates(); ++ + if (fSelStart == fSelEnd) { + if (fSelStart == 0) + return; +@@ -3278,6 +3290,10 @@ BTextView::_HandleBackspace(int32 modifiers) + fCaretOffset = fSelEnd = fSelStart; + + _Refresh(fSelStart, fSelEnd, fCaretOffset); ++ ++ // turn drawing back on ++ if (Window() != NULL) ++ Window()->EnableUpdates(); + } + + +@@ -3487,6 +3503,10 @@ BTextView::_HandleDelete(int32 modifiers) + undoBuffer->ForwardErase(); + } + ++ // we may draw twice, so turn updates off for now ++ if (Window() != NULL) ++ Window()->DisableUpdates(); ++ + if (fSelStart == fSelEnd) { + if (fSelEnd == fText->Length()) + return; +@@ -3499,6 +3519,10 @@ BTextView::_HandleDelete(int32 modifiers) + fCaretOffset = fSelEnd = fSelStart; + + _Refresh(fSelStart, fSelEnd, fCaretOffset); ++ ++ // turn updates back on ++ if (Window() != NULL) ++ Window()->EnableUpdates(); + } + + +@@ -3702,6 +3726,10 @@ BTextView::_HandleAlphaKey(const char* bytes, int32 numBytes) + DeleteText(fSelStart, fSelEnd); + } + ++ // we may draw twice, so turn updates off for now ++ if (Window() != NULL) ++ Window()->DisableUpdates(); ++ + if (fAutoindent && numBytes == 1 && *bytes == B_ENTER) { + int32 start, offset; + start = offset = OffsetAt(_LineAt(fSelStart)); +@@ -3718,8 +3746,11 @@ BTextView::_HandleAlphaKey(const char* bytes, int32 numBytes) + _DoInsertText(bytes, numBytes, fSelStart, NULL); + + fCaretOffset = fSelEnd; +- + ScrollToOffset(fCaretOffset); ++ ++ // turn update back on to draw ++ if (Window() != NULL) ++ Window()->EnableUpdates(); + } + + +@@ -3891,25 +3922,23 @@ BTextView::_RecalculateLineBreaks(int32* startLine, int32* endLine) + switch (fAlignment) { + default: + case B_ALIGN_LEFT: +- // grow right +- fTextRect.right = std::max(fTextRect.right, +- fTextRect.left + fMinTextRectWidth); ++ // move right edge ++ fTextRect.right = fTextRect.left + fMinTextRectWidth; + break; + + case B_ALIGN_RIGHT: +- // grow left +- fTextRect.left = std::min(fTextRect.left, +- fTextRect.right - fMinTextRectWidth); ++ // move left edge ++ fTextRect.left = fTextRect.right - fMinTextRectWidth; + break; + + case B_ALIGN_CENTER: +- // grow out +- if (fMinTextRectWidth > fTextRect.Width()) { +- fTextRect.InsetBy(ceilf((fTextRect.Width() +- - fMinTextRectWidth) / 2.0f), 0); +- } ++ // move both edges ++ fTextRect.InsetBy(roundf((fTextRect.Width() ++ - fMinTextRectWidth) / 2), 0); + break; + } ++ ++ _ValidateTextRect(); + } + + *endLine = lineIndex - 1; +@@ -3917,6 +3946,18 @@ BTextView::_RecalculateLineBreaks(int32* startLine, int32* endLine) + } + + ++void ++BTextView::_ValidateTextRect() ++{ ++ // text rect right must be greater than left ++ if (fTextRect.right <= fTextRect.left) ++ fTextRect.right = fTextRect.left + 1; ++ // text rect bottom must be greater than top ++ if (fTextRect.bottom <= fTextRect.top) ++ fTextRect.bottom = fTextRect.top + 1; ++} ++ ++ + int32 + BTextView::_FindLineBreak(int32 fromOffset, float* _ascent, float* _descent, + float* inOutWidth) +@@ -4598,7 +4639,6 @@ BTextView::_RequestDrawLines(int32 startLine, int32 endLine) + Bounds().right, + to != NULL ? to->origin + fTextRect.top : fTextRect.bottom); + Invalidate(invalidRect); +- Window()->UpdateIfNeeded(); + } + + +@@ -5055,28 +5095,29 @@ BTextView::_ScrollTo(float x, float y) + void + BTextView::_AutoResize(bool redraw) + { +- if (!fResizable) ++ if (!fResizable || fContainerView == NULL) + return; + + BRect bounds = Bounds(); + +- if (fContainerView != NULL) { +- // NOTE: This container view thing is only used by Tracker. +- // move container view if not left aligned +- float oldWidth = bounds.Width(); +- float newWidth = ceilf(fLayoutData->leftInset +- + fTextRect.Width() + fLayoutData->rightInset); +- if (fAlignment == B_ALIGN_CENTER) { +- if (fmod(ceilf(newWidth - oldWidth), 2.0) != 0.0) +- newWidth += 1; ++ // NOTE: This container view thing is only used by Tracker. ++ // move container view if not left aligned ++ float oldWidth = bounds.Width(); ++ float newWidth = ceilf(fLayoutData->leftInset ++ + fTextRect.Width() + fLayoutData->rightInset); ++ float right = oldWidth - newWidth; + +- fContainerView->MoveBy(ceilf(oldWidth - newWidth) / 2, 0); +- } else if (fAlignment == B_ALIGN_RIGHT) +- fContainerView->MoveBy(ceilf(oldWidth - newWidth), 0); ++ if (fAlignment == B_ALIGN_CENTER) ++ fContainerView->MoveBy(roundf(right / 2), 0); ++ else if (fAlignment == B_ALIGN_RIGHT) ++ fContainerView->MoveBy(right, 0); + +- // resize container view +- fContainerView->ResizeBy(ceilf(newWidth - oldWidth), 0); +- } ++ // resize container view ++ float grow = newWidth - oldWidth; ++ fContainerView->ResizeBy(grow, 0); ++ ++ // scroll rect to start, there is room for full text ++ ScrollToOffset(0); + + if (redraw) + _RequestDrawLines(0, 0); +diff --git a/src/kits/tracker/TextWidget.cpp b/src/kits/tracker/TextWidget.cpp +index 5211e771fb..b6dddce8cc 100644 +--- a/src/kits/tracker/TextWidget.cpp ++++ b/src/kits/tracker/TextWidget.cpp +@@ -334,18 +334,12 @@ TextViewFilter(BMessage* message, BHandler**, BMessageFilter* filter) + BTextView* textView = dynamic_cast( + scrollView->FindView("WidgetTextView")); + if (textView != NULL) { +- BRect textRect = textView->TextRect(); +- BRect rect = scrollView->Frame(); +- +- if (rect.right + 5 > poseView->Bounds().right +- || rect.left - 5 < 0) +- textView->MakeResizable(true, NULL); +- +- if (textRect.Width() + 10 < rect.Width()) { ++ // limit max width to 30em ++ float maxWidth = textView->StringWidth("M") * 30; ++ if (textView->TextRect().Width() > maxWidth) ++ textView->MakeResizable(false, NULL); ++ else + textView->MakeResizable(true, scrollView); +- // make sure no empty white space stays on the right +- textView->ScrollToOffset(0); +- } + } + } + +@@ -398,23 +392,11 @@ BTextWidget::StartEdit(BRect bounds, BPoseView* view, BPose* pose) + + textView->SetTextRect(textRect); + +- BPoint origin = view->LeftTop(); +- textRect = view->Bounds(); +- +- bool hitBorder = false; +- if (rect.left <= origin.x) +- rect.left = origin.x + 1, hitBorder = true; +- if (rect.right >= textRect.right) +- rect.right = textRect.right - 1, hitBorder = true; +- ++ // resize textView + textView->MoveTo(rect.LeftTop()); + textView->ResizeTo(rect.Width(), rect.Height()); + +- BScrollView* scrollView = new BScrollView("BorderView", textView, 0, 0, +- false, false, B_PLAIN_BORDER); +- view->AddChild(scrollView); +- +- // configure text view ++ // set alignment before adding textView so it doesn't redraw + switch (view->ViewMode()) { + case kIconMode: + textView->SetAlignment(B_ALIGN_CENTER); +@@ -428,7 +410,17 @@ BTextWidget::StartEdit(BRect bounds, BPoseView* view, BPose* pose) + textView->SetAlignment(fAlignment); + break; + } +- textView->MakeResizable(true, hitBorder ? NULL : scrollView); ++ ++ BScrollView* scrollView = new BScrollView("BorderView", textView, 0, 0, ++ false, false, B_PLAIN_BORDER); ++ view->AddChild(scrollView); ++ ++ // limit max width to 30em ++ float maxWidth = textView->StringWidth("M") * 30; ++ if (textView->TextRect().Width() > maxWidth) ++ textView->MakeResizable(false, NULL); ++ else ++ textView->MakeResizable(true, scrollView); + + view->SetActivePose(pose); + // tell view about pose +-- +2.30.2 + diff --git a/patchset-hrev55144/0035-Menu-use-menu-superitem-when-exists-when-adding-menu.patch b/patchset-hrev55144/0035-Menu-use-menu-superitem-when-exists-when-adding-menu.patch new file mode 100644 index 0000000..4182833 --- /dev/null +++ b/patchset-hrev55144/0035-Menu-use-menu-superitem-when-exists-when-adding-menu.patch @@ -0,0 +1,47 @@ +From 53ad45a6909393a5150e2e76c5af9e5742bbbdd5 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 18 Apr 2021 12:01:04 +0900 +Subject: Menu: use menu superitem when exists when adding menu as item + +Change-Id: I8422fdf27048752d4836e6a2e2fc8e70de2e13b1 +--- + src/kits/interface/Menu.cpp | 9 +++++++++ + 1 file changed, 9 insertions(+) + +diff --git a/src/kits/interface/Menu.cpp b/src/kits/interface/Menu.cpp +index d9158bd0d2..9a2464fa16 100644 +--- a/src/kits/interface/Menu.cpp ++++ b/src/kits/interface/Menu.cpp +@@ -953,6 +953,9 @@ BMenu::AddItem(BMenuItem* item, BRect frame) + bool + BMenu::AddItem(BMenu* submenu) + { ++ if (submenu->Superitem() != NULL) ++ return AddItem(submenu->Superitem(), CountItems()); ++ + BMenuItem* item = new (nothrow) BMenuItem(submenu); + if (item == NULL) + return false; +@@ -975,6 +978,9 @@ BMenu::AddItem(BMenu* submenu, int32 index) + "be called if the menu layout is not B_ITEMS_IN_MATRIX"); + } + ++ if (submenu->Superitem() != NULL) ++ return AddItem(submenu->Superitem(), index); ++ + BMenuItem* item = new (nothrow) BMenuItem(submenu); + if (item == NULL) + return false; +@@ -997,6 +1003,9 @@ BMenu::AddItem(BMenu* submenu, BRect frame) + "be called if the menu layout is B_ITEMS_IN_MATRIX"); + } + ++ if (submenu->Superitem() != NULL) ++ return AddItem(submenu->Superitem(), frame); ++ + BMenuItem* item = new (nothrow) BMenuItem(submenu); + if (item == NULL) + return false; +-- +2.30.2 + diff --git a/patchset-hrev55144/0036-kernel-arch-vm-implement-for-riscv64.patch b/patchset-hrev55144/0036-kernel-arch-vm-implement-for-riscv64.patch new file mode 100644 index 0000000..6ef2232 --- /dev/null +++ b/patchset-hrev55144/0036-kernel-arch-vm-implement-for-riscv64.patch @@ -0,0 +1,1418 @@ +From 2719f605e57465996e729ce12919cd26c5a3975d Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 21:56:36 +0900 +Subject: kernel/arch/vm: implement for riscv64 + +Change-Id: I0b463f3d2bca9f31b0aabacbf70a9774493d3467 +--- + headers/private/kernel/vm/vm_types.h | 2 + + src/system/kernel/arch/riscv64/Jamfile | 1 + + .../arch/riscv64/RISCV64VMTranslationMap.cpp | 870 ++++++++++++++++++ + .../arch/riscv64/RISCV64VMTranslationMap.h | 140 +++ + src/system/kernel/arch/riscv64/arch_vm.cpp | 13 +- + .../arch/riscv64/arch_vm_translation_map.cpp | 245 ++++- + 6 files changed, 1258 insertions(+), 13 deletions(-) + create mode 100644 src/system/kernel/arch/riscv64/RISCV64VMTranslationMap.cpp + create mode 100644 src/system/kernel/arch/riscv64/RISCV64VMTranslationMap.h + +diff --git a/headers/private/kernel/vm/vm_types.h b/headers/private/kernel/vm/vm_types.h +index 85aa030687..a165bb4229 100644 +--- a/headers/private/kernel/vm/vm_types.h ++++ b/headers/private/kernel/vm/vm_types.h +@@ -25,6 +25,8 @@ + + #include "kernel_debug_config.h" + ++#undef DEBUG_PAGE_ACCESS ++ + + #define VM_PAGE_ALLOCATION_TRACKING_AVAILABLE \ + (VM_PAGE_ALLOCATION_TRACKING && PAGE_ALLOCATION_TRACING != 0 \ +diff --git a/src/system/kernel/arch/riscv64/Jamfile b/src/system/kernel/arch/riscv64/Jamfile +index f76a4dfe22..e6d005b3ef 100644 +--- a/src/system/kernel/arch/riscv64/Jamfile ++++ b/src/system/kernel/arch/riscv64/Jamfile +@@ -20,6 +20,7 @@ KernelMergeObject kernel_arch_riscv64.o : + arch_user_debugger.cpp + arch_vm.cpp + arch_vm_translation_map.cpp ++ RISCV64VMTranslationMap.cpp + : + $(TARGET_KERNEL_PIC_CCFLAGS) -Wno-unused + : +diff --git a/src/system/kernel/arch/riscv64/RISCV64VMTranslationMap.cpp b/src/system/kernel/arch/riscv64/RISCV64VMTranslationMap.cpp +new file mode 100644 +index 0000000000..7234beb16d +--- /dev/null ++++ b/src/system/kernel/arch/riscv64/RISCV64VMTranslationMap.cpp +@@ -0,0 +1,870 @@ ++#include "RISCV64VMTranslationMap.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++ ++ ++//#define DO_TRACE ++#ifdef DO_TRACE ++# define TRACE(x...) dprintf(x) ++#else ++# define TRACE(x...) ; ++#endif ++ ++#define NOT_IMPLEMENTED_PANIC() \ ++ panic("not implemented: %s\n", __PRETTY_FUNCTION__) ++ ++ ++static inline void* ++VirtFromPhys(uint64_t physAdr) ++{ ++ return (void*)(physAdr + (KERNEL_PMAP_BASE - 0x80000000)); ++} ++ ++ ++static inline uint64_t ++PhysFromVirt(void *virtAdr) ++{ ++ return (uint64)virtAdr - (KERNEL_PMAP_BASE - 0x80000000); ++} ++ ++ ++static void ++WriteVmPage(vm_page* page) ++{ ++ dprintf("0x%08" B_PRIxADDR " ", page->physical_page_number * B_PAGE_SIZE); ++ switch (page->State()) { ++ case PAGE_STATE_ACTIVE: dprintf("A"); break; ++ case PAGE_STATE_INACTIVE: dprintf("I"); break; ++ case PAGE_STATE_MODIFIED: dprintf("M"); break; ++ case PAGE_STATE_CACHED: dprintf("C"); break; ++ case PAGE_STATE_FREE: dprintf("F"); break; ++ case PAGE_STATE_CLEAR: dprintf("L"); break; ++ case PAGE_STATE_WIRED: dprintf("W"); break; ++ case PAGE_STATE_UNUSED: dprintf("-"); break; ++ } ++ dprintf(" "); ++ if (page->busy) dprintf("B"); else dprintf("-"); ++ if (page->busy_writing) dprintf("W"); else dprintf("-"); ++ if (page->accessed) dprintf("A"); else dprintf("-"); ++ if (page->modified) dprintf("M"); else dprintf("-"); ++ if (page->unused) dprintf("U"); else dprintf("-"); ++ ++ dprintf(" usage:%3u", page->usage_count); ++ dprintf(" wired:%5u", page->WiredCount()); ++} ++ ++ ++static void ++FreePageTable(page_num_t ppn, bool isKernel, uint32 level = 2) ++{ ++ if (level > 0) { ++ Pte* pte = (Pte*)VirtFromPhys(ppn * B_PAGE_SIZE); ++ // NOTE: adjust range if changing kernel address space range ++ for (uint32 i = (level == 2 && !isKernel) ? 256 : 0; i < pteCount; ++ i++) { ++ if ((1 << pteValid) & pte[i].flags) ++ FreePageTable(pte[i].ppn, isKernel, level - 1); ++ } ++ } ++ vm_page* page = vm_lookup_page(ppn); ++ vm_page_set_state(page, PAGE_STATE_FREE); ++} ++ ++ ++static uint64 ++GetPageTableSize(page_num_t ppn, bool isKernel, uint32 level = 2) ++{ ++ if (ppn == 0) ++ return 0; ++ ++ if (level == 0) ++ return 1; ++ ++ uint64 size = 1; ++ Pte* pte = (Pte*)VirtFromPhys(ppn * B_PAGE_SIZE); ++ // NOTE: adjust range if changing kernel address space range ++ for (uint32 i = (level == 2 && !isKernel) ? 256 : 0; i < pteCount; i++) { ++ if ((1 << pteValid) & pte[i].flags) ++ size += GetPageTableSize(pte[i].ppn, isKernel, level - 1); ++ } ++ return size; ++} ++ ++ ++//#pragma mark RISCV64VMTranslationMap ++ ++Pte* ++RISCV64VMTranslationMap::LookupPte(addr_t virtAdr, bool alloc, ++ vm_page_reservation* reservation) ++{ ++ if (fPageTable == 0) { ++ if (!alloc) ++ return NULL; ++ vm_page* page = vm_page_allocate_page(reservation, ++ PAGE_STATE_WIRED | VM_PAGE_ALLOC_CLEAR); ++ fPageTable = page->physical_page_number * B_PAGE_SIZE; ++ if (fPageTable == 0) ++ return NULL; ++ fPageTableSize++; ++ if (!fIsKernel) { ++ // Map kernel address space into user address space. Preallocated ++ // kernel level-2 PTEs are reused. ++ RISCV64VMTranslationMap* kernelMap = (RISCV64VMTranslationMap*) ++ VMAddressSpace::Kernel()->TranslationMap(); ++ Pte *kernelPageTable = (Pte*)VirtFromPhys(kernelMap->PageTable()); ++ Pte *userPageTable = (Pte*)VirtFromPhys(fPageTable); ++ // NOTE: adjust range if changing kernel address space range ++ for (int i = 0; i < 256; i++) { ++ Pte *pte = &userPageTable[i]; ++ pte->ppn = kernelPageTable[i].ppn; ++ pte->flags |= (1 << pteValid); ++ } ++ } ++ } ++ Pte *pte = (Pte*)VirtFromPhys(fPageTable); ++ for (int level = 2; level > 0; level --) { ++ pte += PhysAdrPte(virtAdr, level); ++ if (!((1 << pteValid) & pte->flags)) { ++ if (!alloc) ++ return NULL; ++ vm_page* page = vm_page_allocate_page(reservation, ++ PAGE_STATE_WIRED | VM_PAGE_ALLOC_CLEAR); ++ pte->ppn = page->physical_page_number; ++ if (pte->ppn == 0) ++ return NULL; ++ fPageTableSize++; ++ pte->flags |= (1 << pteValid); ++ } ++ pte = (Pte*)VirtFromPhys(B_PAGE_SIZE * pte->ppn); ++ } ++ pte += PhysAdrPte(virtAdr, 0); ++ return pte; ++} ++ ++ ++phys_addr_t ++RISCV64VMTranslationMap::LookupAddr(addr_t virtAdr) ++{ ++ Pte* pte = LookupPte(virtAdr, false, NULL); ++ if (pte == NULL || !((1 << pteValid) & pte->flags)) ++ return 0; ++ if (fIsKernel != (((1 << pteUser) & pte->flags) == 0)) ++ return 0; ++ return pte->ppn * B_PAGE_SIZE; ++} ++ ++ ++RISCV64VMTranslationMap::RISCV64VMTranslationMap(bool kernel, ++ phys_addr_t pageTable): ++ fIsKernel(kernel), ++ fPageTable(pageTable), ++ fPageTableSize(GetPageTableSize(pageTable / B_PAGE_SIZE, kernel)) ++{ ++ TRACE("+RISCV64VMTranslationMap(%p, %d, 0x%" B_PRIxADDR ")\n", this, ++ kernel, pageTable); ++ TRACE(" pageTableSize: %" B_PRIu64 "\n", fPageTableSize); ++} ++ ++ ++RISCV64VMTranslationMap::~RISCV64VMTranslationMap() ++{ ++ TRACE("-RISCV64VMTranslationMap(%p)\n", this); ++ TRACE(" pageTableSize: %" B_PRIu64 "\n", fPageTableSize); ++ TRACE(" GetPageTableSize(): %" B_PRIu64 "\n", ++ GetPageTableSize(fPageTable / B_PAGE_SIZE, fIsKernel)); ++ if (!fIsKernel) { ++ // We are going to delete currently used page table, switch to ++ // kernel page table. ++ RISCV64VMTranslationMap* kernelMap = (RISCV64VMTranslationMap*) ++ VMAddressSpace::Kernel()->TranslationMap(); ++ SetSatp(kernelMap->Satp()); ++ } ++ FreePageTable(fPageTable / B_PAGE_SIZE, fIsKernel); ++} ++ ++ ++bool ++RISCV64VMTranslationMap::Lock() ++{ ++ TRACE("RISCV64VMTranslationMap::Lock()\n"); ++ recursive_lock_lock(&fLock); ++ return true; ++} ++ ++ ++void ++RISCV64VMTranslationMap::Unlock() ++{ ++ TRACE("RISCV64VMTranslationMap::Unlock()\n"); ++ if (recursive_lock_get_recursion(&fLock) == 1) { ++ // we're about to release it for the last time ++ Flush(); ++ } ++ recursive_lock_unlock(&fLock); ++} ++ ++ ++addr_t ++RISCV64VMTranslationMap::MappedSize() const ++{ ++ NOT_IMPLEMENTED_PANIC(); ++ return 0; ++} ++ ++ ++size_t ++RISCV64VMTranslationMap::MaxPagesNeededToMap(addr_t start, addr_t end) const ++{ ++ enum { ++ level0Range = (uint64_t)B_PAGE_SIZE * pteCount, ++ level1Range = (uint64_t)level0Range * pteCount, ++ level2Range = (uint64_t)level1Range * pteCount, ++ }; ++ ++ if (start == 0) { ++ start = (level2Range) - B_PAGE_SIZE; ++ end += start; ++ } ++ ++ size_t requiredLevel2 = end / level2Range + 1 - start / level2Range; ++ size_t requiredLevel1 = end / level1Range + 1 - start / level1Range; ++ size_t requiredLevel0 = end / level0Range + 1 - start / level0Range; ++ ++ return requiredLevel2 + requiredLevel1 + requiredLevel0; ++} ++ ++ ++status_t ++RISCV64VMTranslationMap::Map(addr_t virtualAddress, ++ phys_addr_t physicalAddress, ++ uint32 attributes, uint32 memoryType, ++ vm_page_reservation* reservation) ++{ ++ TRACE("RISCV64VMTranslationMap::Map(0x%" B_PRIxADDR ", 0x%" B_PRIxADDR ++ ")\n", virtualAddress, physicalAddress); ++ ++ ThreadCPUPinner pinner(thread_get_current_thread()); ++ ++ Pte* pte = LookupPte(virtualAddress, true, reservation); ++ if (pte == NULL) panic("can't allocate page table"); ++ ++ pte->ppn = physicalAddress / B_PAGE_SIZE; ++ pte->flags = 0; ++ if ((attributes & B_USER_PROTECTION) != 0) { ++ pte->flags |= (1 << pteUser); ++ if ((attributes & B_READ_AREA) != 0) pte->flags |= (1 << pteRead); ++ if ((attributes & B_WRITE_AREA) != 0) pte->flags |= (1 << pteWrite); ++ if ((attributes & B_EXECUTE_AREA) != 0) pte->flags |= (1 << pteExec); ++ } else { ++ if ((attributes & B_KERNEL_READ_AREA) != 0) ++ pte->flags |= (1 << pteRead); ++ if ((attributes & B_KERNEL_WRITE_AREA) != 0) ++ pte->flags |= (1 << pteWrite); ++ if ((attributes & B_KERNEL_EXECUTE_AREA) != 0) ++ pte->flags |= (1 << pteExec); ++ } ++ pte->flags |= (1 << pteValid); ++ ++ FlushTlbPage(virtualAddress); ++ ++ fMapCount++; ++ ++ return B_OK; ++} ++ ++ ++status_t ++RISCV64VMTranslationMap::Unmap(addr_t start, addr_t end) ++{ ++ TRACE("RISCV64VMTranslationMap::Unmap(0x%" B_PRIxADDR ", 0x%" B_PRIxADDR ++ ")\n", start, end); ++ ++ ThreadCPUPinner pinner(thread_get_current_thread()); ++ ++ for (addr_t page = start; page < end; page += B_PAGE_SIZE) { ++ Pte* pte = LookupPte(page, false, NULL); ++ if (pte != NULL) { ++ fMapCount--; ++ pte->flags = 0; ++ pte->ppn = 0; ++ FlushTlbPage(page); ++ } ++ } ++ return B_OK; ++} ++ ++ ++status_t ++RISCV64VMTranslationMap::DebugMarkRangePresent(addr_t start, addr_t end, ++ bool markPresent) ++{ ++ NOT_IMPLEMENTED_PANIC(); ++ return B_NOT_SUPPORTED; ++} ++ ++ ++/* ++Things need to be done when unmapping VMArea pages ++ update vm_page::accessed, modified ++ MMIO pages: ++ just unmap ++ wired pages: ++ decrement wired count ++ non-wired pages: ++ remove from VMArea and vm_page `mappings` list ++ wired and non-wird pages ++ vm_page_set_state ++*/ ++ ++status_t ++RISCV64VMTranslationMap::UnmapPage(VMArea* area, addr_t address, ++ bool updatePageQueue) ++{ ++ TRACE("RISCV64VMTranslationMap::UnmapPage(0x%" B_PRIxADDR "(%s), 0x%" ++ B_PRIxADDR ", %d)\n", (addr_t)area, area->name, address, ++ updatePageQueue); ++ ++ ThreadCPUPinner pinner(thread_get_current_thread()); ++ ++ Pte* pte = LookupPte(address, false, NULL); ++ if (pte == NULL || ((1 << pteValid) & pte->flags) == 0) ++ return B_ENTRY_NOT_FOUND; ++ ++ RecursiveLocker locker(fLock); ++ ++ Pte oldPte = *pte; ++ pte->flags = 0; ++ pte->ppn = 0; ++ fMapCount--; ++ FlushTlbPage(address); ++ pinner.Unlock(); ++ ++ locker.Detach(); // PageUnmapped takes ownership ++ PageUnmapped(area, oldPte.ppn, ((1 << pteAccessed) & oldPte.flags) != 0, ++ ((1 << pteDirty) & oldPte.flags) != 0, updatePageQueue); ++ return B_OK; ++} ++ ++ ++void ++RISCV64VMTranslationMap::UnmapPages(VMArea* area, addr_t base, size_t size, ++ bool updatePageQueue) ++{ ++ TRACE("RISCV64VMTranslationMap::UnmapPages(0x%" B_PRIxADDR "(%s), 0x%" ++ B_PRIxADDR ", 0x%" B_PRIxSIZE ", %d)\n", (addr_t)area, area->name, base, ++ size, updatePageQueue); ++ for (addr_t end = base + size; base < end; base += B_PAGE_SIZE) ++ UnmapPage(area, base, updatePageQueue); ++} ++ ++ ++void ++RISCV64VMTranslationMap::UnmapArea(VMArea* area, bool deletingAddressSpace, ++ bool ignoreTopCachePageFlags) ++{ ++ TRACE("RISCV64VMTranslationMap::UnmapArea(0x%" B_PRIxADDR "(%s), 0x%" ++ B_PRIxADDR ", 0x%" B_PRIxSIZE ", %d)\n", (addr_t)area, area->name, base, ++ size, updatePageQueue); ++ ++ if (area->cache_type == CACHE_TYPE_DEVICE || area->wiring != B_NO_LOCK) { ++ UnmapPages(area, area->Base(), area->Size(), true); ++ return; ++ } ++ ++ bool unmapPages = !deletingAddressSpace || !ignoreTopCachePageFlags; ++ ++ RecursiveLocker locker(fLock); ++ ThreadCPUPinner pinner(thread_get_current_thread()); ++ ++ VMAreaMappings mappings; ++ mappings.MoveFrom(&area->mappings); ++ ++ for (VMAreaMappings::Iterator it = mappings.GetIterator(); ++ vm_page_mapping* mapping = it.Next();) { ++ vm_page* page = mapping->page; ++ page->mappings.Remove(mapping); ++ ++ VMCache* cache = page->Cache(); ++ ++ bool pageFullyUnmapped = false; ++ if (!page->IsMapped()) { ++ atomic_add(&gMappedPagesCount, -1); ++ pageFullyUnmapped = true; ++ } ++ ++ if (unmapPages || cache != area->cache) { ++ addr_t address = area->Base() ++ + ((page->cache_offset * B_PAGE_SIZE) - area->cache_offset); ++ ++ Pte* pte = LookupPte(address, false, NULL); ++ if (pte == NULL || ((1 << pteValid) & pte->flags) == 0) ++ ++ Pte* pte = LookupPte(address, false, NULL); ++ if (pte == NULL || ((1 << pteValid) & pte->flags) == 0) { ++ panic("page %p has mapping for area %p (%#" B_PRIxADDR ++ "), but has no page table", page, area, address); ++ continue; ++ } ++ ++ Pte oldPte = *pte; ++ pte->flags = 0; ++ pte->ppn = 0; ++ ++ // transfer the accessed/dirty flags to the page and invalidate ++ // the mapping, if necessary ++ if (((1 << pteAccessed) & oldPte.flags) != 0) { ++ page->accessed = true; ++ ++ if (!deletingAddressSpace) ++ FlushTlbPage(address); ++ } ++ ++ if (((1 << pteDirty) & oldPte.flags) != 0) ++ page->modified = true; ++ ++ if (pageFullyUnmapped) { ++ if (cache->temporary) ++ vm_page_set_state(page, PAGE_STATE_INACTIVE); ++ else if (page->modified) ++ vm_page_set_state(page, PAGE_STATE_MODIFIED); ++ else ++ vm_page_set_state(page, PAGE_STATE_CACHED); ++ } ++ } ++ ++ fMapCount--; ++ } ++ ++ Flush(); ++ // flush explicitely, since we directly use the lock ++ ++ locker.Unlock(); ++ ++ bool isKernelSpace = area->address_space == VMAddressSpace::Kernel(); ++ uint32 freeFlags = CACHE_DONT_WAIT_FOR_MEMORY ++ | (isKernelSpace ? CACHE_DONT_LOCK_KERNEL_SPACE : 0); ++ while (vm_page_mapping* mapping = mappings.RemoveHead()) ++ object_cache_free(gPageMappingsObjectCache, mapping, freeFlags); ++} ++ ++ ++status_t ++RISCV64VMTranslationMap::Query(addr_t virtualAddress, ++ phys_addr_t* _physicalAddress, uint32* _flags) ++{ ++ *_flags = 0; ++ *_physicalAddress = 0; ++ ++ ThreadCPUPinner pinner(thread_get_current_thread()); ++ ++ if (fPageTable == 0) ++ return B_OK; ++ ++ Pte* pte = LookupPte(virtualAddress, false, NULL); ++ if (pte == 0) ++ return B_OK; ++ ++ *_physicalAddress = pte->ppn * B_PAGE_SIZE; ++ ++ if (((1 << pteValid) & pte->flags) != 0) *_flags |= PAGE_PRESENT; ++ if (((1 << pteDirty) & pte->flags) != 0) *_flags |= PAGE_MODIFIED; ++ if (((1 << pteAccessed) & pte->flags) != 0) *_flags |= PAGE_ACCESSED; ++ ++ if (((1 << pteUser) & pte->flags) != 0) { ++ if (((1 << pteRead) & pte->flags) != 0) *_flags |= B_READ_AREA; ++ if (((1 << pteWrite) & pte->flags) != 0) *_flags |= B_WRITE_AREA; ++ if (((1 << pteExec) & pte->flags) != 0) *_flags |= B_EXECUTE_AREA; ++ } else { ++ if (((1 << pteRead) & pte->flags) != 0) ++ *_flags |= B_KERNEL_READ_AREA; ++ if (((1 << pteWrite) & pte->flags) != 0) ++ *_flags |= B_KERNEL_WRITE_AREA; ++ if (((1 << pteExec) & pte->flags) != 0) ++ *_flags |= B_KERNEL_EXECUTE_AREA; ++ } ++ ++ return B_OK; ++} ++ ++ ++status_t ++RISCV64VMTranslationMap::QueryInterrupt(addr_t virtualAddress, ++ phys_addr_t* _physicalAddress, ++ uint32* _flags) ++{ ++ return Query(virtualAddress, _physicalAddress, _flags); ++} ++ ++ ++status_t RISCV64VMTranslationMap::Protect(addr_t base, addr_t top, ++ uint32 attributes, uint32 memoryType) ++{ ++ TRACE("RISCV64VMTranslationMap::Protect(0x%" B_PRIxADDR ", 0x%" B_PRIxADDR ++ ")\n", base, top); ++ ++ ThreadCPUPinner pinner(thread_get_current_thread()); ++ ++ for (addr_t page = base; page < top; page += B_PAGE_SIZE) { ++ Pte* pte = LookupPte(page, false, NULL); ++ if (pte == NULL || ((1 << pteValid) & pte->flags) == 0) { ++ TRACE("attempt to protect not mapped page: 0x%" B_PRIxADDR "\n", ++ page); ++ continue; ++ } ++ ++ Pte newPte = *pte; ++ newPte.flags = (1 << pteValid); ++ if ((attributes & B_USER_PROTECTION) != 0) { ++ newPte.flags |= (1 << pteUser); ++ if ((attributes & B_READ_AREA) != 0) ++ newPte.flags |= (1 << pteRead); ++ if ((attributes & B_WRITE_AREA) != 0) ++ newPte.flags |= (1 << pteWrite); ++ if ((attributes & B_EXECUTE_AREA) != 0) ++ newPte.flags |= (1 << pteExec); ++ } else { ++ if ((attributes & B_KERNEL_READ_AREA) != 0) ++ newPte.flags |= (1 << pteRead); ++ if ((attributes & B_KERNEL_WRITE_AREA) != 0) ++ newPte.flags |= (1 << pteWrite); ++ if ((attributes & B_KERNEL_EXECUTE_AREA) != 0) ++ newPte.flags |= (1 << pteExec); ++ } ++ *pte = newPte; ++ ++ FlushTlbPage(page); ++ } ++ ++ return B_OK; ++} ++ ++ ++status_t ++RISCV64VMTranslationMap::ProtectPage(VMArea* area, addr_t address, ++ uint32 attributes) ++{ ++ NOT_IMPLEMENTED_PANIC(); ++ return B_OK; ++} ++ ++ ++status_t ++RISCV64VMTranslationMap::ProtectArea(VMArea* area, uint32 attributes) ++{ ++ NOT_IMPLEMENTED_PANIC(); ++ return B_NOT_SUPPORTED; ++} ++ ++ ++status_t ++RISCV64VMTranslationMap::ClearFlags(addr_t address, uint32 flags) ++{ ++ ThreadCPUPinner pinner(thread_get_current_thread()); ++ Pte* pte = LookupPte(address, false, NULL); ++ if (pte == NULL || ((1 << pteValid) & pte->flags) == 0) ++ return B_OK; ++ pte->flags &= ~( ++ ((flags & PAGE_MODIFIED) ? (1 << pteDirty ) : 0) | ++ ((flags & PAGE_ACCESSED) ? (1 << pteAccessed) : 0) ++ ); ++ FlushTlbPage(address); ++ return B_OK; ++} ++ ++ ++bool ++RISCV64VMTranslationMap::ClearAccessedAndModified(VMArea* area, addr_t address, ++ bool unmapIfUnaccessed, bool& _modified) ++{ ++ TRACE("RISCV64VMPhysicalPageMapper::ClearAccessedAndModified(0x%" B_PRIxADDR ++ "(%s), 0x%" B_PRIxADDR ", %d)\n", (addr_t)area, area->name, address, ++ unmapIfUnaccessed); ++ ++ RecursiveLocker locker(fLock); ++ ThreadCPUPinner pinner(thread_get_current_thread()); ++ ++ Pte* pte = LookupPte(address, false, NULL); ++ if (pte == NULL || ((1 << pteValid) & pte->flags) == 0) { ++ return false; ++ } ++ Pte oldPte = *pte; ++ if (unmapIfUnaccessed) { ++ if (((1 << pteAccessed) & pte->flags) != 0) { ++ pte->flags &= ~((1 << pteAccessed) | (1 << pteDirty)); ++ } else { ++ pte->flags = 0; ++ pte->ppn = 0; ++ } ++ } else { ++ pte->flags &= ~((1 << pteAccessed) | (1 << pteDirty)); ++ } ++ pinner.Unlock(); ++ _modified = ((1 << pteDirty) & oldPte.flags) != 0; ++ if (((1 << pteAccessed) & oldPte.flags) != 0) { ++ FlushTlbPage(address); ++ Flush(); ++ return true; ++ } ++ ++ if (!unmapIfUnaccessed) ++ return false; ++ ++ fMapCount--; ++ ++ locker.Detach(); // UnaccessedPageUnmapped takes ownership ++ UnaccessedPageUnmapped(area, oldPte.ppn); ++ return false; ++} ++ ++ ++void ++RISCV64VMTranslationMap::Flush() ++{ ++ //NOT_IMPLEMENTED_PANIC(); ++} ++ ++ ++void ++RISCV64VMTranslationMap::DebugPrintMappingInfo(addr_t virtualAddress) ++{ ++ NOT_IMPLEMENTED_PANIC(); ++} ++ ++ ++bool ++RISCV64VMTranslationMap::DebugGetReverseMappingInfo(phys_addr_t physicalAddress, ++ ReverseMappingInfoCallback& callback) ++{ ++ NOT_IMPLEMENTED_PANIC(); ++ return false; ++} ++ ++ ++status_t ++RISCV64VMTranslationMap::MemcpyToMap(addr_t to, const char *from, size_t size) ++{ ++ TRACE("RISCV64VMPhysicalPageMapper::MemcpyToMap(0x%" B_PRIxADDR ", 0x%" ++ B_PRIxADDR ", %" B_PRIuSIZE ")\n", to, (addr_t)from, size); ++ ++ while (size > 0) { ++ uint64 va0 = ROUNDDOWN(to, B_PAGE_SIZE); ++ uint64 pa0 = LookupAddr(va0); ++ TRACE("LookupAddr(0x%" B_PRIxADDR "): 0x%" B_PRIxADDR "\n", va0, pa0); ++ if(pa0 == 0) { ++ TRACE("[!] not mapped: 0x%" B_PRIxADDR "\n", va0); ++ return B_BAD_ADDRESS; ++ } ++ uint64 n = B_PAGE_SIZE - (to - va0); ++ if(n > size) ++ n = size; ++ ++ memcpy(VirtFromPhys(pa0 + (to - va0)), from, n); ++ ++ size -= n; ++ from += n; ++ to = va0 + B_PAGE_SIZE; ++ } ++ return B_OK; ++} ++ ++ ++status_t ++RISCV64VMTranslationMap::MemcpyFromMap(char *to, addr_t from, size_t size) ++{ ++ TRACE("RISCV64VMPhysicalPageMapper::MemcpyFromMap(0x%" B_PRIxADDR ", 0x%" ++ B_PRIxADDR ", %" B_PRIuSIZE ")\n", (addr_t)to, from, size); ++ ++ while (size > 0) { ++ uint64 va0 = ROUNDDOWN(from, B_PAGE_SIZE); ++ uint64 pa0 = LookupAddr(va0); ++ if (pa0 == 0) { ++ TRACE("[!] not mapped: 0x%" B_PRIxADDR ++ ", calling page fault handler\n", va0); ++ addr_t newIP; ++ vm_page_fault(va0, Ra(), true, false, true, &newIP); ++ pa0 = LookupAddr(va0); ++ TRACE("LookupAddr(0x%" B_PRIxADDR "): 0x%" B_PRIxADDR "\n", ++ va0, pa0); ++ if (pa0 == 0) ++ return B_BAD_ADDRESS; ++ } ++ uint64 n = B_PAGE_SIZE - (from - va0); ++ if(n > size) ++ n = size; ++ memcpy(to, VirtFromPhys(pa0 + (from - va0)), n); ++ ++ size -= n; ++ to += n; ++ from = va0 + B_PAGE_SIZE; ++ } ++ ++ return B_OK; ++} ++ ++ ++status_t ++RISCV64VMTranslationMap::MemsetToMap(addr_t to, char c, size_t count) ++{ ++ TRACE("RISCV64VMPhysicalPageMapper::MemsetToMap(0x%" B_PRIxADDR ", %d, %" ++ B_PRIuSIZE ")\n", to, c, count); ++ ++ while (count > 0) { ++ uint64 va0 = ROUNDDOWN(to, B_PAGE_SIZE); ++ uint64 pa0 = LookupAddr(va0); ++ TRACE("LookupAddr(0x%" B_PRIxADDR "): 0x%" B_PRIxADDR "\n", va0, pa0); ++ if(pa0 == 0) { ++ TRACE("[!] not mapped: 0x%" B_PRIxADDR ++ ", calling page fault handler\n", va0); ++ addr_t newIP; ++ vm_page_fault(va0, Ra(), true, false, true, &newIP); ++ pa0 = LookupAddr(va0); ++ TRACE("LookupAddr(0x%" B_PRIxADDR "): 0x%" B_PRIxADDR "\n", ++ va0, pa0); ++ if (pa0 == 0) ++ return B_BAD_ADDRESS; ++ } ++ uint64 n = B_PAGE_SIZE - (to - va0); ++ if(n > count) ++ n = count; ++ ++ memset(VirtFromPhys(pa0 + (to - va0)), c, n); ++ ++ count -= n; ++ to = va0 + B_PAGE_SIZE; ++ } ++ return B_OK; ++} ++ ++ ++ssize_t ++RISCV64VMTranslationMap::StrlcpyFromMap(char *to, addr_t from, size_t size) ++{ ++ // NOT_IMPLEMENTED_PANIC(); ++ return strlcpy(to, (const char*)from, size); ++ // return 0; ++} ++ ++ ++ssize_t ++RISCV64VMTranslationMap::StrlcpyToMap(addr_t to, const char *from, size_t size) ++{ ++ ssize_t len = strlen(from) + 1; ++ if ((size_t)len > size) len = size; ++ if (MemcpyToMap(to, from, len) < B_OK) ++ return 0; ++ return len; ++} ++ ++ ++//#pragma mark RISCV64VMPhysicalPageMapper ++ ++RISCV64VMPhysicalPageMapper::RISCV64VMPhysicalPageMapper() ++{ ++ TRACE("+RISCV64VMPhysicalPageMapper\n"); ++} ++ ++ ++RISCV64VMPhysicalPageMapper::~RISCV64VMPhysicalPageMapper() ++{ ++ TRACE("-RISCV64VMPhysicalPageMapper\n"); ++} ++ ++ ++status_t ++RISCV64VMPhysicalPageMapper::GetPage(phys_addr_t physicalAddress, ++ addr_t* _virtualAddress, void** _handle) ++{ ++ *_virtualAddress = (addr_t)VirtFromPhys(physicalAddress); ++ *_handle = (void*)1; ++ return B_OK; ++} ++ ++ ++status_t ++RISCV64VMPhysicalPageMapper::PutPage(addr_t virtualAddress, void* handle) ++{ ++ return B_OK; ++} ++ ++ ++status_t ++RISCV64VMPhysicalPageMapper::GetPageCurrentCPU( phys_addr_t physicalAddress, ++ addr_t* _virtualAddress, void** _handle) ++{ ++ return GetPage(physicalAddress, _virtualAddress, _handle); ++} ++ ++ ++status_t ++RISCV64VMPhysicalPageMapper::PutPageCurrentCPU(addr_t virtualAddress, ++ void* _handle) ++{ ++ return PutPage(virtualAddress, _handle); ++} ++ ++ ++status_t ++RISCV64VMPhysicalPageMapper::GetPageDebug(phys_addr_t physicalAddress, ++ addr_t* _virtualAddress, void** _handle) ++{ ++ NOT_IMPLEMENTED_PANIC(); ++ return B_NOT_SUPPORTED; ++} ++ ++ ++status_t ++RISCV64VMPhysicalPageMapper::PutPageDebug(addr_t virtualAddress, void* handle) ++{ ++ NOT_IMPLEMENTED_PANIC(); ++ return B_NOT_SUPPORTED; ++} ++ ++ ++status_t ++RISCV64VMPhysicalPageMapper::MemsetPhysical(phys_addr_t address, int value, ++ phys_size_t length) ++{ ++ TRACE("RISCV64VMPhysicalPageMapper::MemsetPhysical(0x%" B_PRIxADDR ++ ", 0x%x, 0x%" B_PRIxADDR ")\n", address, value, length); ++ memset(VirtFromPhys(address), value, length); ++ return B_OK; ++} ++ ++ ++status_t ++RISCV64VMPhysicalPageMapper::MemcpyFromPhysical(void* to, phys_addr_t from, ++ size_t length, bool user) ++{ ++ TRACE("RISCV64VMPhysicalPageMapper::MemcpyFromPhysical(0x%" B_PRIxADDR ++ ", 0x%" B_PRIxADDR ", %" B_PRIuSIZE ")\n", (addr_t)to, from, length); ++ memcpy(to, VirtFromPhys(from), length); ++ return B_OK; ++} ++ ++ ++status_t ++RISCV64VMPhysicalPageMapper::MemcpyToPhysical(phys_addr_t to, const void* from, ++ size_t length, bool user) ++{ ++ TRACE("RISCV64VMPhysicalPageMapper::MemcpyToPhysical(0x%" B_PRIxADDR ++ ", 0x%" B_PRIxADDR ", %" B_PRIuSIZE ")\n", to, (addr_t)from, length); ++ memcpy(VirtFromPhys(to), from, length); ++ return B_OK; ++} ++ ++ ++void ++RISCV64VMPhysicalPageMapper::MemcpyPhysicalPage(phys_addr_t to, ++ phys_addr_t from) ++{ ++ TRACE("RISCV64VMPhysicalPageMapper::MemcpyPhysicalPage(0x%" B_PRIxADDR ++ ", 0x%" B_PRIxADDR ")\n", to, from); ++ memcpy(VirtFromPhys(to), VirtFromPhys(from), B_PAGE_SIZE); ++} +diff --git a/src/system/kernel/arch/riscv64/RISCV64VMTranslationMap.h b/src/system/kernel/arch/riscv64/RISCV64VMTranslationMap.h +new file mode 100644 +index 0000000000..19837441ac +--- /dev/null ++++ b/src/system/kernel/arch/riscv64/RISCV64VMTranslationMap.h +@@ -0,0 +1,140 @@ ++#ifndef _RISCV64VMTRANSLATIONMAP_H_ ++#define _RISCV64VMTRANSLATIONMAP_H_ ++ ++#include ++#include ++ ++ ++struct RISCV64VMTranslationMap: public VMTranslationMap { ++ RISCV64VMTranslationMap(bool kernel, ++ phys_addr_t pageTable = 0); ++ virtual ~RISCV64VMTranslationMap(); ++ ++ virtual bool Lock(); ++ virtual void Unlock(); ++ ++ virtual addr_t MappedSize() const; ++ virtual size_t MaxPagesNeededToMap(addr_t start, ++ addr_t end) const; ++ ++ virtual status_t Map(addr_t virtualAddress, ++ phys_addr_t physicalAddress, ++ uint32 attributes, uint32 memoryType, ++ vm_page_reservation* reservation); ++ virtual status_t Unmap(addr_t start, addr_t end); ++ ++ virtual status_t DebugMarkRangePresent(addr_t start, addr_t end, ++ bool markPresent); ++ ++ virtual status_t UnmapPage(VMArea* area, addr_t address, ++ bool updatePageQueue); ++ virtual void UnmapPages(VMArea* area, addr_t base, ++ size_t size, bool updatePageQueue); ++ virtual void UnmapArea(VMArea* area, ++ bool deletingAddressSpace, ++ bool ignoreTopCachePageFlags); ++ ++ virtual status_t Query(addr_t virtualAddress, ++ phys_addr_t* _physicalAddress, ++ uint32* _flags); ++ virtual status_t QueryInterrupt(addr_t virtualAddress, ++ phys_addr_t* _physicalAddress, ++ uint32* _flags); ++ ++ virtual status_t Protect(addr_t base, addr_t top, ++ uint32 attributes, uint32 memoryType); ++ status_t ProtectPage(VMArea* area, addr_t address, ++ uint32 attributes); ++ status_t ProtectArea(VMArea* area, ++ uint32 attributes); ++ ++ virtual status_t ClearFlags(addr_t virtualAddress, ++ uint32 flags); ++ ++ virtual bool ClearAccessedAndModified( ++ VMArea* area, addr_t address, ++ bool unmapIfUnaccessed, ++ bool& _modified); ++ ++ virtual void Flush(); ++ ++ virtual void DebugPrintMappingInfo(addr_t virtualAddress); ++ virtual bool DebugGetReverseMappingInfo( ++ phys_addr_t physicalAddress, ++ ReverseMappingInfoCallback& callback); ++ ++ inline phys_addr_t PageTable(); ++ inline uint64 Satp(); ++ ++ status_t MemcpyToMap(addr_t to, const char *from, ++ size_t size); ++ status_t MemcpyFromMap(char *to, addr_t from, ++ size_t size); ++ status_t MemsetToMap(addr_t to, char c, size_t count); ++ ssize_t StrlcpyFromMap(char *to, addr_t from, ++ size_t size); ++ ssize_t StrlcpyToMap(addr_t to, const char *from, ++ size_t size); ++ ++private: ++ Pte* LookupPte(addr_t virtAdr, bool alloc, ++ vm_page_reservation* reservation); ++ phys_addr_t LookupAddr(addr_t virtAdr); ++ ++ bool fIsKernel; ++ phys_addr_t fPageTable; ++ uint64_t fPageTableSize; // in page units ++}; ++ ++ ++inline phys_addr_t RISCV64VMTranslationMap::PageTable() ++{ ++ return fPageTable; ++} ++ ++inline uint64 RISCV64VMTranslationMap::Satp() ++{ ++ SatpReg satp; ++ satp.ppn = fPageTable / B_PAGE_SIZE; ++ satp.asid = 0; ++ satp.mode = satpModeSv39; ++ return satp.val; ++} ++ ++ ++struct RISCV64VMPhysicalPageMapper: public VMPhysicalPageMapper { ++ RISCV64VMPhysicalPageMapper(); ++ virtual ~RISCV64VMPhysicalPageMapper(); ++ ++ virtual status_t GetPage(phys_addr_t physicalAddress, ++ addr_t* _virtualAddress, ++ void** _handle); ++ virtual status_t PutPage(addr_t virtualAddress, ++ void* handle); ++ ++ virtual status_t GetPageCurrentCPU( ++ phys_addr_t physicalAddress, ++ addr_t* _virtualAddress, ++ void** _handle); ++ virtual status_t PutPageCurrentCPU(addr_t virtualAddress, ++ void* _handle); ++ ++ virtual status_t GetPageDebug(phys_addr_t physicalAddress, ++ addr_t* _virtualAddress, ++ void** _handle); ++ virtual status_t PutPageDebug(addr_t virtualAddress, ++ void* handle); ++ ++ virtual status_t MemsetPhysical(phys_addr_t address, int value, ++ phys_size_t length); ++ virtual status_t MemcpyFromPhysical(void* to, phys_addr_t from, ++ size_t length, bool user); ++ virtual status_t MemcpyToPhysical(phys_addr_t to, ++ const void* from, size_t length, ++ bool user); ++ virtual void MemcpyPhysicalPage(phys_addr_t to, ++ phys_addr_t from); ++}; ++ ++ ++#endif // _RISCV64VMTRANSLATIONMAP_H_ +diff --git a/src/system/kernel/arch/riscv64/arch_vm.cpp b/src/system/kernel/arch/riscv64/arch_vm.cpp +index 8a72900813..0027e0ed7f 100644 +--- a/src/system/kernel/arch/riscv64/arch_vm.cpp ++++ b/src/system/kernel/arch/riscv64/arch_vm.cpp +@@ -8,6 +8,7 @@ + #include + #include + #include ++#include + + + //#define TRACE_ARCH_VM +@@ -28,6 +29,13 @@ arch_vm_init(kernel_args *args) + status_t + arch_vm_init_post_area(kernel_args *args) + { ++ void* address = (void*)KERNEL_PMAP_BASE; ++ area_id area = vm_create_null_area(VMAddressSpace::KernelID(), ++ "physical map area", &address, B_EXACT_ADDRESS, ++ KERNEL_PMAP_SIZE, 0); ++ if (area < B_OK) ++ return area; ++ + return B_OK; + } + +@@ -115,8 +123,5 @@ arch_vm_unset_memory_type(VMArea *area) + status_t + arch_vm_set_memory_type(VMArea *area, phys_addr_t physicalBase, uint32 type) + { +- if (type == 0) +- return B_OK; +- +- return B_ERROR; ++ return B_OK; + } +diff --git a/src/system/kernel/arch/riscv64/arch_vm_translation_map.cpp b/src/system/kernel/arch/riscv64/arch_vm_translation_map.cpp +index afb42677a2..12df63ea9b 100644 +--- a/src/system/kernel/arch/riscv64/arch_vm_translation_map.cpp ++++ b/src/system/kernel/arch/riscv64/arch_vm_translation_map.cpp +@@ -1,7 +1,8 @@ + /* + * Copyright 2007-2010, Franรงois Revol, revol@free.fr. + * Copyright 2008-2010, Ingo Weinhold, ingo_weinhold@gmx.de. +- * Copyright 2002-2007, Axel Dรถrfler, axeld@pinc-software.de. All rights reserved. ++ * Copyright 2002-2007, Axel Dรถrfler, axeld@pinc-software.de. All rights ++ * reserved. + * Copyright 2019, Adrien Destugues, pulkomandy@pulkomandy.tk. + * Distributed under the terms of the MIT License. + * +@@ -12,9 +13,15 @@ + + #include + #include ++#include + #include + #include + #include ++#include ++#include "RISCV64VMTranslationMap.h" ++#include ++#include ++#include + + + #define TRACE_VM_TMAP +@@ -25,34 +32,245 @@ + #endif + + ++// TODO: read from FDT ++HtifRegs *volatile gHtifRegs = (HtifRegs *volatile)0x40008000; ++PlicRegs *volatile gPlicRegs = (PlicRegs *volatile)0x40100000; ++ClintRegs *volatile gClintRegs = (ClintRegs *volatile)0x02000000; ++ ++ ++phys_addr_t sPageTable = 0; ++bool sPagingEnabled = false; ++char sPhysicalPageMapperData[sizeof(RISCV64VMPhysicalPageMapper)]; ++ ++ ++static inline ++void *VirtFromPhys(uint64_t physAdr) ++{ ++ if (!sPagingEnabled) ++ return (void*)physAdr; ++ return (void*)(physAdr + (KERNEL_PMAP_BASE - 0x80000000)); ++} ++ ++ ++static inline ++uint64_t PhysFromVirt(void *virtAdr) ++{ ++ if (!sPagingEnabled) ++ return (uint64)virtAdr; ++ return (uint64)virtAdr - (KERNEL_PMAP_BASE - 0x80000000); ++} ++ ++ ++static uint64_t ++SignExtendVirtAdr(uint64_t virtAdr) ++{ ++ if (((uint64_t)1 << 38) & virtAdr) ++ return virtAdr | 0xFFFFFF8000000000; ++ return virtAdr; ++} ++ ++ ++static Pte* ++LookupPte(addr_t virtAdr, bool alloc, kernel_args* args, ++ phys_addr_t (*get_free_page)(kernel_args *)) ++{ ++ Pte *pte = (Pte*)VirtFromPhys(sPageTable); ++ for (int level = 2; level > 0; level --) { ++ pte += PhysAdrPte(virtAdr, level); ++ if (!((1 << pteValid) & pte->flags)) { ++ if (!alloc) ++ return NULL; ++ pte->ppn = get_free_page(args); ++ if (pte->ppn == 0) ++ return NULL; ++ memset((Pte*)VirtFromPhys(B_PAGE_SIZE * pte->ppn), 0, B_PAGE_SIZE); ++ pte->flags |= (1 << pteValid); ++ } ++ pte = (Pte*)VirtFromPhys(B_PAGE_SIZE * pte->ppn); ++ } ++ pte += PhysAdrPte(virtAdr, 0); ++ return pte; ++} ++ ++ ++static void ++Map(addr_t virtAdr, phys_addr_t physAdr, uint64 flags, kernel_args* args, ++ phys_addr_t (*get_free_page)(kernel_args *)) ++{ ++ // dprintf("Map(0x%" B_PRIxADDR ", 0x%" B_PRIxADDR ")\n", virtAdr, physAdr); ++ Pte* pte = LookupPte(virtAdr, true, args, get_free_page); ++ if (pte == NULL) panic("can't allocate page table"); ++ ++ pte->ppn = physAdr / B_PAGE_SIZE; ++ pte->flags = (1 << pteValid) | flags; ++ ++ if (sPagingEnabled) FlushTlbPage(virtAdr); ++} ++ ++ ++static void ++MapRange(addr_t virtAdr, phys_addr_t physAdr, size_t size, uint64 flags, ++ kernel_args* args, phys_addr_t (*get_free_page)(kernel_args *)) ++{ ++ dprintf("MapRange(0x%" B_PRIxADDR ", 0x%" B_PRIxADDR ", 0x%" ++ B_PRIxADDR ")\n", virtAdr, physAdr, size); ++ for (size_t i = 0; i < size; i += B_PAGE_SIZE) ++ Map(virtAdr + i, physAdr + i, flags, args, get_free_page); ++} ++ ++ ++static void ++PreallocKernelRange(kernel_args *args) ++{ ++ Pte *root = (Pte*)VirtFromPhys(sPageTable); ++ // NOTE: adjust range if changing kernel address space range ++ for (int i = 0; i < 256; i++) { ++ Pte *pte = &root[i]; ++ pte->ppn = vm_allocate_early_physical_page(args); ++ if (pte->ppn == 0) panic("can't alloc early physical page"); ++ memset(VirtFromPhys(B_PAGE_SIZE * pte->ppn), 0, B_PAGE_SIZE); ++ pte->flags |= (1 << pteValid); ++ } ++} ++ ++ ++void ++EnablePaging() ++{ ++ SatpReg satp; ++ satp.ppn = sPageTable / B_PAGE_SIZE; ++ satp.asid = 0; ++ satp.mode = satpModeSv39; ++ SetSatp(satp.val); ++ FlushTlbAll(); ++ sPagingEnabled = true; ++} ++ ++ ++static void ++WritePteFlags(uint32 flags) ++{ ++ bool first = true; ++ dprintf("{"); ++ for (uint32 i = 0; i < 32; i++) { ++ if ((1 << i) & flags) { ++ if (first) first = false; else dprintf(", "); ++ switch (i) { ++ case pteValid: dprintf("valid"); break; ++ case pteRead: dprintf("read"); break; ++ case pteWrite: dprintf("write"); break; ++ case pteExec: dprintf("exec"); break; ++ case pteUser: dprintf("user"); break; ++ case pteGlobal: dprintf("global"); break; ++ case pteAccessed: dprintf("accessed"); break; ++ case pteDirty: dprintf("dirty"); break; ++ default: dprintf("%" B_PRIu32, i); ++ } ++ } ++ } ++ dprintf("}"); ++} ++ ++ ++static void ++DumpPageTableInt(Pte* pte, uint64_t virtAdr, uint32_t level) ++{ ++ for (uint32 i = 0; i < pteCount; i++) { ++ if ((1 << pteValid) & pte[i].flags) { ++ if (level == 0) { ++ dprintf(" 0x%08" B_PRIxADDR, ++ SignExtendVirtAdr(virtAdr + i * B_PAGE_SIZE)); ++ dprintf(": 0x%08" B_PRIxADDR ", ", pte[i].ppn * B_PAGE_SIZE); ++ WritePteFlags(pte[i].flags); dprintf("\n"); ++ } else { ++ DumpPageTableInt((Pte*)VirtFromPhys(pageSize*pte[i].ppn), ++ virtAdr + ((uint64_t)i << (pageBits + pteIdxBits*level)), ++ level - 1); ++ } ++ } ++ } ++} ++ ++ ++static void ++DumpPageTable(Pte* root) ++{ ++ dprintf("PageTable:\n"); ++ DumpPageTableInt(root, 0, 2); ++} ++ ++ ++//#pragma mark - ++ + status_t + arch_vm_translation_map_init(kernel_args *args, + VMPhysicalPageMapper** _physicalPageMapper) + { + TRACE("vm_translation_map_init: entry\n"); + ++ sPageTable = vm_allocate_early_physical_page(args) * B_PAGE_SIZE; ++ PreallocKernelRange(args); ++ ++ // TODO: don't hardcode RAM base ++ MapRange(KERNEL_PMAP_BASE, 0x80000000, args->physical_memory_range[0].size, ++ (1 << pteRead) | (1 << pteWrite), ++ args, vm_allocate_early_physical_page); ++ ++ for (uint32 i = 0; i < args->num_virtual_allocated_ranges; i++) { ++ addr_t start = args->virtual_allocated_range[i].start; ++ size_t size = args->virtual_allocated_range[i].size; ++ MapRange(start, start, size, ++ (1 << pteRead) | (1 << pteWrite) | (1 << pteExec), ++ args, vm_allocate_early_physical_page); ++ } ++ ++ // TODO: read from FDT ++ // CLINT ++ MapRange( 0x2000000, 0x2000000, 0xC0000, (1 << pteRead) | (1 << pteWrite), ++ args, vm_allocate_early_physical_page); ++ // HTIF ++ MapRange(0x40008000, 0x40008000, 0x1000, (1 << pteRead) | (1 << pteWrite), ++ args, vm_allocate_early_physical_page); ++ // PLIC ++ MapRange(0x40100000, 0x40100000, 0x400000, (1 << pteRead) | (1 << pteWrite), ++ args, vm_allocate_early_physical_page); ++ ++ { ++ SstatusReg status(Sstatus()); ++ status.sum = 1; ++ SetSstatus(status.val); ++ } ++ ++ EnablePaging(); ++ ++ *_physicalPageMapper = new(&sPhysicalPageMapperData) ++ RISCV64VMPhysicalPageMapper(); ++ ++ if (false) { ++ DumpPageTable((Pte*)VirtFromPhys(sPageTable)); ++ HtifShutdown(); ++ } ++ + #ifdef TRACE_VM_TMAP + TRACE("physical memory ranges:\n"); + for (uint32 i = 0; i < args->num_physical_memory_ranges; i++) { + phys_addr_t start = args->physical_memory_range[i].start; + phys_addr_t end = start + args->physical_memory_range[i].size; +- TRACE(" %#10" B_PRIxPHYSADDR " - %#10" B_PRIxPHYSADDR "\n", start, +- end); ++ TRACE(" %" B_PRIxPHYSADDR " - %" B_PRIxPHYSADDR "\n", start, end); + } + + TRACE("allocated physical ranges:\n"); + for (uint32 i = 0; i < args->num_physical_allocated_ranges; i++) { + phys_addr_t start = args->physical_allocated_range[i].start; + phys_addr_t end = start + args->physical_allocated_range[i].size; +- TRACE(" %#10" B_PRIxPHYSADDR " - %#10" B_PRIxPHYSADDR "\n", start, +- end); ++ TRACE(" %" B_PRIxPHYSADDR " - %" B_PRIxPHYSADDR "\n", start, end); + } + + TRACE("allocated virtual ranges:\n"); + for (uint32 i = 0; i < args->num_virtual_allocated_ranges; i++) { + addr_t start = args->virtual_allocated_range[i].start; + addr_t end = start + args->virtual_allocated_range[i].size; +- TRACE(" %#10" B_PRIxADDR " - %#10" B_PRIxADDR "\n", start, end); ++ TRACE(" %" B_PRIxADDR " - %" B_PRIxADDR "\n", start, end); + } + #endif + +@@ -79,7 +297,11 @@ status_t + arch_vm_translation_map_early_map(kernel_args *args, addr_t va, phys_addr_t pa, + uint8 attributes, phys_addr_t (*get_free_page)(kernel_args *)) + { +- TRACE("early_tmap: entry pa 0x%lx va 0x%lx\n", pa, va); ++ uint64 flags = 0; ++ if ((attributes & B_KERNEL_READ_AREA) != 0) flags |= (1 << pteRead); ++ if ((attributes & B_KERNEL_WRITE_AREA) != 0) flags |= (1 << pteWrite); ++ if ((attributes & B_KERNEL_EXECUTE_AREA) != 0) flags |= (1 << pteExec); ++ Map(va, pa, flags, args, get_free_page); + return B_OK; + } + +@@ -87,6 +309,12 @@ arch_vm_translation_map_early_map(kernel_args *args, addr_t va, phys_addr_t pa, + status_t + arch_vm_translation_map_create_map(bool kernel, VMTranslationMap** _map) + { ++ *_map = new(std::nothrow) RISCV64VMTranslationMap(kernel, ++ (kernel) ? sPageTable : 0); ++ ++ if (*_map == NULL) ++ return B_NO_MEMORY; ++ + return B_OK; + } + +@@ -95,6 +323,5 @@ bool + arch_vm_translation_map_is_kernel_page_accessible(addr_t virtualAddress, + uint32 protection) + { +- return false; ++ return virtualAddress != 0; + } +- +-- +2.30.2 + diff --git a/patchset-hrev55144/0037-kernel-arch-thread-implement-for-riscv64.patch b/patchset-hrev55144/0037-kernel-arch-thread-implement-for-riscv64.patch new file mode 100644 index 0000000..4a77ba6 --- /dev/null +++ b/patchset-hrev55144/0037-kernel-arch-thread-implement-for-riscv64.patch @@ -0,0 +1,658 @@ +From bb6e76a5b935a4b2600c0651a3883ae0a555a45c Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 22:15:18 +0900 +Subject: kernel/arch/thread: implement for riscv64 + +Change-Id: I3effa598626b32c29606299cd0edee390d430baf +--- + headers/posix/arch/riscv64/signal.h | 2 +- + .../private/kernel/arch/riscv64/arch_thread.h | 14 +- + .../kernel/arch/riscv64/arch_thread_types.h | 80 +++++- + src/system/kernel/arch/riscv64/arch_asm.S | 152 +++++++++++ + .../kernel/arch/riscv64/arch_thread.cpp | 243 +++++++++++++++++- + 5 files changed, 453 insertions(+), 38 deletions(-) + +diff --git a/headers/posix/arch/riscv64/signal.h b/headers/posix/arch/riscv64/signal.h +index a394b48c07..37fafae524 100644 +--- a/headers/posix/arch/riscv64/signal.h ++++ b/headers/posix/arch/riscv64/signal.h +@@ -16,7 +16,7 @@ struct vregs { + ulong x[31]; + ulong pc; + double f[32]; +- char fcsr; ++ ulong fcsr; + }; + #endif /* defined(__RISCV64__) */ + +diff --git a/headers/private/kernel/arch/riscv64/arch_thread.h b/headers/private/kernel/arch/riscv64/arch_thread.h +index 5da6ac7fa9..3b9e8e5ced 100644 +--- a/headers/private/kernel/arch/riscv64/arch_thread.h ++++ b/headers/private/kernel/arch/riscv64/arch_thread.h +@@ -11,30 +11,24 @@ + + #include + +-#warning IMPLEMENT arch_thread.h +- + #ifdef __cplusplus + extern "C" { + #endif + +-void riscv64_push_iframe(struct iframe_stack* stack, struct iframe* frame); +-void riscv64_pop_iframe(struct iframe_stack* stack); +-struct iframe* riscv64_get_user_iframe(void); +- + + static inline Thread* + arch_thread_get_current_thread(void) + { +-#warning IMPLEMENT arch_thread_get_current_thread +- Thread* t = NULL; +- return t; ++ Thread* t; ++ asm volatile("mv %0, tp" : "=r" (t)); ++ return t; + } + + + static inline void + arch_thread_set_current_thread(Thread* t) + { +-#warning IMPLEMENT arch_thread_set_current_thread ++ asm volatile("mv tp, %0" : : "r" (t)); + } + + +diff --git a/headers/private/kernel/arch/riscv64/arch_thread_types.h b/headers/private/kernel/arch/riscv64/arch_thread_types.h +index cbcd9f70c8..a0c99bc8b3 100644 +--- a/headers/private/kernel/arch/riscv64/arch_thread_types.h ++++ b/headers/private/kernel/arch/riscv64/arch_thread_types.h +@@ -7,20 +7,65 @@ + + #include + +-#define IFRAME_TRACE_DEPTH 4 + +-struct iframe_stack { +- struct iframe *frames[IFRAME_TRACE_DEPTH]; +- int32 index; ++namespace BKernel { ++ struct Thread; ++} ++ ++ ++struct iframe { ++ uint64 ra; ++ uint64 t6; ++ uint64 sp; ++ uint64 gp; ++ uint64 tp; ++ uint64 t0; ++ uint64 t1; ++ uint64 t2; ++ uint64 t5; ++ uint64 s1; ++ uint64 a0; ++ uint64 a1; ++ uint64 a2; ++ uint64 a3; ++ uint64 a4; ++ uint64 a5; ++ uint64 a6; ++ uint64 a7; ++ uint64 s2; ++ uint64 s3; ++ uint64 s4; ++ uint64 s5; ++ uint64 s6; ++ uint64 s7; ++ uint64 s8; ++ uint64 s9; ++ uint64 s10; ++ uint64 s11; ++ uint64 t3; ++ uint64 t4; ++ uint64 fp; ++ uint64 epc; + }; + +-// architecture specific thread info +-struct arch_thread { +- void *sp; // stack pointer +- void *interrupt_stack; ++struct arch_context { ++ uint64 ra; // 0 ++ uint64 s[12]; // 12 ++ uint64 sp; // 13 ++ uint64 satp; // 14 ++}; + +- // used to track interrupts on this thread +- struct iframe_stack iframes; ++struct fpu_context { ++ double f[32]; ++ uint64 fcsr; ++}; ++ ++ ++struct arch_thread { ++ BKernel::Thread* thread; ++ arch_context context; ++ fpu_context fpuContext; ++ iframe* userFrame; + }; + + struct arch_team { +@@ -31,10 +76,17 @@ struct arch_team { + }; + + struct arch_fork_arg { +- // gcc treats empty structures as zero-length in C, but as if they contain +- // a char in C++. So we have to put a dummy in to be able to use the struct +- // from both in a consistent way. +- char dummy; ++ iframe frame; + }; + ++ ++extern "C" int arch_setjmp(arch_context* ctx); ++extern "C" void arch_longjmp(arch_context* ctx, int val); ++extern "C" void save_fpu(fpu_context* ctx); ++extern "C" void restore_fpu(fpu_context* ctx); ++extern "C" void arch_thread_entry(); ++extern "C" void arch_enter_userspace(void *arg1, void *arg2, addr_t sp); ++extern "C" void arch_longjmp_iframe(iframe* frame); ++ ++ + #endif /* KERNEL_ARCH_RISCV64_THREAD_TYPES_H */ +diff --git a/src/system/kernel/arch/riscv64/arch_asm.S b/src/system/kernel/arch/riscv64/arch_asm.S +index f345a1167b..f4d9d6284a 100644 +--- a/src/system/kernel/arch/riscv64/arch_asm.S ++++ b/src/system/kernel/arch/riscv64/arch_asm.S +@@ -8,3 +8,155 @@ + + + .text ++ ++ ++FUNCTION(MSyscall): ++ ecall ++ ret ++FUNCTION_END(MSyscall) ++ ++ ++FUNCTION(arch_setjmp): ++ sd ra, 0*8(a0) ++ sd s0, 1*8(a0) ++ sd s1, 2*8(a0) ++ sd s2, 3*8(a0) ++ sd s3, 4*8(a0) ++ sd s4, 5*8(a0) ++ sd s5, 6*8(a0) ++ sd s6, 7*8(a0) ++ sd s7, 8*8(a0) ++ sd s8, 9*8(a0) ++ sd s9, 10*8(a0) ++ sd s10, 11*8(a0) ++ sd s11, 12*8(a0) ++ sd sp, 13*8(a0) ++ csrr t0, satp ++ sd t0, 14*8(a0) ++ ++ li a0, 0 ++ ret ++FUNCTION_END(arch_setjmp) ++ ++ ++FUNCTION(arch_longjmp): ++ ld ra, 0*8(a0) ++ ld s0, 1*8(a0) ++ ld s1, 2*8(a0) ++ ld s2, 3*8(a0) ++ ld s3, 4*8(a0) ++ ld s4, 5*8(a0) ++ ld s5, 6*8(a0) ++ ld s6, 7*8(a0) ++ ld s7, 8*8(a0) ++ ld s8, 9*8(a0) ++ ld s9, 10*8(a0) ++ ld s10, 11*8(a0) ++ ld s11, 12*8(a0) ++ ld sp, 13*8(a0) ++ ld t0, 14*8(a0) ++ csrw satp, t0 ++ sfence.vma ++ ++ seqz a0, a1 ++ add a0, a0, a1 # a0 = (a1 == 0) ? 1 : a1 ++ ret ++FUNCTION_END(arch_longjmp) ++ ++ ++FUNCTION(save_fpu): ++ fsd f0, 0*8(a0) ++ fsd f1, 1*8(a0) ++ fsd f2, 2*8(a0) ++ fsd f3, 3*8(a0) ++ fsd f4, 4*8(a0) ++ fsd f5, 5*8(a0) ++ fsd f6, 6*8(a0) ++ fsd f7, 7*8(a0) ++ fsd f8, 8*8(a0) ++ fsd f9, 9*8(a0) ++ fsd f10, 10*8(a0) ++ fsd f11, 11*8(a0) ++ fsd f12, 12*8(a0) ++ fsd f13, 13*8(a0) ++ fsd f14, 14*8(a0) ++ fsd f15, 15*8(a0) ++ fsd f16, 16*8(a0) ++ fsd f17, 17*8(a0) ++ fsd f18, 18*8(a0) ++ fsd f19, 19*8(a0) ++ fsd f20, 20*8(a0) ++ fsd f21, 21*8(a0) ++ fsd f22, 22*8(a0) ++ fsd f23, 23*8(a0) ++ fsd f24, 24*8(a0) ++ fsd f25, 25*8(a0) ++ fsd f26, 26*8(a0) ++ fsd f27, 27*8(a0) ++ fsd f28, 28*8(a0) ++ fsd f29, 29*8(a0) ++ fsd f30, 30*8(a0) ++ fsd f31, 31*8(a0) ++ frcsr t0 ++ sd t0, 32*8(a0) ++ ++ ret ++FUNCTION_END(save_fpu) ++ ++ ++FUNCTION(restore_fpu): ++ fld f0, 0*8(a0) ++ fld f1, 1*8(a0) ++ fld f2, 2*8(a0) ++ fld f3, 3*8(a0) ++ fld f4, 4*8(a0) ++ fld f5, 5*8(a0) ++ fld f6, 6*8(a0) ++ fld f7, 7*8(a0) ++ fld f8, 8*8(a0) ++ fld f9, 9*8(a0) ++ fld f10, 10*8(a0) ++ fld f11, 11*8(a0) ++ fld f12, 12*8(a0) ++ fld f13, 13*8(a0) ++ fld f14, 14*8(a0) ++ fld f15, 15*8(a0) ++ fld f16, 16*8(a0) ++ fld f17, 17*8(a0) ++ fld f18, 18*8(a0) ++ fld f19, 19*8(a0) ++ fld f20, 20*8(a0) ++ fld f21, 21*8(a0) ++ fld f22, 22*8(a0) ++ fld f23, 23*8(a0) ++ fld f24, 24*8(a0) ++ fld f25, 25*8(a0) ++ fld f26, 26*8(a0) ++ fld f27, 27*8(a0) ++ fld f28, 28*8(a0) ++ fld f29, 29*8(a0) ++ fld f30, 30*8(a0) ++ fld f31, 31*8(a0) ++ ld t0, 32*8(a0) ++ fscsr t0 ++ ++ ret ++FUNCTION_END(restore_fpu) ++ ++ ++FUNCTION(arch_thread_entry): ++ mv a0, s2 ++ JALR s1 ++FUNCTION_END(arch_thread_entry) ++ ++ ++FUNCTION(arch_enter_userspace): ++ mv sp, a2 ++ sret ++FUNCTION_END(arch_enter_userspace) ++ ++ ++FUNCTION(arch_longjmp_iframe): ++ mv sp, a0 ++ call SVecURet ++FUNCTION_END(arch_longjmp_iframe) +diff --git a/src/system/kernel/arch/riscv64/arch_thread.cpp b/src/system/kernel/arch/riscv64/arch_thread.cpp +index eda19a1cd2..2a17506e9e 100644 +--- a/src/system/kernel/arch/riscv64/arch_thread.cpp ++++ b/src/system/kernel/arch/riscv64/arch_thread.cpp +@@ -10,7 +10,23 @@ + #include + #include + #include ++#include ++#include ++#include + #include ++#include ++#include "RISCV64VMTranslationMap.h" ++#include ++ ++ ++extern "C" void SVecU(); ++ ++ ++extern "C" void RestoreUserRegs() ++{ ++ SetSscratch((addr_t)&thread_get_current_thread()->arch_info); ++ SetTp(thread_get_current_thread()->user_local_storage); ++} + + + status_t +@@ -34,9 +50,7 @@ arch_team_init_team_struct(Team *team, bool kernel) + status_t + arch_thread_init_thread_struct(Thread *thread) + { +- // set up an initial state (stack & fpu) +- //memcpy(&thread->arch_info, &sInitialState, sizeof(struct arch_thread)); +- ++ thread->arch_info.thread = thread; + return B_OK; + } + +@@ -45,22 +59,52 @@ void + arch_thread_init_kthread_stack(Thread* thread, void* _stack, void* _stackTop, + void (*function)(void*), const void* data) + { +- #warning RISCV64: Implement thread init kthread +- panic("arch_thread_init_kthread_stack(): Implement me!"); ++ dprintf("arch_thread_init_kthread_stack(%p(%s))\n", thread, thread->name); ++ memset(&thread->arch_info.context, 0, sizeof(arch_context)); ++ thread->arch_info.context.sp = (addr_t)_stackTop; ++ thread->arch_info.context.s[0] = 0; // fp ++ thread->arch_info.context.s[1] = (addr_t)function; ++ thread->arch_info.context.s[2] = (addr_t)data; ++ thread->arch_info.context.ra = (addr_t)arch_thread_entry; ++ VMTranslationMap* map = (thread->team == team_get_kernel_team()) ++ ? VMAddressSpace::Kernel()->TranslationMap() ++ : thread->team->address_space->TranslationMap(); ++ thread->arch_info.context.satp = ((RISCV64VMTranslationMap*)map)->Satp(); + } + + + status_t + arch_thread_init_tls(Thread *thread) + { +- // TODO: Implement! +- return B_OK; ++ addr_t tls[TLS_FIRST_FREE_SLOT]; ++ ++ thread->user_local_storage = thread->user_stack_base ++ + thread->user_stack_size; ++ ++ // initialize default TLS fields ++ memset(tls, 0, sizeof(tls)); ++ tls[TLS_BASE_ADDRESS_SLOT] = thread->user_local_storage; ++ tls[TLS_THREAD_ID_SLOT] = thread->id; ++ tls[TLS_USER_THREAD_SLOT] = (addr_t)thread->user_thread; ++ ++ return user_memcpy((void*)thread->user_local_storage, tls, sizeof(tls)); + } + + + void + arch_thread_context_switch(Thread *from, Thread *to) + { ++ /* ++ dprintf("arch_thread_context_switch(%p(%s), %p(%s))\n", from, from->name, ++ to, to->name); ++ */ ++ if (arch_setjmp(&from->arch_info.context) == 0) { ++ // TODO: save/restore FPU only if needed ++ save_fpu(&from->arch_info.fpuContext); ++ arch_longjmp(&to->arch_info.context, 1); ++ } else { ++ restore_fpu(&from->arch_info.fpuContext); ++ } + } + + +@@ -71,9 +115,25 @@ arch_thread_dump_info(void *info) + + + status_t +-arch_thread_enter_userspace(Thread *thread, addr_t entry, void *arg1, void *arg2) ++arch_thread_enter_userspace(Thread *thread, addr_t entry, void *arg1, ++ void *arg2) + { +- panic("arch_thread_enter_uspace(): not yet implemented\n"); ++ dprintf("arch_thread_enter_uspace()\n"); ++ ++ disable_interrupts(); ++ if (arch_setjmp(&thread->arch_info.context) == 0) { ++ SstatusReg status(Sstatus()); ++ status.pie = (1 << modeS); // enable interrupts when enter userspace ++ status.spp = modeU; ++ SetSstatus(status.val); ++ SetStvec((addr_t)SVecU); ++ SetSepc(entry); ++ RestoreUserRegs(); ++ arch_enter_userspace(arg1, arg2, ++ thread->user_stack_base + thread->user_stack_size); ++ } else { ++ panic("return from userspace"); ++ } + return B_ERROR; + } + +@@ -81,7 +141,35 @@ arch_thread_enter_userspace(Thread *thread, addr_t entry, void *arg1, void *arg2 + bool + arch_on_signal_stack(Thread *thread) + { +- return false; ++ struct iframe* frame = thread->arch_info.userFrame; ++ if (frame == NULL) { ++ panic("arch_on_signal_stack(): No user iframe!"); ++ return false; ++ } ++ ++ return frame->sp >= thread->signal_stack_base ++ && frame->sp < thread->signal_stack_base ++ + thread->signal_stack_size; ++} ++ ++ ++static uint8* ++get_signal_stack(Thread* thread, struct iframe* frame, ++ struct sigaction* action, size_t spaceNeeded) ++{ ++ // use the alternate signal stack if we should and can ++ if ( ++ thread->signal_stack_enabled && ++ (action->sa_flags & SA_ONSTACK) != 0 && ( ++ frame->sp < thread->signal_stack_base || ++ frame->sp >= thread->signal_stack_base + thread->signal_stack_size ++ ) ++ ) { ++ addr_t stackTop = thread->signal_stack_base ++ + thread->signal_stack_size; ++ return (uint8*)ROUNDDOWN(stackTop - spaceNeeded, 16); ++ } ++ return (uint8*)ROUNDDOWN(frame->sp - spaceNeeded, 16); + } + + +@@ -89,20 +177,132 @@ status_t + arch_setup_signal_frame(Thread *thread, struct sigaction *sa, + struct signal_frame_data *signalFrameData) + { +- return B_ERROR; ++ dprintf("arch_setup_signal_frame()\n"); ++ iframe* frame = thread->arch_info.userFrame; ++ ++ // fill signal context ++ signalFrameData->context.uc_mcontext.x[ 0] = frame->ra; ++ signalFrameData->context.uc_mcontext.x[ 1] = frame->sp; ++ signalFrameData->context.uc_mcontext.x[ 2] = frame->gp; ++ signalFrameData->context.uc_mcontext.x[ 3] = frame->tp; ++ signalFrameData->context.uc_mcontext.x[ 4] = frame->t0; ++ signalFrameData->context.uc_mcontext.x[ 5] = frame->t1; ++ signalFrameData->context.uc_mcontext.x[ 6] = frame->t2; ++ signalFrameData->context.uc_mcontext.x[ 7] = frame->fp; ++ signalFrameData->context.uc_mcontext.x[ 8] = frame->s1; ++ signalFrameData->context.uc_mcontext.x[ 9] = frame->a0; ++ signalFrameData->context.uc_mcontext.x[10] = frame->a1; ++ signalFrameData->context.uc_mcontext.x[11] = frame->a2; ++ signalFrameData->context.uc_mcontext.x[12] = frame->a3; ++ signalFrameData->context.uc_mcontext.x[13] = frame->a4; ++ signalFrameData->context.uc_mcontext.x[14] = frame->a5; ++ signalFrameData->context.uc_mcontext.x[15] = frame->a6; ++ signalFrameData->context.uc_mcontext.x[16] = frame->a7; ++ signalFrameData->context.uc_mcontext.x[17] = frame->s2; ++ signalFrameData->context.uc_mcontext.x[18] = frame->s3; ++ signalFrameData->context.uc_mcontext.x[19] = frame->s4; ++ signalFrameData->context.uc_mcontext.x[20] = frame->s5; ++ signalFrameData->context.uc_mcontext.x[21] = frame->s6; ++ signalFrameData->context.uc_mcontext.x[22] = frame->s7; ++ signalFrameData->context.uc_mcontext.x[23] = frame->s8; ++ signalFrameData->context.uc_mcontext.x[24] = frame->s9; ++ signalFrameData->context.uc_mcontext.x[25] = frame->s10; ++ signalFrameData->context.uc_mcontext.x[26] = frame->s11; ++ signalFrameData->context.uc_mcontext.x[27] = frame->t3; ++ signalFrameData->context.uc_mcontext.x[28] = frame->t4; ++ signalFrameData->context.uc_mcontext.x[29] = frame->t5; ++ signalFrameData->context.uc_mcontext.x[30] = frame->t6; ++ signalFrameData->context.uc_mcontext.pc = frame->epc; ++ // TODO: don't assume that kernel code don't use FPU ++ save_fpu((fpu_context*)&signalFrameData->context.uc_mcontext.f[0]); ++ // end of fill signal context ++ ++ signal_get_user_stack(frame->sp, &signalFrameData->context.uc_stack); ++ ++ dprintf(" thread->signal_stack_enabled: %d\n", ++ thread->signal_stack_enabled); ++ if (thread->signal_stack_enabled) { ++ dprintf(" signal stack: 0x%" B_PRIxADDR " - 0x%" B_PRIxADDR "\n", ++ thread->signal_stack_base, ++ thread->signal_stack_base + thread->signal_stack_size ++ ); ++ } ++ ++ uint8* userStack = get_signal_stack(thread, frame, sa, ++ sizeof(*signalFrameData)); ++ dprintf(" user stack: 0x%" B_PRIxADDR "\n", (addr_t)userStack); ++ status_t res = user_memcpy(userStack, signalFrameData, ++ sizeof(*signalFrameData)); ++ if (res < B_OK) ++ return res; ++ ++ addr_t commpageAdr = (addr_t)thread->team->commpage_address; ++ dprintf(" commpageAdr: 0x%" B_PRIxADDR "\n", commpageAdr); ++ addr_t signalHandlerAddr; ++ ASSERT(user_memcpy(&signalHandlerAddr, ++ &((addr_t*)commpageAdr)[COMMPAGE_ENTRY_RISCV64_SIGNAL_HANDLER], ++ sizeof(signalHandlerAddr)) >= B_OK); ++ signalHandlerAddr += commpageAdr; ++ ++ frame->ra = frame->epc; ++ frame->sp = (addr_t)userStack; ++ frame->epc = signalHandlerAddr; ++ frame->a0 = frame->sp; ++ ++ // WriteTrapInfo(); ++ ++ return B_OK; + } + + + int64 + arch_restore_signal_frame(struct signal_frame_data* signalFrameData) + { +- return 0; ++ dprintf("arch_restore_signal_frame()\n"); ++ iframe* frame = thread_get_current_thread()->arch_info.userFrame; ++ ++ frame->ra = signalFrameData->context.uc_mcontext.x[ 0]; ++ frame->sp = signalFrameData->context.uc_mcontext.x[ 1]; ++ frame->gp = signalFrameData->context.uc_mcontext.x[ 2]; ++ frame->tp = signalFrameData->context.uc_mcontext.x[ 3]; ++ frame->t0 = signalFrameData->context.uc_mcontext.x[ 4]; ++ frame->t1 = signalFrameData->context.uc_mcontext.x[ 5]; ++ frame->t2 = signalFrameData->context.uc_mcontext.x[ 6]; ++ frame->fp = signalFrameData->context.uc_mcontext.x[ 7]; ++ frame->s1 = signalFrameData->context.uc_mcontext.x[ 8]; ++ frame->a0 = signalFrameData->context.uc_mcontext.x[ 9]; ++ frame->a1 = signalFrameData->context.uc_mcontext.x[10]; ++ frame->a2 = signalFrameData->context.uc_mcontext.x[11]; ++ frame->a3 = signalFrameData->context.uc_mcontext.x[12]; ++ frame->a4 = signalFrameData->context.uc_mcontext.x[13]; ++ frame->a5 = signalFrameData->context.uc_mcontext.x[14]; ++ frame->a6 = signalFrameData->context.uc_mcontext.x[15]; ++ frame->a7 = signalFrameData->context.uc_mcontext.x[16]; ++ frame->s2 = signalFrameData->context.uc_mcontext.x[17]; ++ frame->s3 = signalFrameData->context.uc_mcontext.x[18]; ++ frame->s4 = signalFrameData->context.uc_mcontext.x[19]; ++ frame->s5 = signalFrameData->context.uc_mcontext.x[20]; ++ frame->s6 = signalFrameData->context.uc_mcontext.x[21]; ++ frame->s7 = signalFrameData->context.uc_mcontext.x[22]; ++ frame->s8 = signalFrameData->context.uc_mcontext.x[23]; ++ frame->s9 = signalFrameData->context.uc_mcontext.x[24]; ++ frame->s10 = signalFrameData->context.uc_mcontext.x[25]; ++ frame->s11 = signalFrameData->context.uc_mcontext.x[26]; ++ frame->t3 = signalFrameData->context.uc_mcontext.x[27]; ++ frame->t4 = signalFrameData->context.uc_mcontext.x[28]; ++ frame->t5 = signalFrameData->context.uc_mcontext.x[29]; ++ frame->t6 = signalFrameData->context.uc_mcontext.x[30]; ++ frame->epc = signalFrameData->context.uc_mcontext.pc; ++ restore_fpu((fpu_context*)&signalFrameData->context.uc_mcontext.f[0]); ++ ++ return frame->a0; + } + + + void + arch_check_syscall_restart(Thread *thread) + { ++ panic("arch_check_syscall_restart(): not yet implemented\n"); + } + + +@@ -114,6 +314,13 @@ arch_check_syscall_restart(Thread *thread) + void + arch_store_fork_frame(struct arch_fork_arg *arg) + { ++ dprintf("arch_store_fork_frame()\n"); ++ dprintf(" arg: %p\n", arg); ++ dprintf(" userFrame: %p\n", ++ thread_get_current_thread()->arch_info.userFrame); ++ memcpy(&arg->frame, thread_get_current_thread()->arch_info.userFrame, ++ sizeof(iframe)); ++ arg->frame.a0 = 0; // fork return value + } + + +@@ -128,5 +335,15 @@ arch_store_fork_frame(struct arch_fork_arg *arg) + void + arch_restore_fork_frame(struct arch_fork_arg *arg) + { ++ dprintf("arch_restore_fork_frame(%p)\n", arg); ++ disable_interrupts(); ++ if (arch_setjmp(&thread_get_current_thread()->arch_info.context) == 0) { ++ SstatusReg status(Sstatus()); ++ status.pie = (1 << modeS); // enable interrupts when enter userspace ++ status.spp = modeU; ++ SetSstatus(status.val); ++ arch_longjmp_iframe(&arg->frame); ++ } else { ++ panic("return from userspace"); ++ } + } +- +-- +2.30.2 + diff --git a/patchset-hrev55144/0038-kernel-arch-int-implement-for-riscv64.patch b/patchset-hrev55144/0038-kernel-arch-int-implement-for-riscv64.patch new file mode 100644 index 0000000..a0a10b1 --- /dev/null +++ b/patchset-hrev55144/0038-kernel-arch-int-implement-for-riscv64.patch @@ -0,0 +1,679 @@ +From 885db550622c2343bd23c20ebab837c8e7964bcd Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 22:20:49 +0900 +Subject: kernel/arch/int: implement for riscv64 + +Change-Id: I62d9bff75d35a685983c626720514ff17b1cef00 +--- + .../private/kernel/arch/riscv64/arch_int.h | 27 +- + src/system/kernel/arch/riscv64/Jamfile | 1 + + src/system/kernel/arch/riscv64/arch_int.cpp | 417 +++++++++++++++++- + src/system/kernel/arch/riscv64/arch_traps.S | 116 +++++ + 4 files changed, 552 insertions(+), 9 deletions(-) + create mode 100644 src/system/kernel/arch/riscv64/arch_traps.S + +diff --git a/headers/private/kernel/arch/riscv64/arch_int.h b/headers/private/kernel/arch/riscv64/arch_int.h +index 3fd814d512..85331a8c0d 100644 +--- a/headers/private/kernel/arch/riscv64/arch_int.h ++++ b/headers/private/kernel/arch/riscv64/arch_int.h +@@ -10,6 +10,7 @@ + #define _KERNEL_ARCH_RISCV64_INT_H + + #include ++#include + + #define NUM_IO_VECTORS 256 + +@@ -17,30 +18,36 @@ + static inline void + arch_int_enable_interrupts_inline(void) + { +- // TODO: implement ++ SstatusReg status(Sstatus()); ++ status.ie |= (1 << modeS); ++ SetSstatus(status.val); + } + + + static inline int + arch_int_disable_interrupts_inline(void) + { +- // TODO: implement +- return 0; ++ SstatusReg status(Sstatus()); ++ int oldState = ((1 << modeS) & status.ie) != 0; ++ status.ie &= ~(1 << modeS); ++ SetSstatus(status.val); ++ return oldState; + } + + + static inline void + arch_int_restore_interrupts_inline(int oldState) + { +- // TODO: implement ++ if (oldState) ++ arch_int_enable_interrupts_inline(); + } + + + static inline bool + arch_int_are_interrupts_enabled_inline(void) + { +- // TODO: implement +- return false; ++ SstatusReg status(Sstatus()); ++ return ((1 << modeS) & status.ie) != 0; + } + + +@@ -53,4 +60,12 @@ arch_int_are_interrupts_enabled_inline(void) + arch_int_are_interrupts_enabled_inline() + + ++enum { ++ switchToSmodeMmodeSyscall = 0, ++ setTimerMmodeSyscall = 1, ++}; ++ ++extern "C" status_t MSyscall(...); ++ ++ + #endif /* _KERNEL_ARCH_RISCV64_INT_H */ +diff --git a/src/system/kernel/arch/riscv64/Jamfile b/src/system/kernel/arch/riscv64/Jamfile +index e6d005b3ef..0371ebb210 100644 +--- a/src/system/kernel/arch/riscv64/Jamfile ++++ b/src/system/kernel/arch/riscv64/Jamfile +@@ -5,6 +5,7 @@ UsePrivateKernelHeaders ; + + KernelMergeObject kernel_arch_riscv64.o : + arch_asm.S ++ arch_traps.S + arch_commpage.cpp + arch_cpu.cpp + arch_debug.cpp +diff --git a/src/system/kernel/arch/riscv64/arch_int.cpp b/src/system/kernel/arch/riscv64/arch_int.cpp +index 885044d2aa..d4e382cfa4 100644 +--- a/src/system/kernel/arch/riscv64/arch_int.cpp ++++ b/src/system/kernel/arch/riscv64/arch_int.cpp +@@ -8,24 +8,430 @@ + + + #include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include + ++#include ++ ++ ++__attribute__ ((aligned (16))) char sMStack[64*1024]; ++ ++ ++extern "C" void MVec(); ++extern "C" void MVecS(); ++extern "C" void SVec(); ++extern "C" void SVecU(); ++ ++ ++//#pragma mark debug output ++ ++void ++WriteMode(int mode) ++{ ++ switch (mode) { ++ case modeU: dprintf("u"); break; ++ case modeS: dprintf("s"); break; ++ case modeM: dprintf("m"); break; ++ default: dprintf("%d", mode); ++ } ++} ++ ++ ++void ++WriteModeSet(uint32_t val) ++{ ++ bool first = true; ++ dprintf("{"); ++ for (int i = 0; i < 32; i++) { ++ if (((1LL << i) & val) != 0) { ++ if (first) first = false; else dprintf(", "); ++ WriteMode(i); ++ } ++ } ++ dprintf("}"); ++} ++ ++ ++void ++WriteMstatus(uint64_t val) ++{ ++ MstatusReg status(val); ++ dprintf("("); ++ dprintf("ie: "); WriteModeSet(status.ie); ++ dprintf(", pie: "); WriteModeSet(status.pie); ++ dprintf(", spp: "); WriteMode(status.spp); ++ dprintf(", mpp: "); WriteMode(status.mpp); ++ dprintf(", sum: %d", (int)status.sum); ++ dprintf(")"); ++} ++ ++ ++void ++WriteSstatus(uint64_t val) ++{ ++ SstatusReg status(val); ++ dprintf("("); ++ dprintf("ie: "); WriteModeSet(status.ie); ++ dprintf(", pie: "); WriteModeSet(status.pie); ++ dprintf(", spp: "); WriteMode(status.spp); ++ dprintf(", sum: %d", (int)status.sum); ++ dprintf(")"); ++} ++ ++ ++void ++WriteInterrupt(uint64_t val) ++{ ++ switch (val) { ++ case 0 + modeU: dprintf("uSoft"); break; ++ case 0 + modeS: dprintf("sSoft"); break; ++ case 0 + modeM: dprintf("mSoft"); break; ++ case 4 + modeU: dprintf("uTimer"); break; ++ case 4 + modeS: dprintf("sTimer"); break; ++ case 4 + modeM: dprintf("mTimer"); break; ++ case 8 + modeU: dprintf("uExtern"); break; ++ case 8 + modeS: dprintf("sExtern"); break; ++ case 8 + modeM: dprintf("mExtern"); break; ++ default: dprintf("%" B_PRId64, val); ++ } ++} ++ ++ ++void ++WriteInterruptSet(uint64_t val) ++{ ++ bool first = true; ++ dprintf("{"); ++ for (int i = 0; i < 64; i++) { ++ if (((1LL << i) & val) != 0) { ++ if (first) first = false; else dprintf(", "); ++ WriteInterrupt(i); ++ } ++ } ++ dprintf("}"); ++} ++ ++ ++void ++WriteCause(uint64_t cause) ++{ ++ if ((cause & causeInterrupt) == 0) { ++ dprintf("exception "); ++ switch (cause) { ++ case causeExecMisalign: dprintf("execMisalign"); break; ++ case causeExecAccessFault: dprintf("execAccessFault"); break; ++ case causeIllegalInst: dprintf("illegalInst"); break; ++ case causeBreakpoint: dprintf("breakpoint"); break; ++ case causeLoadMisalign: dprintf("loadMisalign"); break; ++ case causeLoadAccessFault: dprintf("loadAccessFault"); break; ++ case causeStoreMisalign: dprintf("storeMisalign"); break; ++ case causeStoreAccessFault: dprintf("storeAccessFault"); break; ++ case causeUEcall: dprintf("uEcall"); break; ++ case causeSEcall: dprintf("sEcall"); break; ++ case causeMEcall: dprintf("mEcall"); break; ++ case causeExecPageFault: dprintf("execPageFault"); break; ++ case causeLoadPageFault: dprintf("loadPageFault"); break; ++ case causeStorePageFault: dprintf("storePageFault"); break; ++ default: dprintf("%" B_PRId64, cause); ++ } ++ } else { ++ dprintf("interrupt "); WriteInterrupt(cause & ~causeInterrupt); ++ } ++} ++ ++ ++void ++WriteTrapInfo() ++{ ++ dprintf("STrap("); WriteCause(Scause()); dprintf(")\n"); ++ dprintf(" sstatus: "); WriteSstatus(Sstatus()); dprintf("\n"); ++ dprintf(" sie: "); WriteInterruptSet(Sie()); dprintf("\n"); ++ dprintf(" sip: "); WriteInterruptSet(Sip()); dprintf("\n"); ++ dprintf(" stval: "); WritePC(Stval()); dprintf("\n"); ++ dprintf(" tp: 0x%" B_PRIxADDR "(%s)\n", Tp(), ++ thread_get_current_thread()->name); ++ //dprintf(" stval: 0x%" B_PRIx64 "\n", Stval()); ++} ++ ++ ++//#pragma mark - ++ ++extern "C" void ++MTrap(iframe* frame) ++{ ++ uint64 cause = Mcause(); ++/* ++ HtifOutString("+MTrap("); WriteCause(Mcause()); HtifOutString(")\n"); ++ dprintf(" mstatus: "); WriteMstatus(Mstatus()); dprintf("\n"); ++ dprintf(" mie: "); WriteInterruptSet(Mie()); dprintf("\n"); ++ dprintf(" mip: "); WriteInterruptSet(Mip()); dprintf("\n"); ++ dprintf(" sie: "); WriteInterruptSet(Sie()); dprintf("\n"); ++ dprintf(" sip: "); WriteInterruptSet(Sip()); dprintf("\n"); ++ dprintf(" mscratch: 0x%" B_PRIxADDR "\n", Mscratch()); ++ DoStackTrace(Fp(), 0); ++*/ ++ switch (cause) { ++ case causeMEcall: ++ case causeSEcall: { ++ frame->epc += 4; ++ uint64 op = frame->a0; ++ switch (op) { ++ case switchToSmodeMmodeSyscall: { ++ HtifOutString("switchToSmodeMmodeSyscall()\n"); ++ MstatusReg status(Mstatus()); ++ status.mpp = modeS; ++ SetMedeleg( ++ 0xffff & ~((1 << causeMEcall) | (1 << causeSEcall))); ++ SetMideleg(0xffff & ~(1 << mTimerInt)); ++ SetMstatus(status.val); ++ dprintf("modeM stack: 0x%" B_PRIxADDR ", 0x%" B_PRIxADDR ++ "\n", (addr_t)sMStack, ++ (addr_t)(sMStack + sizeof(sMStack))); ++ SetMscratch((addr_t)(sMStack + sizeof(sMStack))); ++ SetMtvec((uint64)MVecS); ++ frame->a0 = B_OK; ++ return; ++ } ++ case setTimerMmodeSyscall: { ++ // HtifOutString("setTimerMmodeSyscall()\n"); ++ bool enable = frame->a1 != 0; ++ SetSip(Sip() & ~(1 << sTimerInt)); ++ if (!enable) { ++ SetMie(Mie() & ~(1 << mTimerInt)); ++ } else { ++ gClintRegs->mTimeCmp[0] = frame->a2; ++ SetMie(Mie() | (1 << mTimerInt)); ++ } ++ frame->a0 = B_OK; ++ return; ++ } ++ default: ++ frame->a0 = B_NOT_SUPPORTED; ++ return; ++ } ++ break; ++ } ++ case causeInterrupt + mTimerInt: { ++ disable_interrupts(); ++ SetMie(Mie() & ~(1 << mTimerInt)); ++ SetMip(Mip() | (1 << sTimerInt)); ++ return; ++ } ++ } ++ HtifOutString("unhandled MTrap\n"); ++ // DoStackTrace(Fp(), 0); ++ HtifShutdown(); ++} ++ ++ ++static void ++SendSignal(debug_exception_type type, uint32 signalNumber, int32 signalCode, ++ addr_t signalAddress = 0, int32 signalError = B_ERROR) ++{ ++ if (SstatusReg(Sstatus()).spp == modeU) { ++ struct sigaction action; ++ Thread* thread = thread_get_current_thread(); ++ ++ WriteTrapInfo(); ++ DoStackTrace(Fp(), 0); ++ ++ enable_interrupts(); ++ ++ // If the thread has a signal handler for the signal, we simply send it ++ // the signal. Otherwise we notify the user debugger first. ++ if ((sigaction(signalNumber, NULL, &action) == 0 ++ && action.sa_handler != SIG_DFL ++ && action.sa_handler != SIG_IGN) ++ || user_debug_exception_occurred(type, signalNumber)) { ++ Signal signal(signalNumber, signalCode, signalError, ++ thread->team->id); ++ signal.SetAddress((void*)signalAddress); ++ send_signal_to_thread(thread, signal, 0); ++ } ++ } else { ++ WriteTrapInfo(); ++ panic("Unexpected exception occurred in kernel mode!"); ++ } ++} ++ ++ ++static void ++AfterInterrupt() ++{ ++ Thread* thread = thread_get_current_thread(); ++ cpu_status state = disable_interrupts(); ++ if (thread->cpu->invoke_scheduler) { ++ SpinLocker schedulerLocker(thread->scheduler_lock); ++ scheduler_reschedule(B_THREAD_READY); ++ schedulerLocker.Unlock(); ++ restore_interrupts(state); ++ } else if (thread->post_interrupt_callback != NULL) { ++ void (*callback)(void*) = thread->post_interrupt_callback; ++ void* data = thread->post_interrupt_data; ++ ++ thread->post_interrupt_callback = NULL; ++ thread->post_interrupt_data = NULL; ++ ++ restore_interrupts(state); ++ ++ callback(data); ++ } ++} ++ ++ ++extern "C" void ++STrap(iframe* frame) ++{ ++ // dprintf("STrap("); WriteCause(Scause()); dprintf(")\n"); ++ if (SstatusReg(Sstatus()).spp == modeU) { ++ thread_get_current_thread()->arch_info.userFrame = frame; ++ thread_at_kernel_entry(system_time()); ++ } ++ struct ScopeExit { ++ ~ScopeExit() ++ { ++ if (SstatusReg(Sstatus()).spp == modeU) { ++ if ((thread_get_current_thread()->flags ++ & (THREAD_FLAGS_SIGNALS_PENDING ++ | THREAD_FLAGS_DEBUG_THREAD ++ | THREAD_FLAGS_TRAP_FOR_CORE_DUMP)) != 0) { ++ enable_interrupts(); ++ thread_at_kernel_exit(); ++ } else { ++ thread_at_kernel_exit_no_signals(); ++ } ++ thread_get_current_thread()->arch_info.userFrame = NULL; ++ } ++ } ++ } scopeExit; ++ ++ uint64 cause = Scause(); ++ switch (cause) { ++ case causeIllegalInst: ++ return SendSignal(B_INVALID_OPCODE_EXCEPTION, SIGILL, ILL_ILLOPC, ++ frame->epc); ++ case causeExecMisalign: ++ case causeLoadMisalign: ++ case causeStoreMisalign: ++ return SendSignal(B_ALIGNMENT_EXCEPTION, SIGBUS, BUS_ADRALN, ++ Stval()); ++ // case causeBreakpoint: ++ // case causeExecAccessFault: ++ // case causeLoadAccessFault: ++ // case causeStoreAccessFault: ++ case causeExecPageFault: ++ case causeLoadPageFault: ++ case causeStorePageFault: { ++ uint64 stval = Stval(); ++ SstatusReg status(Sstatus()); ++ addr_t newIP = 0; ++ enable_interrupts(); ++ vm_page_fault(stval, frame->epc, cause == causeStorePageFault, ++ cause == causeExecPageFault, status.spp == modeU, &newIP); ++ if (newIP != 0) ++ frame->epc = newIP; ++ SetSstatus(status.val); ++ return; ++ } ++ case causeInterrupt + sTimerInt: { ++ SstatusReg status(Sstatus()); ++ timer_interrupt(); ++ AfterInterrupt(); ++ SetSstatus(status.val); ++ return; ++ } ++ case causeInterrupt + sExternInt: { ++ SstatusReg status(Sstatus()); ++ uint64 irq = gPlicRegs->contexts[0].claimAndComplete; ++ int_io_interrupt_handler(irq, true); ++ gPlicRegs->contexts[0].claimAndComplete = irq; ++ AfterInterrupt(); ++ SetSstatus(status.val); ++ return; ++ } ++ case causeUEcall: { ++ frame->epc += 4; // skip ecall ++ uint64 syscall = frame->t0; ++ uint64 args[20]; ++ if (syscall < (uint64)kSyscallCount) { ++ uint32 argCnt = kExtendedSyscallInfos[syscall].parameter_count; ++ memcpy(&args[0], &frame->a0, ++ sizeof(uint64)*std::min(argCnt, 8)); ++ if (argCnt > 8) { ++ if (status_t res = user_memcpy(&args[8], (void*)frame->sp, ++ sizeof(uint64)*(argCnt - 8)) < B_OK) { ++ dprintf("can't read syscall arguments on user " ++ "stack\n"); ++ frame->a0 = res; ++ return; ++ } ++ } ++ } ++/* ++ switch (syscall) { ++ case SYSCALL_READ_PORT_ETC: ++ case SYSCALL_WRITE_PORT_ETC: ++ WriteTrapInfo(); ++ DoStackTrace(Fp(), 0); ++ break; ++ } ++*/ ++ // dprintf("syscall: %s\n", kExtendedSyscallInfos[syscall].name); ++ SstatusReg status(Sstatus()); ++ enable_interrupts(); ++ uint64 returnValue = 0; ++ syscall_dispatcher(syscall, (void*)args, &returnValue); ++ frame->a0 = returnValue; ++ SetSstatus(status.val); ++ return; ++ } ++ } ++ WriteTrapInfo(); ++ panic("unhandled STrap"); ++} ++ ++ ++//#pragma mark - + + status_t +-arch_int_init(kernel_args *args) ++arch_int_init(kernel_args* args) + { ++ SetMtvec((uint64)MVec); ++ SetStvec((uint64)SVec); ++ MstatusReg mstatus(Mstatus()); ++ mstatus.ie = 1 << modeM; ++ mstatus.fs = extStatusInitial; // enable FPU ++ mstatus.xs = extStatusOff; ++ SetMstatus(mstatus.val); ++ MSyscall(switchToSmodeMmodeSyscall); ++ SetSie(Sie() | (1 << sTimerInt) | (1 << sExternInt)); ++ ++ // TODO: read from FDT ++ reserve_io_interrupt_vectors(32, 0, INTERRUPT_TYPE_IRQ); ++ + return B_OK; + } + + + status_t +-arch_int_init_post_vm(kernel_args *args) ++arch_int_init_post_vm(kernel_args* args) + { + return B_OK; + } + + + status_t +-arch_int_init_post_device_manager(struct kernel_args *args) ++arch_int_init_post_device_manager(struct kernel_args* args) + { + return B_OK; + } +@@ -41,16 +447,21 @@ arch_int_init_io(kernel_args* args) + void + arch_int_enable_io_interrupt(int irq) + { ++ // not implemented by TinyEMU ++ gPlicRegs->enable[0][irq / 32] |= 1 << (irq % 32); + } + + + void + arch_int_disable_io_interrupt(int irq) + { ++ // not implemented by TinyEMU ++ gPlicRegs->enable[0][irq / 32] &= ~(1 << (irq % 32)); + } + + + void + arch_int_assign_to_cpu(int32 irq, int32 cpu) + { ++ // SMP not yet supported + } +diff --git a/src/system/kernel/arch/riscv64/arch_traps.S b/src/system/kernel/arch/riscv64/arch_traps.S +new file mode 100644 +index 0000000000..a8e7fe9b6b +--- /dev/null ++++ b/src/system/kernel/arch/riscv64/arch_traps.S +@@ -0,0 +1,116 @@ ++/* ++ * Copyright 2021, Haiku, Inc. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++ ++#include "arch_traps.h" ++ ++ ++.globl MVec ++.type MVec, @function ++.align 4 ++MVec: ++ PushTrapFrame ++ sd fp, 2*8(sp) ++ csrr t0, mepc ++ sd t0, 31*8(sp) ++ ++ mv a0, sp ++ call MTrap ++ ++ ld t0, 31*8(sp) ++ csrw mepc, t0 ++ PopTrapFrame ++ mret ++.size MVec, .-MVec ++ ++ ++.globl MVecS ++.type MVecS, @function ++.align 4 ++MVecS: ++ csrrw sp, mscratch, sp ++ ++ PushTrapFrame ++ ++ csrr t0, mscratch ++ sd t0, 2*8(sp) # save supervisor SP ++ csrw mscratch, fp ++ ++ csrr t0, mepc ++ sd t0, 31*8(sp) ++ ++ la t0, MVec ++ csrw mtvec, t0 ++ ++ mv a0, sp ++ call MTrap ++ ++ la t0, MVecS ++ csrw mtvec, t0 ++ ++ ld t0, 31*8(sp) ++ csrw mepc, t0 ++ PopTrapFrame ++ mret ++.size MVecS, .-MVecS ++ ++ ++.globl SVec ++.type SVec, @function ++.align 4 ++SVec: ++ PushTrapFrame ++ sd fp, 2*8(sp) ++ csrr t0, sepc ++ sd t0, 31*8(sp) ++ ++ mv a0, sp ++ call STrap ++ ++ ld t0, 31*8(sp) ++ csrw sepc, t0 ++ PopTrapFrame ++ sret ++.size SVec, .-SVec ++ ++ ++.globl SVecU ++.type SVecU, @function ++.align 4 ++SVecU: ++ csrrw t0, sscratch, t0 # t0: &arch_thread ++ ld tp, 0*8(t0) # tp = arch_thread.thread ++ ld t0, (1 + 13)*8(t0) # t0 = arch_thread.context.sp ++ sd sp, 2*8 - 256(t0) # save user SP ++ mv sp, t0 # switch to kernel stack ++ csrr t0, sscratch ++ ++ PushTrapFrame ++ ++ csrr t0, sepc ++ sd t0, 31*8(sp) ++ ++ la t0, SVec ++ csrw stvec, t0 ++ ++ mv a0, sp ++ call STrap ++ ++.globl SVecURet ++.type SVecURet, @function ++SVecURet: ++ call RestoreUserRegs ++ ++ csrr t0, sscratch ++ sd fp, (1 + 13)*8(t0) # arch_thread.context.sp = fp ++ ++ la t0, SVecU ++ csrw stvec, t0 ++ ++ ld t0, 31*8(sp) ++ csrw sepc, t0 ++ PopTrapFrame ++ sret ++.size SVecU, .-SVecU +-- +2.30.2 + diff --git a/patchset-hrev55144/0039-kernel-arch-debug-implement-for-riscv64.patch b/patchset-hrev55144/0039-kernel-arch-debug-implement-for-riscv64.patch new file mode 100644 index 0000000..e80b945 --- /dev/null +++ b/patchset-hrev55144/0039-kernel-arch-debug-implement-for-riscv64.patch @@ -0,0 +1,331 @@ +From 83245d47dd84e3dee213f4bd2d3f3308f5820728 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 22:26:13 +0900 +Subject: kernel/arch/debug: implement for riscv64 + +Change-Id: Iab5cc9ef4059f968bca03683592d1ec1818a26a2 +--- + .../private/kernel/arch/riscv64/arch_debug.h | 9 + + src/system/kernel/arch/riscv64/arch_debug.cpp | 230 +++++++++++++++++- + .../arch/riscv64/arch_debug_console.cpp | 4 +- + 3 files changed, 239 insertions(+), 4 deletions(-) + +diff --git a/headers/private/kernel/arch/riscv64/arch_debug.h b/headers/private/kernel/arch/riscv64/arch_debug.h +index 57bd5b8e45..69830bfd65 100644 +--- a/headers/private/kernel/arch/riscv64/arch_debug.h ++++ b/headers/private/kernel/arch/riscv64/arch_debug.h +@@ -9,8 +9,17 @@ + #include + + ++struct kernel_args; ++ + struct arch_debug_registers { + }; + + ++void WritePC(addr_t pc); ++void DoStackTrace(addr_t fp, addr_t pc); ++void WriteTrapInfo(); ++ ++status_t arch_debug_init_early(kernel_args *args); ++ ++ + #endif // _KERNEL_ARCH_RISCV64_DEBUG_H +diff --git a/src/system/kernel/arch/riscv64/arch_debug.cpp b/src/system/kernel/arch/riscv64/arch_debug.cpp +index 07a48ef0da..880fd93851 100644 +--- a/src/system/kernel/arch/riscv64/arch_debug.cpp ++++ b/src/system/kernel/arch/riscv64/arch_debug.cpp +@@ -8,11 +8,224 @@ + + + #include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++ ++kernel_args *sKernelArgs; ++bool sInitCalled = false; ++ ++ ++static void ++WriteImage(preloaded_image* _image) ++{ ++ preloaded_elf64_image* image = (preloaded_elf64_image*)_image; ++ dprintf("image \"%s\"\n", (char*)image->name); ++ dprintf( ++ " text: 0x%" B_PRIxADDR " - 0x%" B_PRIxADDR ", %" B_PRIdSSIZE "\n", ++ image->text_region.start, ++ image->text_region.start + image->text_region.size, ++ image->text_region.delta ++ ); ++ dprintf( ++ " data: 0x%" B_PRIxADDR " - 0x%" B_PRIxADDR ", %" B_PRIdSSIZE "\n", ++ image->data_region.start, ++ image->data_region.start + image->data_region.size, ++ image->data_region.delta ++ ); ++} ++ ++ ++static void ++WriteImages() ++{ ++ WriteImage(sKernelArgs->kernel_image); ++ for (preloaded_image* image = sKernelArgs->preloaded_images; image != NULL; ++ image = image->next) ++ WriteImage(image); ++} ++ ++ ++static bool ++AddressInImage(preloaded_image* _image, addr_t adr) ++{ ++ preloaded_elf64_image* image = (preloaded_elf64_image*)_image; ++ if ( ++ adr >= image->text_region.start && ++ adr < image->text_region.start + image->text_region.size ++ ) return true; ++ if ( ++ adr >= image->data_region.start && ++ adr < image->data_region.start + image->data_region.size ++ ) return true; ++ return false; ++} ++ ++ ++static bool ++SymbolAt(preloaded_image* _image, addr_t adr, const char **name, ssize_t *ofs) ++{ ++ preloaded_elf64_image* image = (preloaded_elf64_image*)_image; ++ adr -= image->text_region.delta; ++ for (uint32 i = 0; i < image->num_debug_symbols; i++) { ++ Elf64_Sym& sym = image->debug_symbols[i]; ++ if (sym.st_shndx != STN_UNDEF && adr >= sym.st_value ++ && adr < sym.st_value + sym.st_size) { ++ if (name != NULL) ++ *name = &image->debug_string_table[sym.st_name]; ++ if (ofs != NULL) ++ *ofs = adr - sym.st_value; ++ return true; ++ } ++ } ++ return false; ++} ++ ++ ++static preloaded_image* ++FindImage(addr_t adr) ++{ ++ if (AddressInImage(sKernelArgs->kernel_image, adr)) ++ return sKernelArgs->kernel_image; ++ ++ for (preloaded_image* image = sKernelArgs->preloaded_images; image != NULL; ++ image = image->next) ++ if (AddressInImage(image, adr)) ++ return image; ++ ++ return NULL; ++} ++ ++ ++static VMArea* ++FindArea(addr_t adr) ++{ ++ VMAddressSpacePutter addrSpace; ++ addrSpace.SetTo(VMAddressSpace::GetCurrent()); ++ return addrSpace->LookupArea(adr); ++} ++ ++ ++static status_t ++lookup_symbol(Thread* thread, addr_t address, addr_t* _baseAddress, ++ const char** _symbolName, const char** _imageName, bool* _exactMatch) ++{ ++ status_t status = B_ENTRY_NOT_FOUND; ++ ++ if (IS_KERNEL_ADDRESS(address)) { ++ // a kernel symbol ++ status = elf_debug_lookup_symbol_address(address, _baseAddress, ++ _symbolName, _imageName, _exactMatch); ++ } else if (thread != NULL && thread->team != NULL) { ++ // try a lookup using the userland runtime loader structures ++ status = elf_debug_lookup_user_symbol_address(thread->team, address, ++ _baseAddress, _symbolName, _imageName, _exactMatch); ++ ++ if (status != B_OK) { ++ // try to locate the image in the images loaded into user space ++ status = image_debug_lookup_user_symbol_address(thread->team, ++ address, _baseAddress, _symbolName, _imageName, _exactMatch); ++ } ++ } ++ ++ return status; ++} ++ ++ ++void ++WritePCBoot(addr_t pc) ++{ ++ preloaded_image* image = FindImage(pc); ++ if (image != NULL) { ++ const char *name; ++ ssize_t ofs; ++ if (SymbolAt(image, pc, &name, &ofs)) { ++ dprintf("<%s> %s + %" B_PRIdSSIZE, (char*)image->name, name, ofs); ++ return; ++ } ++ dprintf("<%s> 0x%" B_PRIxADDR, (char*)image->name, ++ pc - ((preloaded_elf64_image*)image)->text_region.delta); ++ return; ++ } ++/* ++ VMArea* area = FindArea(pc); ++ if (area != NULL) { ++ dprintf("<%s> 0x%" B_PRIxADDR, area->name, pc - area->Base()); ++ return; ++ } ++*/ ++ dprintf("0x%" B_PRIxADDR, pc); ++} ++ ++ ++void ++WritePC(addr_t pc) ++{ ++ // dprintf("0x%" B_PRIxADDR " ", pc); ++ if (!sInitCalled) { ++ WritePCBoot(pc); return; ++ } ++ ++ addr_t baseAddress; ++ const char* symbolName; ++ const char* imageName; ++ bool exactMatch; ++ if (lookup_symbol(thread_get_current_thread(), pc, &baseAddress, ++ &symbolName, &imageName, &exactMatch) >= B_OK) { ++ if (symbolName != NULL) { ++ dprintf("<%s> %s + %" B_PRIdSSIZE, imageName, symbolName, ++ pc - baseAddress); ++ return; ++ } ++ dprintf("<%s> 0x%" B_PRIxADDR, imageName, pc - baseAddress); ++ return; ++ } ++ ++ VMArea* area = FindArea(pc); ++ if (area != NULL) { ++ dprintf("<%s> 0x%" B_PRIxADDR, area->name, pc - area->Base()); ++ return; ++ } ++ ++ dprintf("0x%" B_PRIxADDR, pc); ++} ++ ++ ++void ++DoStackTrace(addr_t fp, addr_t pc) ++{ ++ dprintf("Stack:\n"); ++ dprintf("FP: 0x%" B_PRIxADDR, fp); ++ if (pc != 0) { ++ dprintf(", PC: "); WritePC(pc); ++ } ++ dprintf("\n"); ++ while (fp != 0) { ++ if (user_memcpy(&pc, (uint64*)fp - 1, sizeof(pc)) < B_OK) break; ++ if (user_memcpy(&fp, (uint64*)fp - 2, sizeof(pc)) < B_OK) break; ++ dprintf("FP: 0x%" B_PRIxADDR, fp); ++ dprintf(", PC: "); WritePC(pc - 1); ++ dprintf("\n"); ++ } ++} ++ ++ ++static int ++stack_trace(int argc, char **argv) ++{ ++ DoStackTrace(Fp(), 0); ++ return 0; ++} + + + void + arch_debug_stack_trace(void) + { ++ DoStackTrace(Fp(), 0); + } + + +@@ -41,6 +254,7 @@ void + arch_debug_call_with_fault_handler(cpu_ent* cpu, jmp_buf jumpBuffer, + void (*function)(void*), void* parameter) + { ++ function(parameter); + } + + +@@ -99,14 +313,24 @@ arch_debug_unset_current_thread(void) + } + + ++status_t ++arch_debug_init_early(kernel_args *args) ++{ ++ dprintf("arch_debug_init_early()\n"); ++ sKernelArgs = args; ++ WriteImages(); ++ return B_OK; ++} ++ ++ + status_t + arch_debug_init(kernel_args *args) + { +-#if 0 ++ sInitCalled = true; ++ + add_debugger_command("where", &stack_trace, "Same as \"sc\""); + add_debugger_command("bt", &stack_trace, "Same as \"sc\" (as in gdb)"); + add_debugger_command("sc", &stack_trace, "Stack crawl for current thread"); +-#endif + +- return B_NO_ERROR; ++ return B_OK; + } +diff --git a/src/system/kernel/arch/riscv64/arch_debug_console.cpp b/src/system/kernel/arch/riscv64/arch_debug_console.cpp +index 32eaa295fe..6f82d72773 100644 +--- a/src/system/kernel/arch/riscv64/arch_debug_console.cpp ++++ b/src/system/kernel/arch/riscv64/arch_debug_console.cpp +@@ -11,6 +11,7 @@ + #include + #include + #include ++#include + + #include + +@@ -59,6 +60,7 @@ arch_debug_serial_getchar(void) + void + arch_debug_serial_putchar(const char c) + { ++ HtifOutChar(c); + } + + +@@ -75,7 +77,7 @@ arch_debug_serial_puts(const char *s) + void + arch_debug_serial_early_boot_message(const char *string) + { +- // this function will only be called in fatal situations ++ arch_debug_serial_puts(string); + } + + +-- +2.30.2 + diff --git a/patchset-hrev55144/0040-kernel-arch-elf-implement-for-riscv64.patch b/patchset-hrev55144/0040-kernel-arch-elf-implement-for-riscv64.patch new file mode 100644 index 0000000..7e53b36 --- /dev/null +++ b/patchset-hrev55144/0040-kernel-arch-elf-implement-for-riscv64.patch @@ -0,0 +1,33 @@ +From 915ce583eb3140d9d16e15a405290679f0829a53 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 22:30:08 +0900 +Subject: kernel/arch/elf: implement for riscv64 + +Change-Id: I919ee4883af780f48385a53e5768eba35dde6423 +--- + src/system/kernel/arch/riscv64/arch_elf.cpp | 2 ++ + 1 file changed, 2 insertions(+) + +diff --git a/src/system/kernel/arch/riscv64/arch_elf.cpp b/src/system/kernel/arch/riscv64/arch_elf.cpp +index 763d6a1d03..78dc01444f 100644 +--- a/src/system/kernel/arch/riscv64/arch_elf.cpp ++++ b/src/system/kernel/arch/riscv64/arch_elf.cpp +@@ -94,6 +94,7 @@ arch_elf_relocate_rela(struct elf_image_info *image, + case R_RISCV_NONE: + continue; + case R_RISCV_64: ++ case R_RISCV_JUMP_SLOT: + relocValue = symAddr + rel[i].r_addend; + break; + case R_RISCV_RELATIVE: +@@ -113,6 +114,7 @@ arch_elf_relocate_rela(struct elf_image_info *image, + rel[i].r_offset); + return B_BAD_ADDRESS; + } ++ *(Elf64_Addr *)relocAddr = relocValue; + #endif + } + +-- +2.30.2 + diff --git a/patchset-hrev55144/0041-kernel-add-RISC-V-HTIF-code.patch b/patchset-hrev55144/0041-kernel-add-RISC-V-HTIF-code.patch new file mode 100644 index 0000000..3b5f2ba --- /dev/null +++ b/patchset-hrev55144/0041-kernel-add-RISC-V-HTIF-code.patch @@ -0,0 +1,82 @@ +From 5c4fdb630eb50e5922071ab0c4388d74dfe5ed4c Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 22:37:10 +0900 +Subject: kernel: add RISC-V HTIF code + +Change-Id: I83251bb4586b4f752c97741f62a96d2f6f842377 +--- + src/system/kernel/arch/riscv64/Htif.cpp | 49 +++++++++++++++++++++++++ + src/system/kernel/arch/riscv64/Jamfile | 1 + + 2 files changed, 50 insertions(+) + create mode 100644 src/system/kernel/arch/riscv64/Htif.cpp + +diff --git a/src/system/kernel/arch/riscv64/Htif.cpp b/src/system/kernel/arch/riscv64/Htif.cpp +new file mode 100644 +index 0000000000..c4063b1150 +--- /dev/null ++++ b/src/system/kernel/arch/riscv64/Htif.cpp +@@ -0,0 +1,49 @@ ++/* ++ * Copyright 2021, Haiku, Inc. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++ ++#include ++ ++ ++uint64 ++HtifCmd(uint32 device, uint8 cmd, uint32 arg) ++{ ++ uint64 htifTohost = ((uint64)device << 56) ++ + ((uint64)cmd << 48) + arg; ++ gHtifRegs->toHostLo = htifTohost % ((uint64)1 << 32); ++ gHtifRegs->toHostHi = htifTohost / ((uint64)1 << 32); ++ return (uint64)gHtifRegs->fromHostLo ++ + ((uint64)gHtifRegs->fromHostHi << 32); ++} ++ ++ ++void ++HtifShutdown() ++{ ++ HtifCmd(0, 0, 1); ++} ++ ++ ++void ++HtifOutChar(char ch) ++{ ++ HtifCmd(1, 1, ch); ++} ++ ++ ++void ++HtifOutString(const char *str) ++{ ++ for (; *str != '\0'; str++) ++ HtifOutChar(*str); ++} ++ ++ ++void ++HtifOutString(const char *str, size_t len) ++{ ++ for (; len > 0; str++, len--) ++ HtifOutChar(*str); ++} +diff --git a/src/system/kernel/arch/riscv64/Jamfile b/src/system/kernel/arch/riscv64/Jamfile +index 0371ebb210..de684e5081 100644 +--- a/src/system/kernel/arch/riscv64/Jamfile ++++ b/src/system/kernel/arch/riscv64/Jamfile +@@ -22,6 +22,7 @@ KernelMergeObject kernel_arch_riscv64.o : + arch_vm.cpp + arch_vm_translation_map.cpp + RISCV64VMTranslationMap.cpp ++ Htif.cpp + : + $(TARGET_KERNEL_PIC_CCFLAGS) -Wno-unused + : +-- +2.30.2 + diff --git a/patchset-hrev55144/0042-kernel-arch-commpage-implement-for-riscv64.patch b/patchset-hrev55144/0042-kernel-arch-commpage-implement-for-riscv64.patch new file mode 100644 index 0000000..9741c30 --- /dev/null +++ b/patchset-hrev55144/0042-kernel-arch-commpage-implement-for-riscv64.patch @@ -0,0 +1,133 @@ +From abc73bcd45c1bfbd62ef66d8a0350081d703a215 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 22:42:23 +0900 +Subject: kernel/arch/commpage: implement for riscv64 + +Change-Id: Id7f495896a08a237db85dcedd1174e4c181e373d +--- + .../system/arch/riscv64/arch_commpage_defs.h | 6 +- + src/system/kernel/arch/riscv64/arch_asm.S | 8 +++ + .../kernel/arch/riscv64/arch_commpage.cpp | 62 ++++++++++++++++++- + 3 files changed, 71 insertions(+), 5 deletions(-) + +diff --git a/headers/private/system/arch/riscv64/arch_commpage_defs.h b/headers/private/system/arch/riscv64/arch_commpage_defs.h +index 18f187011f..044a61f419 100644 +--- a/headers/private/system/arch/riscv64/arch_commpage_defs.h ++++ b/headers/private/system/arch/riscv64/arch_commpage_defs.h +@@ -10,9 +10,7 @@ + # error Must not be included directly. Include instead! + #endif + +-/* +-#define COMMPAGE_ENTRY_RISCV64_SYSCALL (COMMPAGE_ENTRY_FIRST_ARCH_SPECIFIC + 0) +-#define COMMPAGE_ENTRY_RISCV64_MEMCPY (COMMPAGE_ENTRY_FIRST_ARCH_SPECIFIC + 1) +-*/ ++#define COMMPAGE_ENTRY_RISCV64_SIGNAL_HANDLER (COMMPAGE_ENTRY_FIRST_ARCH_SPECIFIC + 0) ++#define COMMPAGE_ENTRY_RISCV64_SIGNAL_THREAD_EXIT (COMMPAGE_ENTRY_FIRST_ARCH_SPECIFIC + 1) + + #endif /* _SYSTEM_ARCH_RISCV64_COMMPAGE_DEFS_H */ +diff --git a/src/system/kernel/arch/riscv64/arch_asm.S b/src/system/kernel/arch/riscv64/arch_asm.S +index f4d9d6284a..c88b47b880 100644 +--- a/src/system/kernel/arch/riscv64/arch_asm.S ++++ b/src/system/kernel/arch/riscv64/arch_asm.S +@@ -5,6 +5,7 @@ + + + #include ++#include "syscall_numbers.h" + + + .text +@@ -160,3 +161,10 @@ FUNCTION(arch_longjmp_iframe): + mv sp, a0 + call SVecURet + FUNCTION_END(arch_longjmp_iframe) ++ ++ ++FUNCTION(arch_user_thread_exit): ++ li t0, SYSCALL_EXIT_THREAD ++ ecall ++ ret ++FUNCTION_END(arch_user_thread_exit) +diff --git a/src/system/kernel/arch/riscv64/arch_commpage.cpp b/src/system/kernel/arch/riscv64/arch_commpage.cpp +index b7378611ab..e6dd6e45d7 100644 +--- a/src/system/kernel/arch/riscv64/arch_commpage.cpp ++++ b/src/system/kernel/arch/riscv64/arch_commpage.cpp +@@ -13,6 +13,59 @@ + #include + #include + ++#include "syscall_numbers.h" ++ ++ ++extern "C" void arch_user_thread_exit(); ++ ++typedef void (*SignalHandler)(int signal, siginfo_t* signalInfo, ++ ucontext_t* ctx); ++ ++extern "C" void arch_user_signal_handler(signal_frame_data* data) ++{ ++ SignalHandler handler = (SignalHandler)data->handler; ++ handler(data->info.si_signo, &data->info, &data->context); ++ ++ #define TO_STRING_LITERAL_HELPER(number) #number ++ #define TO_STRING_LITERAL(number) TO_STRING_LITERAL_HELPER(number) ++ ++ // _kern_restore_signal_frame(data) ++ asm volatile( ++ "mv a0, %0;" ++ "li t0, " TO_STRING_LITERAL(SYSCALL_RESTORE_SIGNAL_FRAME) ";" ++ "ecall;" ++ :: "r"(data) ++ ); ++ ++ #undef TO_STRING_LITERAL_HELPER ++ #undef TO_STRING_LITERAL ++} ++ ++ ++static void ++register_commpage_function(const char* functionName, int32 commpageIndex, ++ const char* commpageSymbolName, addr_t expectedAddress) ++{ ++ // get address and size of function ++ elf_symbol_info symbolInfo; ++ if (elf_lookup_kernel_symbol(functionName, &symbolInfo) ++ != B_OK) { ++ panic("register_commpage_function(): Failed to find " ++ "signal frame function \"%s\"!", functionName); ++ } ++ ++ ASSERT(expectedAddress == symbolInfo.address); ++ ++ // fill in the commpage table entry ++ addr_t position = fill_commpage_entry(commpageIndex, ++ (void*)symbolInfo.address, symbolInfo.size); ++ ++ // add symbol to the commpage image ++ image_id image = get_commpage_image(); ++ elf_add_memory_image_symbol(image, commpageSymbolName, position, ++ symbolInfo.size, B_SYMBOL_TYPE_TEXT); ++} ++ + + status_t + arch_commpage_init(void) +@@ -24,6 +77,13 @@ arch_commpage_init(void) + status_t + arch_commpage_init_post_cpus(void) + { ++ register_commpage_function("arch_user_signal_handler", ++ COMMPAGE_ENTRY_RISCV64_SIGNAL_HANDLER, "commpage_signal_handler", ++ (addr_t)&arch_user_signal_handler); ++ ++ register_commpage_function("arch_user_thread_exit", ++ COMMPAGE_ENTRY_RISCV64_SIGNAL_THREAD_EXIT, "commpage_thread_exit", ++ (addr_t)&arch_user_thread_exit); ++ + return B_OK; + } +- +-- +2.30.2 + diff --git a/patchset-hrev55144/0043-kernel-arch-cpu-implement-for-riscv64.patch b/patchset-hrev55144/0043-kernel-arch-cpu-implement-for-riscv64.patch new file mode 100644 index 0000000..6a8a2c9 --- /dev/null +++ b/patchset-hrev55144/0043-kernel-arch-cpu-implement-for-riscv64.patch @@ -0,0 +1,113 @@ +From c61049ff2ee9ed8b51909c44cb9202793e491067 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 22:51:53 +0900 +Subject: kernel/arch/cpu: implement for riscv64 + +Change-Id: Ib4dd636f9ebb62931f77c809185ea810485d801e +--- + .../private/kernel/arch/riscv64/arch_atomic.h | 11 +++++----- + .../private/kernel/arch/riscv64/arch_cpu.h | 20 ++++++++++++++++--- + src/system/kernel/arch/riscv64/arch_cpu.cpp | 2 ++ + 3 files changed, 24 insertions(+), 9 deletions(-) + +diff --git a/headers/private/kernel/arch/riscv64/arch_atomic.h b/headers/private/kernel/arch/riscv64/arch_atomic.h +index 5ecc1e8749..8a10e814ed 100644 +--- a/headers/private/kernel/arch/riscv64/arch_atomic.h ++++ b/headers/private/kernel/arch/riscv64/arch_atomic.h +@@ -12,24 +12,23 @@ + static inline void + memory_read_barrier_inline(void) + { +- asm volatile ("nop;" : : : "memory"); +-#warning RISCV64: check memory_read_barrier_inline (FNOP ?) ++ // TODO: investigate reparate read/write barriers ++ __sync_synchronize(); + } + + + static inline void + memory_write_barrier_inline(void) + { +- asm volatile ("nop;" : : : "memory"); +-#warning RISCV64: check memory_write_barrier_inline (FNOP ?) ++ // TODO: investigate reparate read/write barriers ++ __sync_synchronize(); + } + + + static inline void + memory_full_barrier_inline(void) + { +- asm volatile ("nop;" : : : "memory"); +-#warning RISCV64: check memory_full_barrier_inline (FNOP ?) ++ __sync_synchronize(); + } + + +diff --git a/headers/private/kernel/arch/riscv64/arch_cpu.h b/headers/private/kernel/arch/riscv64/arch_cpu.h +index e5efc8ac63..5b1414898c 100644 +--- a/headers/private/kernel/arch/riscv64/arch_cpu.h ++++ b/headers/private/kernel/arch/riscv64/arch_cpu.h +@@ -8,6 +8,7 @@ + + + #include ++#include + #include + + +@@ -15,8 +16,21 @@ + #define CACHE_LINE_SIZE 64 + + +-#define set_ac() +-#define clear_ac() ++inline void set_ac() ++{ ++ return; ++ SstatusReg sstatus(Sstatus()); ++ sstatus.sum = 1; ++ SetSstatus(sstatus.val); ++} ++ ++inline void clear_ac() ++{ ++ return; ++ SstatusReg sstatus(Sstatus()); ++ sstatus.sum = 0; ++ SetSstatus(sstatus.val); ++} + + + typedef struct arch_cpu_info { +@@ -39,7 +53,7 @@ arch_cpu_pause(void) + static inline void + arch_cpu_idle(void) + { +- // TODO: CPU idle call ++ Wfi(); + } + + +diff --git a/src/system/kernel/arch/riscv64/arch_cpu.cpp b/src/system/kernel/arch/riscv64/arch_cpu.cpp +index c8fa731a13..0bd867a9a6 100644 +--- a/src/system/kernel/arch/riscv64/arch_cpu.cpp ++++ b/src/system/kernel/arch/riscv64/arch_cpu.cpp +@@ -10,6 +10,7 @@ + #include + #include + #include ++#include + + + status_t +@@ -95,5 +96,6 @@ arch_cpu_user_TLB_invalidate(void) + status_t + arch_cpu_shutdown(bool reboot) + { ++ HtifShutdown(); + return B_ERROR; + } +-- +2.30.2 + diff --git a/patchset-hrev55144/0044-kernel-arch-user_debugger-implement-for-risv64.patch b/patchset-hrev55144/0044-kernel-arch-user_debugger-implement-for-risv64.patch new file mode 100644 index 0000000..fcf3bf5 --- /dev/null +++ b/patchset-hrev55144/0044-kernel-arch-user_debugger-implement-for-risv64.patch @@ -0,0 +1,136 @@ +From 22842db03688f3d1fc13cc8dce5ca513bbfaab1a Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 22:55:15 +0900 +Subject: kernel/arch/user_debugger: implement for risv64 + +Change-Id: I9cdf7a6a5b66cdd83133485f98067ce9a5fb819d +--- + headers/os/arch/riscv64/arch_debugger.h | 6 +- + .../arch/riscv64/arch_user_debugger.cpp | 81 ++++++++++++++++++- + 2 files changed, 84 insertions(+), 3 deletions(-) + +diff --git a/headers/os/arch/riscv64/arch_debugger.h b/headers/os/arch/riscv64/arch_debugger.h +index f4b8fb07eb..71191fb004 100644 +--- a/headers/os/arch/riscv64/arch_debugger.h ++++ b/headers/os/arch/riscv64/arch_debugger.h +@@ -6,9 +6,11 @@ + #define _ARCH_RISCV64_DEBUGGER_H + + +-//#warning RISCV64: fixme + struct riscv64_debug_cpu_state { +- uint32 dummy; ++ uint64 x[31]; ++ uint64 pc; ++ double f[32]; ++ uint64 fcsr; + } __attribute__((aligned(8))); + + +diff --git a/src/system/kernel/arch/riscv64/arch_user_debugger.cpp b/src/system/kernel/arch/riscv64/arch_user_debugger.cpp +index 08023893e8..0178d93051 100644 +--- a/src/system/kernel/arch/riscv64/arch_user_debugger.cpp ++++ b/src/system/kernel/arch/riscv64/arch_user_debugger.cpp +@@ -45,19 +45,98 @@ arch_update_thread_single_step() + void + arch_set_debug_cpu_state(const debug_cpu_state *cpuState) + { ++ iframe* frame = thread_get_current_thread()->arch_info.userFrame; ++ ++ frame->ra = cpuState->x[ 0]; ++ frame->sp = cpuState->x[ 1]; ++ frame->gp = cpuState->x[ 2]; ++ frame->tp = cpuState->x[ 3]; ++ frame->t0 = cpuState->x[ 4]; ++ frame->t1 = cpuState->x[ 5]; ++ frame->t2 = cpuState->x[ 6]; ++ frame->fp = cpuState->x[ 7]; ++ frame->s1 = cpuState->x[ 8]; ++ frame->a0 = cpuState->x[ 9]; ++ frame->a1 = cpuState->x[10]; ++ frame->a2 = cpuState->x[11]; ++ frame->a3 = cpuState->x[12]; ++ frame->a4 = cpuState->x[13]; ++ frame->a5 = cpuState->x[14]; ++ frame->a6 = cpuState->x[15]; ++ frame->a7 = cpuState->x[16]; ++ frame->s2 = cpuState->x[17]; ++ frame->s3 = cpuState->x[18]; ++ frame->s4 = cpuState->x[19]; ++ frame->s5 = cpuState->x[20]; ++ frame->s6 = cpuState->x[21]; ++ frame->s7 = cpuState->x[22]; ++ frame->s8 = cpuState->x[23]; ++ frame->s9 = cpuState->x[24]; ++ frame->s10 = cpuState->x[25]; ++ frame->s11 = cpuState->x[26]; ++ frame->t3 = cpuState->x[27]; ++ frame->t4 = cpuState->x[28]; ++ frame->t5 = cpuState->x[29]; ++ frame->t6 = cpuState->x[30]; ++ frame->epc = cpuState->pc; ++ restore_fpu((fpu_context*)&cpuState->f[0]); + } + + + void + arch_get_debug_cpu_state(debug_cpu_state *cpuState) + { ++ arch_get_thread_debug_cpu_state(thread_get_current_thread(), cpuState); + } + + + status_t + arch_get_thread_debug_cpu_state(Thread* thread, debug_cpu_state* cpuState) + { +- return B_UNSUPPORTED; ++ iframe* frame = thread->arch_info.userFrame; ++ if (frame == NULL) ++ return B_BAD_DATA; ++ ++ cpuState->x[ 0] = frame->ra; ++ cpuState->x[ 1] = frame->sp; ++ cpuState->x[ 2] = frame->gp; ++ cpuState->x[ 3] = frame->tp; ++ cpuState->x[ 4] = frame->t0; ++ cpuState->x[ 5] = frame->t1; ++ cpuState->x[ 6] = frame->t2; ++ cpuState->x[ 7] = frame->fp; ++ cpuState->x[ 8] = frame->s1; ++ cpuState->x[ 9] = frame->a0; ++ cpuState->x[10] = frame->a1; ++ cpuState->x[11] = frame->a2; ++ cpuState->x[12] = frame->a3; ++ cpuState->x[13] = frame->a4; ++ cpuState->x[14] = frame->a5; ++ cpuState->x[15] = frame->a6; ++ cpuState->x[16] = frame->a7; ++ cpuState->x[17] = frame->s2; ++ cpuState->x[18] = frame->s3; ++ cpuState->x[19] = frame->s4; ++ cpuState->x[20] = frame->s5; ++ cpuState->x[21] = frame->s6; ++ cpuState->x[22] = frame->s7; ++ cpuState->x[23] = frame->s8; ++ cpuState->x[24] = frame->s9; ++ cpuState->x[25] = frame->s10; ++ cpuState->x[26] = frame->s11; ++ cpuState->x[27] = frame->t3; ++ cpuState->x[28] = frame->t4; ++ cpuState->x[29] = frame->t5; ++ cpuState->x[30] = frame->t6; ++ cpuState->pc = frame->epc; ++ // TODO: don't assume that kernel code don't use FPU ++ if (thread == thread_get_current_thread()) ++ save_fpu((fpu_context*)&cpuState->f[0]); ++ else ++ memcpy(&cpuState->f[0], &thread->arch_info.fpuContext, ++ sizeof(thread->arch_info.fpuContext)); ++ ++ return B_OK; + } + + +-- +2.30.2 + diff --git a/patchset-hrev55144/0045-kernel-arch-platform-implement-for-riscv64.patch b/patchset-hrev55144/0045-kernel-arch-platform-implement-for-riscv64.patch new file mode 100644 index 0000000..4234541 --- /dev/null +++ b/patchset-hrev55144/0045-kernel-arch-platform-implement-for-riscv64.patch @@ -0,0 +1,34 @@ +From 14be46cfb37c517e64a86aadfcc575ba2a64796f Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 22:57:41 +0900 +Subject: kernel/arch/platform: implement for riscv64 + +Change-Id: Id1839ef39d927e6a2017c8b8ac3482d9eeb00fa1 +--- + src/system/kernel/arch/riscv64/arch_platform.cpp | 5 +++++ + 1 file changed, 5 insertions(+) + +diff --git a/src/system/kernel/arch/riscv64/arch_platform.cpp b/src/system/kernel/arch/riscv64/arch_platform.cpp +index 30a2394057..aae0d4b6fd 100644 +--- a/src/system/kernel/arch/riscv64/arch_platform.cpp ++++ b/src/system/kernel/arch/riscv64/arch_platform.cpp +@@ -4,11 +4,16 @@ + + + #include ++#include ++ ++ ++void* gFDT = NULL; + + + status_t + arch_platform_init(struct kernel_args *kernelArgs) + { ++ gFDT = kernelArgs->arch_args.fdt; + return B_OK; + } + +-- +2.30.2 + diff --git a/patchset-hrev55144/0046-kernel-arch-system_info-implement-for-riscv64.patch b/patchset-hrev55144/0046-kernel-arch-system_info-implement-for-riscv64.patch new file mode 100644 index 0000000..3aa687a --- /dev/null +++ b/patchset-hrev55144/0046-kernel-arch-system_info-implement-for-riscv64.patch @@ -0,0 +1,49 @@ +From ceb5da75cb69ef000581e13b93027f8a8b2fcffe Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 22:59:07 +0900 +Subject: kernel/arch/system_info: implement for riscv64 + +Change-Id: Ifa66859a7f87cd821fe50ca7d26e08472adcf279 +--- + .../kernel/arch/riscv64/arch_system_info.cpp | 19 +++++++++++++++++++ + 1 file changed, 19 insertions(+) + +diff --git a/src/system/kernel/arch/riscv64/arch_system_info.cpp b/src/system/kernel/arch/riscv64/arch_system_info.cpp +index 6fb0f54290..86fbc293b2 100644 +--- a/src/system/kernel/arch/riscv64/arch_system_info.cpp ++++ b/src/system/kernel/arch/riscv64/arch_system_info.cpp +@@ -24,12 +24,31 @@ static uint16 sCPURevision; + void + arch_fill_topology_node(cpu_topology_node_info* node, int32 cpu) + { ++ switch (node->type) { ++ case B_TOPOLOGY_ROOT: ++ node->data.root.platform = B_CPU_RISC_V; ++ break; ++ ++ case B_TOPOLOGY_PACKAGE: ++ node->data.package.vendor = B_CPU_VENDOR_UNKNOWN; ++ node->data.package.cache_line_size = CACHE_LINE_SIZE; ++ break; ++ ++ case B_TOPOLOGY_CORE: ++ node->data.core.model = 0; ++ node->data.core.default_frequency = sCPUClockFrequency; ++ break; ++ ++ default: ++ break; ++ } + } + + + status_t + arch_system_info_init(struct kernel_args *args) + { ++ sCPUClockFrequency = 1000000000; + return B_OK; + } + +-- +2.30.2 + diff --git a/patchset-hrev55144/0047-kernel-arch-timer-implement-for-riscv64.patch b/patchset-hrev55144/0047-kernel-arch-timer-implement-for-riscv64.patch new file mode 100644 index 0000000..745e725 --- /dev/null +++ b/patchset-hrev55144/0047-kernel-arch-timer-implement-for-riscv64.patch @@ -0,0 +1,48 @@ +From b58cbac35b31665a6ec1d8aaeeb2299bd769dbfb Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 23:02:03 +0900 +Subject: kernel/arch/timer: implement for riscv64 + +Change-Id: Ia854b0048a86b1427e975f482325ed4d4df1a12a +--- + src/system/kernel/arch/riscv64/arch_timer.cpp | 8 ++++++-- + 1 file changed, 6 insertions(+), 2 deletions(-) + +diff --git a/src/system/kernel/arch/riscv64/arch_timer.cpp b/src/system/kernel/arch/riscv64/arch_timer.cpp +index fc5193b4a4..33f8014fad 100644 +--- a/src/system/kernel/arch/riscv64/arch_timer.cpp ++++ b/src/system/kernel/arch/riscv64/arch_timer.cpp +@@ -11,17 +11,22 @@ + #include + #include + #include ++#include ++#include ++#include + + + void + arch_timer_set_hardware_timer(bigtime_t timeout) + { ++ MSyscall(setTimerMmodeSyscall, true, gClintRegs->mTime + timeout/10); + } + + + void + arch_timer_clear_hardware_timer() + { ++ MSyscall(setTimerMmodeSyscall, false); + } + + +@@ -35,6 +40,5 @@ arch_init_timer(kernel_args *args) + bigtime_t + system_time(void) + { +- // TODO +- return 0; ++ return CpuTime(); + } +-- +2.30.2 + diff --git a/patchset-hrev55144/0048-kernel-non-arch-changes-for-riscv64.patch b/patchset-hrev55144/0048-kernel-non-arch-changes-for-riscv64.patch new file mode 100644 index 0000000..029828b --- /dev/null +++ b/patchset-hrev55144/0048-kernel-non-arch-changes-for-riscv64.patch @@ -0,0 +1,200 @@ +From 3ca01a48c039e0233dea272d3349ccc336fbd67f Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 23:04:21 +0900 +Subject: kernel: non-arch changes for riscv64 + +Change-Id: I641a400ad54a25717e2178ca1df4d5c5f2941c7d +--- + src/system/kernel/debug/debug.cpp | 1 + + src/system/kernel/debug/user_debugger.cpp | 2 ++ + src/system/kernel/device_manager/device_manager.cpp | 5 ++++- + src/system/kernel/elf.cpp | 3 ++- + src/system/kernel/fs/vfs_boot.cpp | 2 +- + src/system/kernel/main.cpp | 6 ++++-- + src/system/kernel/team.cpp | 1 + + src/system/kernel/vm/vm.cpp | 6 ++++++ + 8 files changed, 21 insertions(+), 5 deletions(-) + +diff --git a/src/system/kernel/debug/debug.cpp b/src/system/kernel/debug/debug.cpp +index 7f7bb54324..59842a6eba 100644 +--- a/src/system/kernel/debug/debug.cpp ++++ b/src/system/kernel/debug/debug.cpp +@@ -1671,6 +1671,7 @@ debug_init(kernel_args* args) + + debug_paranoia_init(); + arch_debug_console_init(args); ++ arch_debug_init_early(args); + } + + +diff --git a/src/system/kernel/debug/user_debugger.cpp b/src/system/kernel/debug/user_debugger.cpp +index 2553c073cd..c94196f3c1 100644 +--- a/src/system/kernel/debug/user_debugger.cpp ++++ b/src/system/kernel/debug/user_debugger.cpp +@@ -2782,6 +2782,8 @@ ensure_debugger_installed() + void + _user_debugger(const char *userMessage) + { ++ WriteTrapInfo(); ++ DoStackTrace(Fp(), 0); + // install the default debugger, if there is none yet + status_t error = ensure_debugger_installed(); + if (error != B_OK) { +diff --git a/src/system/kernel/device_manager/device_manager.cpp b/src/system/kernel/device_manager/device_manager.cpp +index ab6dbe85da..765d9dcb4a 100644 +--- a/src/system/kernel/device_manager/device_manager.cpp ++++ b/src/system/kernel/device_manager/device_manager.cpp +@@ -1717,7 +1717,6 @@ device_node::_GetNextDriverPath(void*& cookie, KPath& _path) + _AddPath(*stack, "busses/pci"); + _AddPath(*stack, "bus_managers"); + } else if (!generic) { +- _AddPath(*stack, "busses", "virtio"); + _AddPath(*stack, "drivers"); + } else { + // For generic drivers, we only allow busses when the +@@ -1731,6 +1730,7 @@ device_node::_GetNextDriverPath(void*& cookie, KPath& _path) + _AddPath(*stack, "drivers", sGenericContextPath); + _AddPath(*stack, "busses/i2c"); + _AddPath(*stack, "busses/scsi"); ++ _AddPath(*stack, "busses", "virtio"); + _AddPath(*stack, "busses/random"); + } + break; +@@ -1792,6 +1792,7 @@ device_node::_FindBestDriver(const char* path, driver_module_info*& bestDriver, + void* list = open_module_list_etc(path, "driver_v1"); + driver_module_info* driver; + while (_GetNextDriver(list, driver) == B_OK) { ++ dprintf(" candidate: \"%s\"\n", driver->info.name); + if (previous != NULL && driver == previous->DriverModule()) { + put_module(driver->info.name); + continue; +@@ -1856,6 +1857,7 @@ device_node::_AlwaysRegisterDynamic() + status_t + device_node::_RegisterDynamic(device_node* previous) + { ++ dprintf("%p._RegisterDynamic()\n", this); + // If this is not a bus, we don't have to scan it + if (find_attr(this, B_DEVICE_BUS, false, B_STRING_TYPE) == NULL) + return B_OK; +@@ -1875,6 +1877,7 @@ device_node::_RegisterDynamic(device_node* previous) + void* cookie = NULL; + + while (_GetNextDriverPath(cookie, path) == B_OK) { ++ dprintf(" candidate: \"%s\"\n", path.Path()); + _FindBestDriver(path.Path(), bestDriver, bestSupport, previous); + } + +diff --git a/src/system/kernel/elf.cpp b/src/system/kernel/elf.cpp +index 4706f4c3db..74c527b0b5 100644 +--- a/src/system/kernel/elf.cpp ++++ b/src/system/kernel/elf.cpp +@@ -177,11 +177,12 @@ register_elf_image(struct elf_image_info *image) + static struct elf_image_info * + find_image_at_address(addr_t address) + { ++/* + #if KDEBUG + if (!debug_debugger_running()) + ASSERT_LOCKED_MUTEX(&sImageMutex); + #endif +- ++*/ + ImageHash::Iterator iterator(sImagesHash); + + // get image that may contain the address +diff --git a/src/system/kernel/fs/vfs_boot.cpp b/src/system/kernel/fs/vfs_boot.cpp +index 45e7fb785a..7748e47601 100644 +--- a/src/system/kernel/fs/vfs_boot.cpp ++++ b/src/system/kernel/fs/vfs_boot.cpp +@@ -478,7 +478,7 @@ vfs_mount_boot_file_system(kernel_args* args) + panic("get_boot_partitions failed!"); + } + if (partitions.IsEmpty()) { +- panic("did not find any boot partitions! @! syslog | tail 15"); ++ panic("did not find any boot partitions! @! dm_tree"); + } + + dev_t bootDevice = -1; +diff --git a/src/system/kernel/main.cpp b/src/system/kernel/main.cpp +index f4b948c9f4..a3fdb1ac6f 100644 +--- a/src/system/kernel/main.cpp ++++ b/src/system/kernel/main.cpp +@@ -64,7 +64,7 @@ + #include "vm/VMAnonymousCache.h" + + +-//#define TRACE_BOOT ++#define TRACE_BOOT + #ifdef TRACE_BOOT + # define TRACE(x...) dprintf("INIT: " x) + #else +@@ -97,6 +97,8 @@ non_boot_cpu_init(void* args, int currentCPU) + extern "C" int + _start(kernel_args *bootKernelArgs, int currentCPU) + { ++ debug_early_boot_message("Kernel entry point\n"); ++ + if (bootKernelArgs->version == CURRENT_KERNEL_ARGS_VERSION + && bootKernelArgs->kernel_args_size == kernel_args_size_v1) { + sKernelArgs.ucode_data = NULL; +@@ -372,7 +374,7 @@ main2(void* /*unused*/) + // The boot splash screen is the last user of the kernel args. + // Note: don't confuse the kernel_args structure (which is never freed) + // with the kernel args ranges it contains (and which are freed here). +- vm_free_kernel_args(&sKernelArgs); ++ // vm_free_kernel_args(&sKernelArgs); + + // start the init process + { +diff --git a/src/system/kernel/team.cpp b/src/system/kernel/team.cpp +index 51421eb595..9f17b31029 100644 +--- a/src/system/kernel/team.cpp ++++ b/src/system/kernel/team.cpp +@@ -1650,6 +1650,7 @@ team_create_thread_start_internal(void* args) + strerror(commPageArea))); + return commPageArea; + } ++ dprintf("clone_commpage_area: %p\n", team->commpage_address); + + // Register commpage image + image_id commPageImage = get_commpage_image(); +diff --git a/src/system/kernel/vm/vm.cpp b/src/system/kernel/vm/vm.cpp +index bb5fe6719a..c95f8ddb1f 100644 +--- a/src/system/kernel/vm/vm.cpp ++++ b/src/system/kernel/vm/vm.cpp +@@ -52,6 +52,7 @@ + #include + #include + #include ++#include + + #include "VMAddressSpaceLocking.h" + #include "VMAnonymousCache.h" +@@ -3953,6 +3954,7 @@ static void + unreserve_boot_loader_ranges(kernel_args* args) + { + TRACE(("unreserve_boot_loader_ranges()\n")); ++ return; // !!! + + for (uint32 i = 0; i < args->num_virtual_allocated_ranges; i++) { + vm_unreserve_address_range(VMAddressSpace::KernelID(), +@@ -4427,12 +4429,16 @@ vm_page_fault(addr_t address, addr_t faultAddress, bool isWrite, bool isExecute, + // modify the IP on the interrupt frame or whatever to return + // to this address + *newIP = reinterpret_cast(thread->fault_handler); ++ dprintf("*newIP = 0x%" B_PRIxADDR "\n", *newIP); + } else { ++ WriteTrapInfo(); + // unhandled page fault in the kernel + panic("vm_page_fault: unhandled page fault in kernel space at " + "0x%lx, ip 0x%lx\n", address, faultAddress); + } + } else { ++ WriteTrapInfo(); ++ DoStackTrace(Fp(), 0); + Thread* thread = thread_get_current_thread(); + + #ifdef TRACE_FAULTS +-- +2.30.2 + diff --git a/patchset-hrev55144/0049-libdebug-add-riscv64-support.patch b/patchset-hrev55144/0049-libdebug-add-riscv64-support.patch new file mode 100644 index 0000000..5839544 --- /dev/null +++ b/patchset-hrev55144/0049-libdebug-add-riscv64-support.patch @@ -0,0 +1,57 @@ +From 21d992b6abf5ee313cda91f03358b4de0e472599 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 23:07:20 +0900 +Subject: libdebug: add riscv64 support + +Change-Id: I9d9d1697bc67d2ab674f2fbe0dbf3a37ead58595 +--- + src/kits/debug/arch/riscv64/arch_debug_support.cpp | 12 +++--------- + 1 file changed, 3 insertions(+), 9 deletions(-) + +diff --git a/src/kits/debug/arch/riscv64/arch_debug_support.cpp b/src/kits/debug/arch/riscv64/arch_debug_support.cpp +index 136b0e4e2d..21293d135a 100644 +--- a/src/kits/debug/arch/riscv64/arch_debug_support.cpp ++++ b/src/kits/debug/arch/riscv64/arch_debug_support.cpp +@@ -20,17 +20,14 @@ status_t + arch_debug_get_instruction_pointer(debug_context *context, thread_id thread, + void **ip, void **stackFrameAddress) + { +- #warning TODO RISCV64 get instruction pointer +- #if 0 + // get the CPU state + debug_cpu_state cpuState; + status_t error = debug_get_cpu_state(context, thread, NULL, &cpuState); + if (error != B_OK) + return error; + +- *ip = (void*)cpuState.rip; +- *stackFrameAddress = (void*)cpuState.rbp; +- #endif ++ *ip = (void*)cpuState.pc; ++ *stackFrameAddress = (void*)cpuState.x[7]; + + return B_OK; + } +@@ -40,10 +37,8 @@ status_t + arch_debug_get_stack_frame(debug_context *context, void *stackFrameAddress, + debug_stack_frame_info *stackFrameInfo) + { +- #warning TODO RISCV64 get stack frame +- #if 0 + stack_frame stackFrame; +- ssize_t bytesRead = debug_read_memory(context, stackFrameAddress, ++ ssize_t bytesRead = debug_read_memory(context, (uint8*)stackFrameAddress - sizeof(stackFrame), + &stackFrame, sizeof(stackFrame)); + if (bytesRead < B_OK) + return bytesRead; +@@ -53,7 +48,6 @@ arch_debug_get_stack_frame(debug_context *context, void *stackFrameAddress, + stackFrameInfo->frame = stackFrameAddress; + stackFrameInfo->parent_frame = stackFrame.previous; + stackFrameInfo->return_address = stackFrame.return_address; +- #endif + + return B_OK; + } +-- +2.30.2 + diff --git a/patchset-hrev55144/0050-add-image-files-for-riscv64.patch b/patchset-hrev55144/0050-add-image-files-for-riscv64.patch new file mode 100644 index 0000000..cd49375 --- /dev/null +++ b/patchset-hrev55144/0050-add-image-files-for-riscv64.patch @@ -0,0 +1,93 @@ +From fc9d3f47f4b532bcedf90e39912d22fea528473e Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 23:10:55 +0900 +Subject: add image files for riscv64 + +Change-Id: I5141de4e0bfcb44c5368dfafdf68ebf06ca5fb93 +--- + build/jam/images/definitions/minimum | 9 +++++---- + build/jam/packages/Haiku | 8 +++++--- + 2 files changed, 10 insertions(+), 7 deletions(-) + +diff --git a/build/jam/images/definitions/minimum b/build/jam/images/definitions/minimum +index 52d78a3a0d..c32164f56c 100644 +--- a/build/jam/images/definitions/minimum ++++ b/build/jam/images/definitions/minimum +@@ -143,9 +143,9 @@ SYSTEM_NETWORK_PROTOCOLS = + ; + + SYSTEM_ADD_ONS_ACCELERANTS = [ FFilterByBuildFeatures +- x86,x86_64 @{ ++ x86,x86_64,riscv64 @{ + vesa.accelerant +- }@ # x86,x86_64 ++ }@ # x86,x86_64,riscv64 + ] ; + + SYSTEM_ADD_ONS_TRANSLATORS = +@@ -171,9 +171,9 @@ SYSTEM_ADD_ONS_DRIVERS_AUDIO = ; + SYSTEM_ADD_ONS_DRIVERS_AUDIO_OLD = ; + + SYSTEM_ADD_ONS_DRIVERS_GRAPHICS = [ FFilterByBuildFeatures +- x86,x86_64 @{ ++ x86,x86_64,riscv64 @{ + vesa +- }@ # x86,x86_64 ++ }@ # x86,x86_64,riscv64 + ] ; + + SYSTEM_ADD_ONS_DRIVERS_MIDI = ; +@@ -217,6 +217,7 @@ SYSTEM_ADD_ONS_BUS_MANAGERS = [ FFilterByBuildFeatures + mmc + scsi + pci ps2@x86,x86_64 ++ fdt@riscv64 + random + usb + virtio +diff --git a/build/jam/packages/Haiku b/build/jam/packages/Haiku +index d5a3542d20..3e29e02899 100644 +--- a/build/jam/packages/Haiku ++++ b/build/jam/packages/Haiku +@@ -39,7 +39,7 @@ AddFilesToPackage add-ons kernel busses random : virtio_rng ; + AddFilesToPackage add-ons kernel busses scsi : ahci virtio_scsi ; + AddFilesToPackage add-ons kernel busses usb : uhci ohci ehci + xhci ; +-AddFilesToPackage add-ons kernel busses virtio : virtio_pci ; ++AddFilesToPackage add-ons kernel busses virtio : virtio_pci virtio_mmio ; + AddFilesToPackage add-ons kernel console : vga_text ; + AddFilesToPackage add-ons kernel debugger + : demangle disasm@x86,x86_64 hangman +@@ -68,6 +68,7 @@ AddNewDriversToPackage disk virtual : virtio_block ram_disk ; + AddNewDriversToPackage power : $(SYSTEM_ADD_ONS_DRIVERS_POWER) ; + AddNewDriversToPackage sensor : $(SYSTEM_ADD_ONS_DRIVERS_SENSOR) ; + AddNewDriversToPackage network : virtio_net ; ++AddNewDriversToPackage input : virtio_input ; + #AddNewDriversToPackage display : display_adapter@x86 ; + + # legacy drivers +@@ -194,10 +195,11 @@ AddBootModuleSymlinksToPackage + nvme_disk@x86,x86_64 + openpic@ppc + packagefs pci ++ fdt@riscv64 + scsi scsi_cd scsi_disk scsi_periph silicon_image_3112 highpoint_ide_pci + sdhci_pci + usb usb_disk ehci ohci uhci xhci +- virtio virtio_block virtio_pci virtio_scsi ++ virtio virtio_block virtio_pci virtio_mmio virtio_scsi + ; + + # add-ons +@@ -230,7 +232,7 @@ AddSymlinkToPackage add-ons Tracker + : /boot/system/apps/DiskUsage : DiskUsage ; + + AddFilesToPackage add-ons input_server devices +- : keyboard mouse tablet wacom ; ++ : keyboard mouse tablet wacom virtio ; + AddFilesToPackage add-ons input_server filters + : padblocker screen_saver shortcut_catcher switch_workspace ; + AddDirectoryToPackage add-ons input_server methods ; +-- +2.30.2 + diff --git a/patchset-hrev55144/0051-Revert-Interface-kit-rewrite-menu-logic-by-using-inp.patch b/patchset-hrev55144/0051-Revert-Interface-kit-rewrite-menu-logic-by-using-inp.patch new file mode 100644 index 0000000..c53ec32 --- /dev/null +++ b/patchset-hrev55144/0051-Revert-Interface-kit-rewrite-menu-logic-by-using-inp.patch @@ -0,0 +1,2011 @@ +From 2a041c65707fce007dfbcd3e435b7cca5a53ea3b Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sat, 15 May 2021 19:37:43 +0900 +Subject: Revert "Interface kit: rewrite menu logic by using input events" + +This reverts commit fb1392cc6d5fb067388e1239601d9b57838e3af4. + +Change-Id: I43781806cc52f670859c769cc8bd35370f5d7054 +--- + headers/os/interface/Menu.h | 27 +- + headers/private/interface/MenuPrivate.h | 35 +- + headers/private/interface/MenuWindow.h | 2 + + src/kits/interface/BMCPrivate.cpp | 6 - + src/kits/interface/Menu.cpp | 929 +++++++++++------------- + src/kits/interface/MenuBar.cpp | 140 +++- + src/kits/interface/MenuField.cpp | 7 +- + src/kits/interface/MenuPrivate.cpp | 6 +- + src/kits/interface/MenuWindow.cpp | 137 ++-- + src/kits/interface/PopUpMenu.cpp | 10 + + 10 files changed, 622 insertions(+), 677 deletions(-) + +diff --git a/headers/os/interface/Menu.h b/headers/os/interface/Menu.h +index 625287701f..017cbe0242 100644 +--- a/headers/os/interface/Menu.h ++++ b/headers/os/interface/Menu.h +@@ -17,7 +17,6 @@ class BMenuItem; + + + namespace BPrivate { +- class MenuTrackState; + class BMenuWindow; + class ExtraMenuData; + class TriggerList; +@@ -189,9 +188,10 @@ private: + BMenu& operator=(const BMenu& other); + + void _InitData(BMessage* archive); +- bool _Show(bool selectFirstItem = false); ++ bool _Show(bool selectFirstItem = false, ++ bool keyDown = false); + void _Hide(); +- BMenuItem* _Track(int32* action, int32 start = -1); ++ BMenuItem* _Track(int* action, long start = -1); + void _ScriptReceived(BMessage* message); + void _ItemScriptReceived(BMessage* message, + BMenuItem* item); +@@ -206,12 +206,14 @@ private: + BRect& navAreaRectAbove, + BRect& navAreaBelow); + +- bool _HitNavigationArea(BPoint position, BMenuItem* item); +- + void _UpdateStateOpenSelect(BMenuItem* item, + BPoint position, BRect& navAreaRectAbove, + BRect& navAreaBelow, +- bool isTimeout); ++ bigtime_t& selectedTime, ++ bigtime_t& navigationAreaTime); ++ void _UpdateStateClose(BMenuItem* item, ++ const BPoint& where, ++ const uint32& buttons); + + bool _AddItem(BMenuItem* item, int32 index); + bool _RemoveItems(int32 index, int32 count, +@@ -248,7 +250,8 @@ private: + void _Uninstall(); + void _SelectItem(BMenuItem* item, + bool showSubmenu = true, +- bool selectFirstItem = false); ++ bool selectFirstItem = false, ++ bool keyDown = false); + bool _SelectNextItem(BMenuItem* item, bool forward); + BMenuItem* _NextItem(BMenuItem* item, bool forward) const; + void _SetIgnoreHidden(bool ignoreHidden) +@@ -268,11 +271,13 @@ private: + uint32& trigger, + BPrivate::TriggerList& triggers); + void _UpdateWindowViewSize(const bool &updatePosition); +- bool _AddDynamicItems(); +- bool _OkToProceed(BMenuItem* item); ++ bool _AddDynamicItems(bool keyDown = false); ++ bool _OkToProceed(BMenuItem* item, ++ bool keyDown = false); + +- void _CallTrackingHook(); ++ bool _CustomTrackingWantsToQuit(); + ++ int _State(BMenuItem** _item = NULL) const; + void _InvokeItem(BMenuItem* item, bool now = false); + void _QuitTracking(bool onlyThis = true); + +@@ -286,7 +291,7 @@ private: + static uint32 sCommandKey; + static uint32 sMenuKey; + +- BPrivate::MenuTrackState* fTrackState; ++ BMenuItem* fChosenItem; + BList fItems; + BRect fPad; + BMenuItem* fSelected; +diff --git a/headers/private/interface/MenuPrivate.h b/headers/private/interface/MenuPrivate.h +index 64bf3f2359..4627b701ed 100644 +--- a/headers/private/interface/MenuPrivate.h ++++ b/headers/private/interface/MenuPrivate.h +@@ -11,18 +11,14 @@ + + + #include +-#include +-#include + +-#include + +- +-enum menu_track_command { +- MENU_TRACK_CMD_DONE +-}; +- +-enum { +- navigationAreaTimeoutMsg = 'nvat', ++enum menu_states { ++ MENU_STATE_TRACKING = 0, ++ MENU_STATE_TRACKING_SUBMENU = 1, ++ MENU_STATE_KEY_TO_SUBMENU = 2, ++ MENU_STATE_KEY_LEAVE_SUBMENU = 3, ++ MENU_STATE_CLOSED = 5 + }; + + +@@ -52,7 +48,7 @@ public: + const; + void SetItemMargins(float, float, float, float); + +- bool IsTracking() const; ++ int State(BMenuItem** item = NULL) const; + + void Install(BWindow* window); + void Uninstall(); +@@ -82,23 +78,6 @@ private: + + }; + +-struct MenuTrackState { +- thread_id trackThread; +- BLocker locker; +- bool quit; +- BMenu* rootMenu; +- BMenu* curMenu; +- BMenu* cursorMenu; // menu that holding pointer event mask +- BMenuItem* invokedItem; +- bool cursorInside, cursorObscured; +- BPoint clickPoint, enterPoint; +- BRect navAreaRectAbove; +- BRect navAreaRectBelow; +- bigtime_t selectedTime; +- bigtime_t navigationAreaTime; +- ObjectDeleter navigationAreaTimer; +-}; +- + }; // namespace BPrivate + + +diff --git a/headers/private/interface/MenuWindow.h b/headers/private/interface/MenuWindow.h +index c409bd4c54..eb1b943c9d 100644 +--- a/headers/private/interface/MenuWindow.h ++++ b/headers/private/interface/MenuWindow.h +@@ -38,10 +38,12 @@ public: + void SetSmallStep(float step); + void GetSteps(float* _smallStep, float* _largeStep) const; + bool HasScrollers() const; ++ bool CheckForScrolling(const BPoint& cursor); + bool TryScrollBy(const float& step); + bool TryScrollTo(const float& where); + + private: ++ bool _Scroll(const BPoint& cursor); + void _ScrollBy(const float& step); + + BMenu* fMenu; +diff --git a/src/kits/interface/BMCPrivate.cpp b/src/kits/interface/BMCPrivate.cpp +index 537cb00c33..6e6ca327e4 100644 +--- a/src/kits/interface/BMCPrivate.cpp ++++ b/src/kits/interface/BMCPrivate.cpp +@@ -21,8 +21,6 @@ + #include + #include + +-#include +- + + static const float kPopUpIndicatorWidth = 13.0f; + +@@ -78,10 +76,6 @@ _BMCFilter_::~_BMCFilter_() + filter_result + _BMCFilter_::Filter(BMessage* message, BHandler** handler) + { +- BPrivate::MenuPrivate menuPrivate(fMenuField->MenuBar()); +- if (menuPrivate.IsTracking()) +- return B_DISPATCH_MESSAGE; +- + if (message->what == B_MOUSE_DOWN) { + if (BView* view = dynamic_cast(*handler)) { + BPoint point; +diff --git a/src/kits/interface/Menu.cpp b/src/kits/interface/Menu.cpp +index 9a2464fa16..7e25525a68 100644 +--- a/src/kits/interface/Menu.cpp ++++ b/src/kits/interface/Menu.cpp +@@ -39,7 +39,6 @@ + #include + #include + #include +-#include + + #include + #include +@@ -54,8 +53,6 @@ + + #define USE_CACHED_MENUWINDOW 1 + +-#define SHOW_NAVIGATION_AREA 0 +- + using BPrivate::gSystemCatalog; + + #undef B_TRANSLATION_CONTEXT +@@ -230,7 +227,7 @@ struct BMenu::LayoutData { + BMenu::BMenu(const char* name, menu_layout layout) + : + BView(BRect(0, 0, 0, 0), name, 0, B_WILL_DRAW), +- fTrackState(NULL), ++ fChosenItem(NULL), + fSelected(NULL), + fCachedMenuWindow(NULL), + fSuper(NULL), +@@ -238,6 +235,7 @@ BMenu::BMenu(const char* name, menu_layout layout) + fAscent(-1.0f), + fDescent(-1.0f), + fFontHeight(-1.0f), ++ fState(MENU_STATE_CLOSED), + fLayout(layout), + fExtraRect(NULL), + fMaxContentWidth(0.0f), +@@ -266,7 +264,7 @@ BMenu::BMenu(const char* name, menu_layout layout) + BMenu::BMenu(const char* name, float width, float height) + : + BView(BRect(0.0f, 0.0f, 0.0f, 0.0f), name, 0, B_WILL_DRAW), +- fTrackState(NULL), ++ fChosenItem(NULL), + fPad(14.0f, 2.0f, 20.0f, 0.0f), + fSelected(NULL), + fCachedMenuWindow(NULL), +@@ -275,6 +273,7 @@ BMenu::BMenu(const char* name, float width, float height) + fAscent(-1.0f), + fDescent(-1.0f), + fFontHeight(-1.0f), ++ fState(0), + fLayout(B_ITEMS_IN_MATRIX), + fExtraRect(NULL), + fMaxContentWidth(0.0f), +@@ -300,7 +299,7 @@ BMenu::BMenu(const char* name, float width, float height) + BMenu::BMenu(BMessage* archive) + : + BView(archive), +- fTrackState(NULL), ++ fChosenItem(NULL), + fPad(14.0f, 2.0f, 20.0f, 0.0f), + fSelected(NULL), + fCachedMenuWindow(NULL), +@@ -309,6 +308,7 @@ BMenu::BMenu(BMessage* archive) + fAscent(-1.0f), + fDescent(-1.0f), + fFontHeight(-1.0f), ++ fState(MENU_STATE_CLOSED), + fLayout(B_ITEMS_IN_ROW), + fExtraRect(NULL), + fMaxContentWidth(0.0f), +@@ -402,7 +402,14 @@ BMenu::AttachedToWindow() + _GetOptionKey(sOptionKey); + _GetMenuKey(sMenuKey); + +- fAttachAborted = _AddDynamicItems(); ++ // The menu should be added to the menu hierarchy and made visible if: ++ // * the mouse is over the menu, ++ // * the user has requested the menu via the keyboard. ++ // So if we don't pass keydown in here, keyboard navigation breaks since ++ // fAttachAborted will return false if the mouse isn't over the menu ++ bool keyDown = Supermenu() != NULL ++ ? Supermenu()->fState == MENU_STATE_KEY_TO_SUBMENU : false; ++ fAttachAborted = _AddDynamicItems(keyDown); + + if (!fAttachAborted) { + _CacheFontInfo(); +@@ -443,43 +450,15 @@ BMenu::Draw(BRect updateRect) + + DrawBackground(updateRect); + DrawItems(updateRect); +- +- #if SHOW_NAVIGATION_AREA +- if (fTrackState != NULL) { +- BRect above, below; +- { +- AutoLocker locker(fTrackState->locker); +- above = ConvertFromScreen(fTrackState->navAreaRectAbove); +- below = ConvertFromScreen(fTrackState->navAreaRectBelow); +- } +- bool isLeft = above.left == 0; +- PushState(); +- SetDrawingMode(B_OP_ALPHA); +- SetHighColor(0xff, 0, 0, 0x66); +- if (!isLeft) { +- FillTriangle(above.LeftBottom(), above.RightTop(), above.RightBottom()); +- FillTriangle(below.LeftTop(), below.RightBottom(), above.RightTop()); +- } else { +- FillTriangle(above.RightBottom(), above.LeftTop(), above.LeftBottom()); +- FillTriangle(below.RightTop(), below.LeftBottom(), above.LeftTop()); +- } +- PopState(); +- } +- #endif + } + + +-const static bigtime_t kNavigationAreaTimeout = 1000000; +- + void + BMenu::MessageReceived(BMessage* message) + { + if (message->HasSpecifiers()) + return _ScriptReceived(message); + +- if (fTrackState == NULL) +- return BView::MessageReceived(message); +- + switch (message->what) { + case B_MOUSE_WHEEL_CHANGED: + { +@@ -506,159 +485,6 @@ BMenu::MessageReceived(BMessage* message) + break; + } + +- case B_MOUSE_DOWN: { +- printf("B_MOUSE_DOWN, _IsStickyMode: %d\n", _IsStickyMode()); +- BPoint where = B_ORIGIN; +- message->FindPoint("be:view_where", &where); +- { +- AutoLocker locker(fTrackState->locker); +- if (!fTrackState->cursorInside) { +- _QuitTracking(false); +- BView::MessageReceived(message); +- return; +- } +- } +- if (_IsStickyMode()) +- _SetStickyMode(false); +- +- _CallTrackingHook(); +- +- BView::MessageReceived(message); +- break; +- } +- +- case B_MOUSE_UP: { +- printf("B_MOUSE_UP, _IsStickyMode: %d\n", _IsStickyMode()); +- BPoint where = B_ORIGIN; +- message->FindPoint("be:view_where", &where); +- BMenuItem* item = _HitTestItems(where, B_ORIGIN); +- if ( +- !_IsStickyMode() || ( +- !(fExtraRect != NULL && fExtraRect->Contains(where)) && +- dynamic_cast(Window()) == NULL && +- (item == NULL || item->Submenu() == NULL) +- ) +- ) { +- if (item != NULL) _InvokeItem(item); +- _QuitTracking(false); +- } +- _CallTrackingHook(); +- BView::MessageReceived(message); +- break; +- } +- +- case B_MOUSE_MOVED: { +- BPoint where = B_ORIGIN; +- int32 buttons = 0; +- int32 transit = B_OUTSIDE_VIEW; +- +- message->FindPoint("be:view_where", &where); +- message->FindInt32("buttons", &buttons); +- message->FindInt32("be:transit", &transit); +- +- if (fTrackState == NULL) { +- BView::MessageReceived(message); +- return; +- } +- +- { +- AutoLocker locker(fTrackState->locker); +- +- BRect checkRect(-8, -8, 8, 8); +- checkRect.OffsetBy(fTrackState->clickPoint); +- +- if (_IsStickyMode() && !checkRect.Contains(ConvertToScreen(where))) { +- printf("outside of checkRect\n"); +- _SetStickyMode(false); +- } +- +- switch (transit) { +- case B_ENTERED_VIEW: +- fTrackState->cursorMenu = this; +- fTrackState->cursorMenu->SetEventMask(B_POINTER_EVENTS, 0); +- fTrackState->cursorInside = true; +- break; +- case B_EXITED_VIEW: +- if (fTrackState->cursorMenu == this) +- fTrackState->cursorInside = false; +- +- if ((fSelected != NULL) && (fSelected->Submenu() == NULL)) +- _SelectItem(NULL); +- +- break; +- } +- +- if (fTrackState->cursorMenu != this) +- SetEventMask(0, 0); +- } +- +- switch (transit) { +- case B_ENTERED_VIEW: +- case B_INSIDE_VIEW: { +- { +- AutoLocker locker(fTrackState->locker); +- if (fTrackState->cursorObscured) { +- if (transit == B_ENTERED_VIEW) { +- fTrackState->enterPoint = where; +- break; +- } +- if (fTrackState->enterPoint == where) +- break; +- +- fTrackState->cursorObscured = false; +- } +- } +- BMenuItem* oldSelected = fSelected; +- BMenuItem* item = _HitTestItems(where, B_ORIGIN); +- if (item == NULL) { +- if ((fSelected != NULL) && (fSelected->Submenu() == NULL)) +- _SelectItem(NULL); +- } else if (fSelected != item) { +- if (!_HitNavigationArea(where, item)) { +- fTrackState->navigationAreaTimer.Unset(); +- _SelectItem(item, true); +- } else { +- if (fTrackState->navigationAreaTimer.IsSet()) +- fTrackState->navigationAreaTimer.SetTo(new(std::nothrow) BMessageRunner(BMessenger(this), BMessage(navigationAreaTimeoutMsg), kNavigationAreaTimeout, 1)); +- } +- } +- { +- AutoLocker locker(fTrackState->locker); +- if (oldSelected != fSelected) +- fTrackState->curMenu = this; +- } +- break; +- } +- } +- +- _CallTrackingHook(); +- +- BView::MessageReceived(message); +- break; +- } +- +- case navigationAreaTimeoutMsg: { +- if (fTrackState->navigationAreaTimer.IsSet()) { +- fTrackState->navigationAreaTimer.Unset(); +- BPoint where; +- GetMouse(&where, NULL); +- BMenuItem* oldSelected = fSelected; +- BMenuItem* item = _HitTestItems(where, B_ORIGIN); +- if (item == NULL) { +- if ((fSelected != NULL) && (fSelected->Submenu() == NULL)) +- _SelectItem(NULL); +- } else +- _SelectItem(item, true); +- +- { +- AutoLocker locker(fTrackState->locker); +- if (oldSelected != fSelected) +- fTrackState->curMenu = this; +- } +- } +- break; +- } +- + default: + BView::MessageReceived(message); + break; +@@ -669,63 +495,64 @@ BMenu::MessageReceived(BMessage* message) + void + BMenu::KeyDown(const char* bytes, int32 numBytes) + { +- if (fTrackState == NULL) +- return; +- +- AutoLocker locker(fTrackState->locker); +- +- if (fTrackState->curMenu != this) { +- BMessenger messenger(fTrackState->curMenu); +- messenger.SendMessage(Window()->CurrentMessage()); +- return; +- } +- +- fTrackState->cursorObscured = true; +- be_app->ObscureCursor(); +- ++ // TODO: Test how it works on BeOS R5 and implement this correctly + switch (bytes[0]) { + case B_UP_ARROW: +- if (fLayout == B_ITEMS_IN_COLUMN) { ++ if (fLayout == B_ITEMS_IN_COLUMN) + _SelectNextItem(fSelected, false); +- } else if (fLayout == B_ITEMS_IN_ROW || fLayout == B_ITEMS_IN_MATRIX) { +- _QuitTracking(true); +- } + break; + + case B_DOWN_ARROW: +- if (fLayout == B_ITEMS_IN_COLUMN) { +- _SelectNextItem(fSelected, true); +- } else if (fLayout == B_ITEMS_IN_ROW || fLayout == B_ITEMS_IN_MATRIX) { +- if (fSelected != NULL) { +- BMenu* subMenu = fSelected->Submenu(); +- if (subMenu != NULL && subMenu->LockLooper()) { +- subMenu->_SelectNextItem(subMenu->fSelected, true); +- subMenu->UnlockLooper(); +- fTrackState->curMenu = subMenu; +- } +- } ++ { ++ BMenuBar* bar = dynamic_cast(Supermenu()); ++ if (bar != NULL && fState == MENU_STATE_CLOSED) { ++ // tell MenuBar's _Track: ++ bar->fState = MENU_STATE_KEY_TO_SUBMENU; + } ++ if (fLayout == B_ITEMS_IN_COLUMN) ++ _SelectNextItem(fSelected, true); + break; ++ } + + case B_LEFT_ARROW: +- if (fLayout == B_ITEMS_IN_ROW || fLayout == B_ITEMS_IN_MATRIX) { ++ if (fLayout == B_ITEMS_IN_ROW) + _SelectNextItem(fSelected, false); +- } else if (fLayout == B_ITEMS_IN_COLUMN) { +- _QuitTracking(true); ++ else { ++ // this case has to be handled a bit specially. ++ BMenuItem* item = Superitem(); ++ if (item) { ++ if (dynamic_cast(Supermenu())) { ++ // If we're at the top menu below the menu bar, pass ++ // the keypress to the menu bar so we can move to ++ // another top level menu. ++ BMessenger messenger(Supermenu()); ++ messenger.SendMessage(Window()->CurrentMessage()); ++ } else { ++ // tell _Track ++ fState = MENU_STATE_KEY_LEAVE_SUBMENU; ++ } ++ } + } + break; + + case B_RIGHT_ARROW: +- if (fLayout == B_ITEMS_IN_ROW || fLayout == B_ITEMS_IN_MATRIX) { ++ if (fLayout == B_ITEMS_IN_ROW) + _SelectNextItem(fSelected, true); +- } else if (fLayout == B_ITEMS_IN_COLUMN) { +- if (fSelected != NULL) { +- BMenu* subMenu = fSelected->Submenu(); +- if (subMenu != NULL && subMenu->LockLooper()) { +- subMenu->_SelectNextItem(subMenu->fSelected, true); +- subMenu->UnlockLooper(); +- fTrackState->curMenu = subMenu; +- } ++ else { ++ if (fSelected != NULL && fSelected->Submenu() != NULL) { ++ fSelected->Submenu()->_SetStickyMode(true); ++ // fix me: this shouldn't be needed but dynamic menus ++ // aren't getting it set correctly when keyboard ++ // navigating, which aborts the attach ++ fState = MENU_STATE_KEY_TO_SUBMENU; ++ _SelectItem(fSelected, true, true, true); ++ } else if (dynamic_cast(Supermenu())) { ++ // if we have no submenu and we're an ++ // item in the top menu below the menubar, ++ // pass the keypress to the menubar ++ // so you can use the keypress to switch menus. ++ BMessenger messenger(Supermenu()); ++ messenger.SendMessage(Window()->CurrentMessage()); + } + } + break; +@@ -748,13 +575,21 @@ BMenu::KeyDown(const char* bytes, int32 numBytes) + case B_ENTER: + case B_SPACE: + if (fSelected != NULL) { +- _InvokeItem(fSelected); ++ fChosenItem = fSelected; ++ // preserve for exit handling + _QuitTracking(false); + } + break; + + case B_ESCAPE: +- _QuitTracking(false); ++ _SelectItem(NULL); ++ if (fState == MENU_STATE_CLOSED ++ && dynamic_cast(Supermenu())) { ++ // Keyboard may show menu without tracking it ++ BMessenger messenger(Supermenu()); ++ messenger.SendMessage(Window()->CurrentMessage()); ++ } else ++ _QuitTracking(false); + break; + + default: +@@ -766,18 +601,8 @@ BMenu::KeyDown(const char* bytes, int32 numBytes) + if (item->fTriggerIndex < 0 || item->fTrigger != trigger) + continue; + +- if (item->Submenu()) { +- _SelectItem(item, true, false); +- BMenu* subMenu = fSelected->Submenu(); +- if (subMenu != NULL && subMenu->LockLooper()) { +- subMenu->_SelectNextItem(subMenu->fSelected, true); +- subMenu->UnlockLooper(); +- fTrackState->curMenu = subMenu; +- } +- } else { +- _InvokeItem(item); +- _QuitTracking(false); +- } ++ _InvokeItem(item); ++ _QuitTracking(false); + break; + } + break; +@@ -1463,7 +1288,7 @@ BMenu::BMenu(BRect frame, const char* name, uint32 resizingMode, uint32 flags, + menu_layout layout, bool resizeToFit) + : + BView(frame, name, resizingMode, flags), +- fTrackState(NULL), ++ fChosenItem(NULL), + fSelected(NULL), + fCachedMenuWindow(NULL), + fSuper(NULL), +@@ -1471,6 +1296,7 @@ BMenu::BMenu(BRect frame, const char* name, uint32 resizingMode, uint32 flags, + fAscent(-1.0f), + fDescent(-1.0f), + fFontHeight(-1.0f), ++ fState(MENU_STATE_CLOSED), + fLayout(layout), + fExtraRect(NULL), + fMaxContentWidth(0.0f), +@@ -1565,7 +1391,7 @@ BMenu::Track(bool sticky, BRect* clickToOpenRect) + + _SetStickyMode(sticky); + +- int32 action; ++ int action; + BMenuItem* menuItem = _Track(&action); + + fExtraRect = NULL; +@@ -1681,7 +1507,7 @@ BMenu::_InitData(BMessage* archive) + + + bool +-BMenu::_Show(bool selectFirstItem) ++BMenu::_Show(bool selectFirstItem, bool keyDown) + { + if (Window() != NULL) + return false; +@@ -1708,6 +1534,17 @@ BMenu::_Show(bool selectFirstItem) + return false; + + if (window->Lock()) { ++ bool addAborted = false; ++ if (keyDown) ++ addAborted = _AddDynamicItems(keyDown); ++ ++ if (addAborted) { ++ if (ourWindow) ++ window->Quit(); ++ else ++ window->Unlock(); ++ return false; ++ } + fAttachAborted = false; + + window->AttachMenu(this); +@@ -1721,7 +1558,6 @@ BMenu::_Show(bool selectFirstItem) + + // Menu didn't have the time to add its items: aborting... + if (fAttachAborted) { +- printf("fAttachAborted\n"); + window->DetachMenu(); + // TODO: Probably not needed, we can just let _hide() quit the + // window. +@@ -1735,11 +1571,6 @@ BMenu::_Show(bool selectFirstItem) + _UpdateWindowViewSize(true); + window->Show(); + +- if (Supermenu() != NULL) { +- fTrackState = Supermenu()->fTrackState; +- fTriggerEnabled = Supermenu()->fTriggerEnabled; +- } +- + if (selectFirstItem) + _SelectItem(ItemAt(0), false); + +@@ -1760,22 +1591,6 @@ BMenu::_Hide() + if (fSelected != NULL) + _SelectItem(NULL); + +- BMenu *rootMenu = NULL; +- if (fTrackState != NULL) { +- AutoLocker locker(fTrackState->locker); +- if (fTrackState->cursorMenu == this) { +- SetEventMask(0, 0); +- rootMenu = fTrackState->rootMenu; +- fTrackState->cursorMenu = rootMenu; +- } +- } +- if (rootMenu != NULL && rootMenu->LockLooper()) { +- rootMenu->SetEventMask(B_POINTER_EVENTS, 0); +- rootMenu->UnlockLooper(); +- } +- +- fTrackState = NULL; +- + window->Hide(); + window->DetachMenu(); + // we don't want to be deleted when the window is removed +@@ -2128,92 +1943,189 @@ status_t BMenu::_InsertItemAtSpecifier(const BMessage& specifier, int32 what, + // #pragma mark - mouse tracking + + ++const static bigtime_t kOpenSubmenuDelay = 0; ++const static bigtime_t kNavigationAreaTimeout = 1000000; ++ ++ + BMenuItem* +-BMenu::_Track(int32* action, int32 start) ++BMenu::_Track(int* action, long start) + { +- if (fTrackState != NULL) { +- printf("Track: already entered\n"); +- return NULL; +- } +- printf("+Track\n"); +- printf("sticky: %d\n", fStickyMode); +- if (fExtraRect != NULL) { +- printf("extraRect: "); fExtraRect->PrintToStream(); +- } +- if (sMenuInfo.click_to_open) +- _SetStickyMode(true); +- BPrivate::MenuTrackState trackState; ++ // TODO: cleanup + BMenuItem* item = NULL; +- BMenuItem* startItem = ItemAt(start); +- bool oldTriggerEnabled = fTriggerEnabled; +- thread_id senderThread; +- bool run = true; +- +- fTrackState = &trackState; +- fTrackState->trackThread = find_thread(NULL); +- fTrackState->quit = false; +- fTrackState->rootMenu = this; +- fTrackState->curMenu = this; +- fTrackState->cursorMenu = this; +- fTrackState->invokedItem = NULL; +- fTrackState->cursorInside = false; +- fTrackState->cursorObscured = false; +- fTrackState->navAreaRectAbove = BRect(); +- fTrackState->navAreaRectBelow = BRect(); +- //fTrackState->navigationAreaTimer = NULL; ++ BRect navAreaRectAbove; ++ BRect navAreaRectBelow; ++ bigtime_t selectedTime = system_time(); ++ bigtime_t navigationAreaTime = 0; + ++ fState = MENU_STATE_TRACKING; ++ fChosenItem = NULL; ++ // we will use this for keyboard selection ++ ++ BPoint location; ++ uint32 buttons = 0; + if (LockLooper()) { +- SetEventMask(B_POINTER_EVENTS, 0); +- BPoint where; +- uint32 btns; +- GetMouse(&where, &btns); +- fTrackState->cursorInside = Bounds().Contains(where); +- fTrackState->clickPoint = ConvertToScreen(where); +- if (startItem == NULL) { +- startItem = _HitTestItems(where, B_ORIGIN); +- } +- if (!oldTriggerEnabled && btns == 0) { +- fTrackState->cursorObscured = true; +- be_app->ObscureCursor(); +- fTriggerEnabled = true; +- Invalidate(); +- } +- _SelectItem(startItem, true, false); ++ GetMouse(&location, &buttons); + UnlockLooper(); + } +- while (run) { +- int32 cmd = receive_data(&senderThread, NULL, 0); +- switch (cmd) { +- case MENU_TRACK_CMD_DONE: +- run = false; ++ ++ bool releasedOnce = buttons == 0; ++ while (fState != MENU_STATE_CLOSED) { ++ if (_CustomTrackingWantsToQuit()) ++ break; ++ ++ if (!LockLooper()) ++ break; ++ ++ BMenuWindow* window = static_cast(Window()); ++ BPoint screenLocation = ConvertToScreen(location); ++ if (window->CheckForScrolling(screenLocation)) { ++ UnlockLooper(); ++ continue; ++ } ++ ++ // The order of the checks is important ++ // to be able to handle overlapping menus: ++ // first we check if mouse is inside a submenu, ++ // then if the mouse is inside this menu, ++ // then if it's over a super menu. ++ if (_OverSubmenu(fSelected, screenLocation) ++ || fState == MENU_STATE_KEY_TO_SUBMENU) { ++ if (fState == MENU_STATE_TRACKING) { ++ // not if from R.Arrow ++ fState = MENU_STATE_TRACKING_SUBMENU; ++ } ++ navAreaRectAbove = BRect(); ++ navAreaRectBelow = BRect(); ++ ++ // Since the submenu has its own looper, ++ // we can unlock ours. Doing so also make sure ++ // that our window gets any update message to ++ // redraw itself ++ UnlockLooper(); ++ ++ // To prevent NULL access violation, ensure a menu has actually ++ // been selected and that it has a submenu. Because keyboard and ++ // mouse interactions set selected items differently, the menu ++ // tracking thread needs to be careful in triggering the navigation ++ // to the submenu. ++ if (fSelected != NULL) { ++ BMenu* submenu = fSelected->Submenu(); ++ int submenuAction = MENU_STATE_TRACKING; ++ if (submenu != NULL) { ++ submenu->_SetStickyMode(_IsStickyMode()); ++ ++ // The following call blocks until the submenu ++ // gives control back to us, either because the mouse ++ // pointer goes out of the submenu's bounds, or because ++ // the user closes the menu ++ BMenuItem* submenuItem = submenu->_Track(&submenuAction); ++ if (submenuAction == MENU_STATE_CLOSED) { ++ item = submenuItem; ++ fState = MENU_STATE_CLOSED; ++ } else if (submenuAction == MENU_STATE_KEY_LEAVE_SUBMENU) { ++ if (LockLooper()) { ++ BMenuItem* temp = fSelected; ++ // close the submenu: ++ _SelectItem(NULL); ++ // but reselect the item itself for user: ++ _SelectItem(temp, false); ++ UnlockLooper(); ++ } ++ // cancel key-nav state ++ fState = MENU_STATE_TRACKING; ++ } else ++ fState = MENU_STATE_TRACKING; ++ } ++ } ++ if (!LockLooper()) + break; ++ } else if ((item = _HitTestItems(location, B_ORIGIN)) != NULL) { ++ _UpdateStateOpenSelect(item, location, navAreaRectAbove, ++ navAreaRectBelow, selectedTime, navigationAreaTime); ++ releasedOnce = true; ++ } else if (_OverSuper(screenLocation) ++ && fSuper->fState != MENU_STATE_KEY_TO_SUBMENU) { ++ fState = MENU_STATE_TRACKING; ++ UnlockLooper(); ++ break; ++ } else if (fState == MENU_STATE_KEY_LEAVE_SUBMENU) { ++ UnlockLooper(); ++ break; ++ } else if (fSuper == NULL ++ || fSuper->fState != MENU_STATE_KEY_TO_SUBMENU) { ++ // Mouse pointer outside menu: ++ // If there's no other submenu opened, ++ // deselect the current selected item ++ if (fSelected != NULL ++ && (fSelected->Submenu() == NULL ++ || fSelected->Submenu()->Window() == NULL)) { ++ _SelectItem(NULL); ++ fState = MENU_STATE_TRACKING; ++ } ++ ++ if (fSuper != NULL) { ++ // Give supermenu the chance to continue tracking ++ *action = fState; ++ UnlockLooper(); ++ return NULL; ++ } ++ } ++ ++ UnlockLooper(); ++ ++ if (releasedOnce) ++ _UpdateStateClose(item, location, buttons); ++ ++ if (fState != MENU_STATE_CLOSED) { ++ bigtime_t snoozeAmount = 50000; ++ ++ BPoint newLocation = location; ++ uint32 newButtons = buttons; ++ ++ // If user doesn't move the mouse, loop here, ++ // so we don't interfere with keyboard menu navigation ++ do { ++ snooze(snoozeAmount); ++ if (!LockLooper()) ++ break; ++ GetMouse(&newLocation, &newButtons, true); ++ UnlockLooper(); ++ } while (newLocation == location && newButtons == buttons ++ && !(item != NULL && item->Submenu() != NULL ++ && item->Submenu()->Window() == NULL) ++ && fState == MENU_STATE_TRACKING); ++ ++ if (newLocation != location || newButtons != buttons) { ++ if (!releasedOnce && newButtons == 0 && buttons != 0) ++ releasedOnce = true; ++ location = newLocation; ++ buttons = newButtons; ++ } ++ ++ if (releasedOnce) ++ _UpdateStateClose(item, location, buttons); + } + } + +- item = fTrackState->invokedItem; ++ if (action != NULL) ++ *action = fState; + +- if (LockLooper()) { +- // hide submenus ++ // keyboard Enter will set this ++ if (fChosenItem != NULL) ++ item = fChosenItem; ++ else if (fSelected == NULL) { ++ // needed to cover (rare) mouse/ESC combination ++ item = NULL; ++ } ++ ++ if (fSelected != NULL && LockLooper()) { + _SelectItem(NULL); +- SetEventMask(0, 0); +- if (fTriggerEnabled != oldTriggerEnabled) { +- fTriggerEnabled = oldTriggerEnabled; +- Invalidate(); +- } +-/* +- if (fTrackState->navigationAreaTimer != NULL) { +- delete fTrackState->navigationAreaTimer; +- fTrackState->navigationAreaTimer = NULL; +- } +-*/ +- fTrackState = NULL; + UnlockLooper(); + } + + // delete the menu window recycled for all the child menus + _DeleteMenuWindow(); + +- printf("-Track\n"); + return item; + } + +@@ -2259,15 +2171,16 @@ BMenu::_UpdateNavigationArea(BPoint position, BRect& navAreaRectAbove, + if (fSelected == NULL) + return; + +- BView* submenu = fSelected->Submenu()->Parent(); ++ BMenu* submenu = fSelected->Submenu(); + + if (submenu != NULL) { + BRect menuBounds = ConvertToScreen(Bounds()); + + BRect submenuBounds; +- if (submenu->LockLooper()) { +- submenuBounds = submenu->ConvertToScreen(submenu->Bounds()); +- submenu->UnlockLooper(); ++ if (fSelected->Submenu()->LockLooper()) { ++ submenuBounds = fSelected->Submenu()->ConvertToScreen( ++ fSelected->Submenu()->Bounds()); ++ fSelected->Submenu()->UnlockLooper(); + } + + if (menuBounds.left < submenuBounds.left) { +@@ -2289,95 +2202,21 @@ BMenu::_UpdateNavigationArea(BPoint position, BRect& navAreaRectAbove, + navAreaRectAbove = BRect(); + navAreaRectBelow = BRect(); + } +- +- #if SHOW_NAVIGATION_AREA +- Invalidate(); +- #endif +-} +- +- +-bool +-BMenu::_HitNavigationArea(BPoint position, BMenuItem* item) +-{ +- if (fLayout != B_ITEMS_IN_COLUMN) +- return false; +- +- BRect navAreaRectAbove, navAreaRectBelow; +- { +- AutoLocker locker(fTrackState->locker); +- navAreaRectAbove = fTrackState->navAreaRectAbove; +- navAreaRectBelow = fTrackState->navAreaRectBelow; +- } +- +- position = ConvertToScreen(position); +- printf("position: "); position.PrintToStream(); +- +- if (!navAreaRectAbove.IsValid() && !navAreaRectBelow.IsValid() && fSelected != NULL && fSelected->Submenu() != NULL) { +- printf("_UpdateNavigationArea\n"); +- _UpdateNavigationArea(position, navAreaRectAbove, +- navAreaRectBelow); +- } +- +- printf("navAreaRectAbove: "); navAreaRectAbove.PrintToStream(); +- printf("navAreaRectBelow: "); navAreaRectBelow.PrintToStream(); +- +- bool inNavArea = false; +- bool inNavAreaRectAbove = navAreaRectAbove.Contains(position); +- bool inNavAreaRectBelow = navAreaRectBelow.Contains(position); +- +- if (inNavAreaRectAbove || inNavAreaRectBelow) { +- bool isLeft = ConvertFromScreen(navAreaRectAbove).left == 0; +- BPoint p1, p2; +- +- if (inNavAreaRectAbove) { +- if (!isLeft) { +- p1 = navAreaRectAbove.LeftBottom(); +- p2 = navAreaRectAbove.RightTop(); +- } else { +- p2 = navAreaRectAbove.RightBottom(); +- p1 = navAreaRectAbove.LeftTop(); +- } +- } else { +- if (!isLeft) { +- p2 = navAreaRectBelow.LeftTop(); +- p1 = navAreaRectBelow.RightBottom(); +- } else { +- p1 = navAreaRectBelow.RightTop(); +- p2 = navAreaRectBelow.LeftBottom(); +- } +- } +- inNavArea = +- (p1.y - p2.y) * position.x + (p2.x - p1.x) * position.y +- + (p1.x - p2.x) * p1.y + (p2.y - p1.y) * p1.x >= 0; +- } +- +- printf("inNavArea: %d\n", inNavArea); +- +- if (!inNavArea && !(item != NULL && item->Frame().Contains(ConvertFromScreen(position)))) { +- printf("reset nav area\n"); +- navAreaRectAbove = BRect(); +- navAreaRectBelow = BRect(); +- } +- +- { +- AutoLocker locker(fTrackState->locker); +- navAreaRectAbove = fTrackState->navAreaRectAbove = navAreaRectAbove; +- navAreaRectBelow = fTrackState->navAreaRectBelow = navAreaRectBelow; +- } +- +- return inNavArea; + } + + + void + BMenu::_UpdateStateOpenSelect(BMenuItem* item, BPoint position, +- BRect& navAreaRectAbove, BRect& navAreaRectBelow, bool isTimeout) ++ BRect& navAreaRectAbove, BRect& navAreaRectBelow, bigtime_t& selectedTime, ++ bigtime_t& navigationAreaTime) + { +- if (fLayout != B_ITEMS_IN_COLUMN) { +- _SelectItem(item, true); ++ if (fState == MENU_STATE_CLOSED) + return; +- } ++ + if (item != fSelected) { ++ if (navigationAreaTime == 0) ++ navigationAreaTime = system_time(); ++ + position = ConvertToScreen(position); + + bool inNavAreaRectAbove = navAreaRectAbove.Contains(position); +@@ -2385,13 +2224,11 @@ BMenu::_UpdateStateOpenSelect(BMenuItem* item, BPoint position, + + if (fSelected == NULL + || (!inNavAreaRectAbove && !inNavAreaRectBelow)) { +- _SelectItem(item, true); ++ _SelectItem(item, false); + navAreaRectAbove = BRect(); + navAreaRectBelow = BRect(); +- { +- AutoLocker locker(fTrackState->locker); +- fTrackState->navigationAreaTimer.Unset(); +- } ++ selectedTime = system_time(); ++ navigationAreaTime = 0; + return; + } + +@@ -2419,8 +2256,13 @@ BMenu::_UpdateStateOpenSelect(BMenuItem* item, BPoint position, + (p1.y - p2.y) * position.x + (p2.x - p1.x) * position.y + + (p1.x - p2.x) * p1.y + (p2.y - p1.y) * p1.x >= 0; + +- if (!inNavArea || isTimeout) { +- _SelectItem(item, true); ++ bigtime_t systime = system_time(); ++ ++ if (!inNavArea || (navigationAreaTime > 0 && systime - ++ navigationAreaTime > kNavigationAreaTimeout)) { ++ // Don't delay opening of submenu if the user had ++ // to wait for the navigation area timeout anyway ++ _SelectItem(item, inNavArea); + + if (inNavArea) { + _UpdateNavigationArea(position, navAreaRectAbove, +@@ -2430,18 +2272,11 @@ BMenu::_UpdateStateOpenSelect(BMenuItem* item, BPoint position, + navAreaRectBelow = BRect(); + } + +- { +- AutoLocker locker(fTrackState->locker); +- fTrackState->navigationAreaTimer.Unset(); +- } ++ selectedTime = system_time(); ++ navigationAreaTime = 0; + } +- } else if (fSelected->Submenu() != NULL) { +- { +- AutoLocker locker(fTrackState->locker); +- BMessage message(navigationAreaTimeoutMsg); +- fTrackState->navigationAreaTimer.SetTo(new(std::nothrow) BMessageRunner(BMessenger(this), BMessage(navigationAreaTimeoutMsg), kNavigationAreaTimeout, 1)); +- } +- ++ } else if (fSelected->Submenu() != NULL && ++ system_time() - selectedTime > kOpenSubmenuDelay) { + _SelectItem(fSelected, true); + + if (!navAreaRectAbove.IsValid() && !navAreaRectBelow.IsValid()) { +@@ -2450,6 +2285,42 @@ BMenu::_UpdateStateOpenSelect(BMenuItem* item, BPoint position, + navAreaRectBelow); + } + } ++ ++ if (fState != MENU_STATE_TRACKING) ++ fState = MENU_STATE_TRACKING; ++} ++ ++ ++void ++BMenu::_UpdateStateClose(BMenuItem* item, const BPoint& where, ++ const uint32& buttons) ++{ ++ if (fState == MENU_STATE_CLOSED) ++ return; ++ ++ if (buttons != 0 && _IsStickyMode()) { ++ if (item == NULL) { ++ if (item != fSelected && LockLooper()) { ++ _SelectItem(item, false); ++ UnlockLooper(); ++ } ++ fState = MENU_STATE_CLOSED; ++ } else ++ _SetStickyMode(false); ++ } else if (buttons == 0 && !_IsStickyMode()) { ++ if (fExtraRect != NULL && fExtraRect->Contains(where)) { ++ _SetStickyMode(true); ++ fExtraRect = NULL; ++ // Setting this to NULL will prevent this code ++ // to be executed next time ++ } else { ++ if (item != fSelected && LockLooper()) { ++ _SelectItem(item, false); ++ UnlockLooper(); ++ } ++ fState = MENU_STATE_CLOSED; ++ } ++ } + } + + +@@ -2829,7 +2700,7 @@ BMenu::ScreenLocation() + + BPoint point; + if (superMenu->Layout() == B_ITEMS_IN_COLUMN) +- point = superItem->Frame().RightTop() + BPoint(1.0f, 0.0f); ++ point = superItem->Frame().RightTop() + BPoint(1.0f, 1.0f); + else + point = superItem->Frame().LeftBottom() + BPoint(1.0f, 1.0f); + +@@ -2929,41 +2800,29 @@ BMenu::DrawItems(BRect updateRect) + } + + ++int ++BMenu::_State(BMenuItem** item) const ++{ ++ if (fState == MENU_STATE_TRACKING || fState == MENU_STATE_CLOSED) ++ return fState; ++ ++ if (fSelected != NULL && fSelected->Submenu() != NULL) ++ return fSelected->Submenu()->_State(item); ++ ++ return fState; ++} ++ ++ + void + BMenu::_InvokeItem(BMenuItem* item, bool now) + { + if (!item->IsEnabled()) + return; + +- // called from BWindow for shortcut handling +- if (now) { +- // Lock the root menu window before calling BMenuItem::Invoke() +- BMenu* parent = this; +- BMenu* rootMenu = NULL; +- do { +- rootMenu = parent; +- parent = rootMenu->Supermenu(); +- } while (parent != NULL); +- +- if (rootMenu->LockLooper()) { +- item->Invoke(); +- rootMenu->UnlockLooper(); +- } +- return; +- } +- +- { +- if (fTrackState == NULL) +- return; +- AutoLocker locker(fTrackState->locker); +- if (fTrackState->invokedItem != NULL) +- return; +- fTrackState->invokedItem = item; +- } +- + // Do the "selected" animation +- #if 0 +- if (LockLooper()) { ++ // TODO: Doesn't work. This is supposed to highlight ++ // and dehighlight the item, works on beos but not on haiku. ++ if (!item->Submenu() && LockLooper()) { + snooze(50000); + item->Select(true); + Window()->UpdateIfNeeded(); +@@ -2978,7 +2837,19 @@ BMenu::_InvokeItem(BMenuItem* item, bool now) + Window()->UpdateIfNeeded(); + UnlockLooper(); + } +- #endif ++ ++ // Lock the root menu window before calling BMenuItem::Invoke() ++ BMenu* parent = this; ++ BMenu* rootMenu = NULL; ++ do { ++ rootMenu = parent; ++ parent = rootMenu->Supermenu(); ++ } while (parent != NULL); ++ ++ if (rootMenu->LockLooper()) { ++ item->Invoke(); ++ rootMenu->UnlockLooper(); ++ } + } + + +@@ -3108,7 +2979,8 @@ BMenu::_Uninstall() + + + void +-BMenu::_SelectItem(BMenuItem* item, bool showSubmenu, bool selectFirstItem) ++BMenu::_SelectItem(BMenuItem* item, bool showSubmenu, bool selectFirstItem, ++ bool keyDown) + { + // Avoid deselecting and then reselecting the same item + // which would cause flickering +@@ -3121,27 +2993,15 @@ BMenu::_SelectItem(BMenuItem* item, bool showSubmenu, bool selectFirstItem) + } + + fSelected = item; +- if (fSelected != NULL) { +- BMenuWindow* window = dynamic_cast(Window()); +- if (window != NULL && window->LockLooper()) { +- BRect frame = ConvertToParent(fSelected->Frame()); +- float height = Parent()->Bounds().Height(); +- if (frame.top < 0) +- window->TryScrollBy(frame.top); +- else if (frame.bottom > height) +- window->TryScrollBy(frame.bottom - height); +- window->UnlockLooper(); +- } ++ if (fSelected != NULL) + fSelected->Select(true); +- } + } + + if (fSelected != NULL && showSubmenu) { + BMenu* subMenu = fSelected->Submenu(); + if (subMenu != NULL && subMenu->Window() == NULL) { +- if (!subMenu->_Show(selectFirstItem)) { ++ if (!subMenu->_Show(selectFirstItem, keyDown)) { + // something went wrong, deselect the item +- printf("_SelectItem: can't show submenu\n"); + fSelected->Select(false); + fSelected = NULL; + } +@@ -3160,7 +3020,7 @@ BMenu::_SelectNextItem(BMenuItem* item, bool forward) + if (nextItem == NULL) + return false; + +- _SelectItem(nextItem, true, false); ++ _SelectItem(nextItem, dynamic_cast(this) != NULL); + + if (LockLooper()) { + be_app->ObscureCursor(); +@@ -3180,7 +3040,7 @@ BMenu::_NextItem(BMenuItem* item, bool forward) const + + int32 index = fItems.IndexOf(item); + int32 loopCount = numItems; +- while (loopCount--) { ++ while (--loopCount) { + // Cycle through menu items in the given direction... + if (forward) + index++; +@@ -3207,23 +3067,32 @@ BMenu::_NextItem(BMenuItem* item, bool forward) const + void + BMenu::_SetStickyMode(bool sticky) + { +- if (fTrackState == NULL) { +- fStickyMode = sticky; ++ if (fStickyMode == sticky) + return; ++ ++ fStickyMode = sticky; ++ ++ if (fSuper != NULL) { ++ // propagate the status to the super menu ++ fSuper->_SetStickyMode(sticky); ++ } else { ++ // TODO: Ugly hack, but it needs to be done in this method ++ BMenuBar* menuBar = dynamic_cast(this); ++ if (sticky && menuBar != NULL && menuBar->LockLooper()) { ++ // If we are switching to sticky mode, ++ // steal the focus from the current focus view ++ // (needed to handle keyboard navigation) ++ menuBar->_StealFocus(); ++ menuBar->UnlockLooper(); ++ } + } +- AutoLocker locker(fTrackState->locker); +- fTrackState->rootMenu->fStickyMode = sticky; + } + + + bool + BMenu::_IsStickyMode() const + { +- if (fTrackState == NULL) { +- return fStickyMode; +- } +- AutoLocker locker(fTrackState->locker); +- return fTrackState->rootMenu->fStickyMode; ++ return fStickyMode; + } + + +@@ -3366,10 +3235,13 @@ BMenu::_ChooseTrigger(const char* title, int32& index, uint32& trigger, + void + BMenu::_UpdateWindowViewSize(const bool &move) + { +- BMenuWindow* window = dynamic_cast(Window()); ++ BMenuWindow* window = static_cast(Window()); + if (window == NULL) + return; + ++ if (dynamic_cast(this) != NULL) ++ return; ++ + if (!fResizeToFit) + return; + +@@ -3430,17 +3302,15 @@ BMenu::_UpdateWindowViewSize(const bool &move) + + + bool +-BMenu::_AddDynamicItems() ++BMenu::_AddDynamicItems(bool keyDown) + { +- printf("_AddDynamicItems(%p)\n", this); + bool addAborted = false; + if (AddDynamicItem(B_INITIAL_ADD)) { + BMenuItem* superItem = Superitem(); + BMenu* superMenu = Supermenu(); + do { +- //printf("_AddDynamicItems: step\n"); + if (superMenu != NULL +- && !superMenu->_OkToProceed(superItem)) { ++ && !superMenu->_OkToProceed(superItem, keyDown)) { + AddDynamicItem(B_ABORT); + addAborted = true; + break; +@@ -3453,41 +3323,66 @@ BMenu::_AddDynamicItems() + + + bool +-BMenu::_OkToProceed(BMenuItem* item) +-{ +- return true; /* !!! */ ++BMenu::_OkToProceed(BMenuItem* item, bool keyDown) ++{ ++ BPoint where; ++ uint32 buttons; ++ GetMouse(&where, &buttons, false); ++ bool stickyMode = _IsStickyMode(); ++ // Quit if user clicks the mouse button in sticky mode ++ // or releases the mouse button in nonsticky mode ++ // or moves the pointer over another item ++ // TODO: I added the check for BMenuBar to solve a problem with Deskbar. ++ // BeOS seems to do something similar. This could also be a bug in ++ // Deskbar, though. ++ if ((buttons != 0 && stickyMode) ++ || ((dynamic_cast(this) == NULL ++ && (buttons == 0 && !stickyMode)) ++ || ((_HitTestItems(where) != item) && !keyDown))) { ++ return false; ++ } ++ ++ return true; + } + + +-void +-BMenu::_CallTrackingHook() ++bool ++BMenu::_CustomTrackingWantsToQuit() + { + if (fExtraMenuData != NULL && fExtraMenuData->trackingHook != NULL + && fExtraMenuData->trackingState != NULL) { +- if (fExtraMenuData->trackingHook(this, fExtraMenuData->trackingState)) +- _QuitTracking(true); ++ return fExtraMenuData->trackingHook(this, ++ fExtraMenuData->trackingState); + } ++ ++ return false; + } + + + void + BMenu::_QuitTracking(bool onlyThis) + { +- if (fTrackState == NULL) +- return; ++ _SelectItem(NULL); ++ if (BMenuBar* menuBar = dynamic_cast(this)) ++ menuBar->_RestoreFocus(); + +- AutoLocker locker(fTrackState->locker); ++ fState = MENU_STATE_CLOSED; + +- if (onlyThis && Supermenu() != NULL) { +- _SelectItem(NULL); +- fTrackState->curMenu = Supermenu(); +- return; +- } ++ if (!onlyThis) { ++ // Close the whole menu hierarchy ++ if (Supermenu() != NULL) ++ Supermenu()->fState = MENU_STATE_CLOSED; + +- if (!fTrackState->quit) { +- fTrackState->quit = true; +- send_data(fTrackState->trackThread, MENU_TRACK_CMD_DONE, NULL, 0); ++ if (_IsStickyMode()) ++ _SetStickyMode(false); ++ ++ if (LockLooper()) { ++ be_app->ShowCursor(); ++ UnlockLooper(); ++ } + } ++ ++ _Hide(); + } + + +diff --git a/src/kits/interface/MenuBar.cpp b/src/kits/interface/MenuBar.cpp +index 91442206f2..6a07dd23c4 100644 +--- a/src/kits/interface/MenuBar.cpp ++++ b/src/kits/interface/MenuBar.cpp +@@ -173,9 +173,6 @@ BMenuBar::AllDetached() + void + BMenuBar::WindowActivated(bool state) + { +- if (!state) { +- BPrivate::MenuPrivate(this).QuitTracking(false); +- } + BView::WindowActivated(state); + } + +@@ -553,32 +550,152 @@ BMenuBar::_TrackTask(void* arg) + BMenuItem* + BMenuBar::_Track(int32* action, int32 startIndex, bool showMenu) + { ++ // TODO: Cleanup, merge some "if" blocks if possible + BMenuItem* item = NULL; ++ fState = MENU_STATE_TRACKING; ++ fChosenItem = NULL; ++ // we will use this for keyboard selection + +- if (startIndex == -1 && showMenu) +- startIndex = 0; +- ++ BPoint where; ++ uint32 buttons; + if (LockLooper()) { +- _StealFocus(); ++ if (startIndex != -1) { ++ be_app->ObscureCursor(); ++ _SelectItem(ItemAt(startIndex), true, false); ++ } ++ GetMouse(&where, &buttons); + UnlockLooper(); + } + +- item = BMenu::_Track(action, startIndex); ++ while (fState != MENU_STATE_CLOSED) { ++ bigtime_t snoozeAmount = 40000; ++ if (!LockLooper()) ++ break; ++ ++ item = dynamic_cast<_BMCMenuBar_*>(this) != NULL ? ItemAt(0) ++ : _HitTestItems(where, B_ORIGIN); ++ ++ if (_OverSubmenu(fSelected, ConvertToScreen(where)) ++ || fState == MENU_STATE_KEY_TO_SUBMENU) { ++ // call _Track() from the selected sub-menu when the mouse cursor ++ // is over its window ++ BMenu* submenu = fSelected->Submenu(); ++ UnlockLooper(); ++ snoozeAmount = 30000; ++ submenu->_SetStickyMode(_IsStickyMode()); ++ int localAction; ++ fChosenItem = submenu->_Track(&localAction); ++ ++ // The mouse could have meen moved since the last time we ++ // checked its position, or buttons might have been pressed. ++ // Unfortunately our child menus don't tell ++ // us the new position. ++ // TODO: Maybe have a shared struct between all menus ++ // where to store the current mouse position ? ++ // (Or just use the BView mouse hooks) ++ BPoint newWhere; ++ if (LockLooper()) { ++ GetMouse(&newWhere, &buttons); ++ UnlockLooper(); ++ } ++ ++ // Needed to make BMenuField child menus "sticky" ++ // (see ticket #953) ++ if (localAction == MENU_STATE_CLOSED) { ++ if (fExtraRect != NULL && fExtraRect->Contains(where) ++ && point_distance(newWhere, where) < 9) { ++ // 9 = 3 pixels ^ 2 (since point_distance() returns the ++ // square of the distance) ++ _SetStickyMode(true); ++ fExtraRect = NULL; ++ } else ++ fState = MENU_STATE_CLOSED; ++ } ++ if (!LockLooper()) ++ break; ++ } else if (item != NULL) { ++ if (item->Submenu() != NULL && item != fSelected) { ++ if (item->Submenu()->Window() == NULL) { ++ // open the menu if it's not opened yet ++ _SelectItem(item); ++ } else { ++ // Menu was already opened, close it and bail ++ _SelectItem(NULL); ++ fState = MENU_STATE_CLOSED; ++ fChosenItem = NULL; ++ } ++ } else { ++ // No submenu, just select the item ++ _SelectItem(item); ++ } ++ } else if (item == NULL && fSelected != NULL ++ && !_IsStickyMode() && Bounds().Contains(where)) { ++ _SelectItem(NULL); ++ fState = MENU_STATE_TRACKING; ++ } ++ ++ UnlockLooper(); ++ ++ if (fState != MENU_STATE_CLOSED) { ++ BPoint newWhere = where; ++ uint32 newButtons = buttons; ++ ++ do { ++ // If user doesn't move the mouse or change buttons loop ++ // here so that we don't interfere with keyboard menu ++ // navigation ++ snooze(snoozeAmount); ++ if (!LockLooper()) ++ break; ++ ++ GetMouse(&newWhere, &newButtons); ++ UnlockLooper(); ++ } while (newWhere == where && newButtons == buttons ++ && fState == MENU_STATE_TRACKING); ++ ++ if (newButtons != 0 && _IsStickyMode()) { ++ if (item == NULL || (item->Submenu() != NULL ++ && item->Submenu()->Window() != NULL)) { ++ // clicked outside the menu bar or on item with already ++ // open sub menu ++ fState = MENU_STATE_CLOSED; ++ } else ++ _SetStickyMode(false); ++ } else if (newButtons == 0 && !_IsStickyMode()) { ++ if ((fSelected != NULL && fSelected->Submenu() == NULL) ++ || item == NULL) { ++ // clicked on an item without a submenu or clicked and ++ // released the mouse button outside the menu bar ++ fChosenItem = fSelected; ++ fState = MENU_STATE_CLOSED; ++ } else ++ _SetStickyMode(true); ++ } ++ where = newWhere; ++ buttons = newButtons; ++ } ++ } + + if (LockLooper()) { + if (fSelected != NULL) + _SelectItem(NULL); + +- if (item != NULL) +- item->Invoke(); ++ if (fChosenItem != NULL) ++ fChosenItem->Invoke(); + + _RestoreFocus(); + UnlockLooper(); + } + ++ if (_IsStickyMode()) ++ _SetStickyMode(false); ++ + _DeleteMenuWindow(); + +- return item; ++ if (action != NULL) ++ *action = fState; ++ ++ return fChosenItem; + } + + +@@ -630,6 +747,7 @@ BMenuBar::_InitData(menu_layout layout) + + fBorders = BControlLook::B_ALL_BORDERS; + fLastBounds = new BRect(Bounds()); ++ _SetIgnoreHidden(true); + SetLowUIColor(B_MENU_BACKGROUND_COLOR); + SetViewColor(B_TRANSPARENT_COLOR); + } +diff --git a/src/kits/interface/MenuField.cpp b/src/kits/interface/MenuField.cpp +index 588ef6818f..8bf6193010 100644 +--- a/src/kits/interface/MenuField.cpp ++++ b/src/kits/interface/MenuField.cpp +@@ -507,11 +507,6 @@ BMenuField::KeyDown(const char* bytes, int32 numBytes) + + fMenuBar->StartMenuBar(0, true, true, &bounds); + +- fMenuTaskID = spawn_thread((thread_func)_thread_entry, +- "_m_task_", B_NORMAL_PRIORITY, this); +- if (fMenuTaskID >= 0) +- resume_thread(fMenuTaskID); +- + bounds = Bounds(); + bounds.right = fDivider; + +@@ -1092,7 +1087,7 @@ BMenuField::_DrawLabel(BRect updateRect) + rgb_color textColor; + + BPrivate::MenuPrivate menuPrivate(fMenuBar); +- if (menuPrivate.IsTracking()) { ++ if (menuPrivate.State() != MENU_STATE_CLOSED) { + // highlight the background of the label grey (like BeOS R5) + SetLowColor(ui_color(B_MENU_SELECTED_BACKGROUND_COLOR)); + BRect fillRect(rect.InsetByCopy(0, kVMargin)); +diff --git a/src/kits/interface/MenuPrivate.cpp b/src/kits/interface/MenuPrivate.cpp +index 73ea8d70e5..4339654f77 100644 +--- a/src/kits/interface/MenuPrivate.cpp ++++ b/src/kits/interface/MenuPrivate.cpp +@@ -168,10 +168,10 @@ MenuPrivate::SetItemMargins(float left, float top, float right, float bottom) + } + + +-bool +-MenuPrivate::IsTracking() const ++int ++MenuPrivate::State(BMenuItem** item) const + { +- return fMenu->fTrackState != NULL; ++ return fMenu->_State(item); + } + + +diff --git a/src/kits/interface/MenuWindow.cpp b/src/kits/interface/MenuWindow.cpp +index 2a1b735292..f1b373c087 100644 +--- a/src/kits/interface/MenuWindow.cpp ++++ b/src/kits/interface/MenuWindow.cpp +@@ -15,7 +15,6 @@ + #include + #include + #include +-#include + + #include + #include +@@ -26,24 +25,12 @@ namespace BPrivate { + class BMenuScroller : public BView { + public: + BMenuScroller(BRect frame); +- ~BMenuScroller(); + + bool IsEnabled() const; + void SetEnabled(bool enabled); + +- void MouseMoved(BPoint where, uint32 transit, +- const BMessage* dragMessage); +- void MessageReceived(BMessage* msg); +- +-protected: +- virtual void DoScroll() = 0; +- + private: +- void _StartScrolling(bool doStart); +- + bool fEnabled; +- bool fMouseInside; +- BMessageRunner* fScrollRunner; + }; + + +@@ -66,8 +53,7 @@ class UpperScroller : public BMenuScroller { + public: + UpperScroller(BRect frame); + +- void DoScroll(); +- void Draw(BRect updateRect); ++ virtual void Draw(BRect updateRect); + }; + + +@@ -75,8 +61,7 @@ class LowerScroller : public BMenuScroller { + public: + LowerScroller(BRect frame); + +- void DoScroll(); +- void Draw(BRect updateRect); ++ virtual void Draw(BRect updateRect); + }; + + +@@ -88,29 +73,17 @@ using namespace BPrivate; + + const int kScrollerHeight = 12; + +-enum { +- scrollMsg = 'scrl' +-}; +- + + BMenuScroller::BMenuScroller(BRect frame) + : + BView(frame, "menu scroller", 0, B_WILL_DRAW | B_FRAME_EVENTS + | B_FULL_UPDATE_ON_RESIZE), +- fEnabled(false), +- fMouseInside(false), +- fScrollRunner(NULL) ++ fEnabled(false) + { + SetViewUIColor(B_MENU_BACKGROUND_COLOR); + } + + +-BMenuScroller::~BMenuScroller() +-{ +- _StartScrolling(false); +-} +- +- + bool + BMenuScroller::IsEnabled() const + { +@@ -122,51 +95,6 @@ void + BMenuScroller::SetEnabled(bool enabled) + { + fEnabled = enabled; +- _StartScrolling(fEnabled && fMouseInside); +-} +- +- +-void +-BMenuScroller::MouseMoved(BPoint where, uint32 transit, +- const BMessage* dragMessage) +-{ +- switch (transit) { +- case B_ENTERED_VIEW: +- fMouseInside = true; +- if (fEnabled) _StartScrolling(true); +- break; +- case B_EXITED_VIEW: +- fMouseInside = false; +- if (fEnabled) _StartScrolling(false); +- break; +- } +-} +- +- +-void +-BMenuScroller::MessageReceived(BMessage* msg) +-{ +- switch (msg->what) { +- case scrollMsg: +- DoScroll(); +- break; +- default: +- BView::MessageReceived(msg); +- } +-} +- +- +-void +-BMenuScroller::_StartScrolling(bool doStart) +-{ +- if (doStart) { +- if (fScrollRunner == NULL) +- fScrollRunner = new (std::nothrow) BMessageRunner(BMessenger(this), new BMessage(scrollMsg), 5000, -1); +- } else { +- if (fScrollRunner != NULL) { +- delete fScrollRunner; fScrollRunner = NULL; +- } +- } + } + + +@@ -180,16 +108,6 @@ UpperScroller::UpperScroller(BRect frame) + } + + +-void +-UpperScroller::DoScroll() +-{ +- BMenuWindow* window = dynamic_cast(Window()); +- float smallStep; +- window->GetSteps(&smallStep, NULL); +- window->TryScrollBy(-smallStep); +-} +- +- + void + UpperScroller::Draw(BRect updateRect) + { +@@ -222,16 +140,6 @@ LowerScroller::LowerScroller(BRect frame) + } + + +-void +-LowerScroller::DoScroll() +-{ +- BMenuWindow* window = dynamic_cast(Window()); +- float smallStep; +- window->GetSteps(&smallStep, NULL); +- window->TryScrollBy(smallStep); +-} +- +- + void + LowerScroller::Draw(BRect updateRect) + { +@@ -483,6 +391,16 @@ BMenuWindow::HasScrollers() const + } + + ++bool ++BMenuWindow::CheckForScrolling(const BPoint &cursor) ++{ ++ if (!fMenuFrame || !fUpperScroller || !fLowerScroller) ++ return false; ++ ++ return _Scroll(cursor); ++} ++ ++ + bool + BMenuWindow::TryScrollBy(const float& step) + { +@@ -505,6 +423,35 @@ BMenuWindow::TryScrollTo(const float& where) + } + + ++bool ++BMenuWindow::_Scroll(const BPoint& where) ++{ ++ ASSERT((fLowerScroller != NULL)); ++ ASSERT((fUpperScroller != NULL)); ++ ++ const BPoint cursor = ConvertFromScreen(where); ++ const BRect &lowerFrame = fLowerScroller->Frame(); ++ const BRect &upperFrame = fUpperScroller->Frame(); ++ ++ int32 delta = 0; ++ if (fLowerScroller->IsEnabled() && lowerFrame.Contains(cursor)) ++ delta = 1; ++ else if (fUpperScroller->IsEnabled() && upperFrame.Contains(cursor)) ++ delta = -1; ++ ++ if (delta == 0) ++ return false; ++ ++ float smallStep; ++ GetSteps(&smallStep, NULL); ++ _ScrollBy(smallStep * delta); ++ ++ snooze(5000); ++ ++ return true; ++} ++ ++ + void + BMenuWindow::_ScrollBy(const float& step) + { +diff --git a/src/kits/interface/PopUpMenu.cpp b/src/kits/interface/PopUpMenu.cpp +index 892d938c9b..7b94b380ab 100644 +--- a/src/kits/interface/PopUpMenu.cpp ++++ b/src/kits/interface/PopUpMenu.cpp +@@ -429,10 +429,20 @@ BPopUpMenu::_StartTrack(BPoint where, bool autoInvoke, bool startOpened, + fWhere = where; + fUseWhere = true; + ++ // Determine when mouse-down-up will be taken as a 'press', ++ // rather than a 'click' ++ bigtime_t clickMaxTime = 0; ++ get_click_speed(&clickMaxTime); ++ clickMaxTime += system_time(); ++ + // Show the menu's window + Show(); ++ snooze(50000); + BMenuItem* result = Track(startOpened, _specialRect); + ++ // If it was a click, keep the menu open and tracking ++ if (system_time() <= clickMaxTime) ++ result = Track(true, _specialRect); + if (result != NULL && autoInvoke) + result->Invoke(); + +-- +2.30.2 + diff --git a/patchset-hrev55144/0052-libroot-os-implement-arch-specific-parts-for-riscv64.patch b/patchset-hrev55144/0052-libroot-os-implement-arch-specific-parts-for-riscv64.patch new file mode 100644 index 0000000..c82846d --- /dev/null +++ b/patchset-hrev55144/0052-libroot-os-implement-arch-specific-parts-for-riscv64.patch @@ -0,0 +1,316 @@ +From 437fabf302c12d523921b6749f6e44cbc2434101 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 17 May 2021 17:57:21 +0900 +Subject: libroot/os: implement arch-specific parts for riscv64 + +Change-Id: Idb6920b4c98a579a184e6a7e1976f2d8c7618dba +--- + src/system/libroot/os/arch/riscv64/Jamfile | 10 +++--- + .../libroot/os/arch/riscv64/stack_frame.S | 14 ++++++++ + .../libroot/os/arch/riscv64/stack_frame.c | 17 ---------- + .../libroot/os/arch/riscv64/syscalls.inc | 6 ++-- + .../libroot/os/arch/riscv64/system_time.c | 33 ------------------- + .../libroot/os/arch/riscv64/system_time.cpp | 32 ++++++++++++++++++ + src/system/libroot/os/arch/riscv64/thread.c | 9 ----- + src/system/libroot/os/arch/riscv64/thread.cpp | 19 +++++++++++ + .../os/arch/riscv64/{time.c => time.cpp} | 2 +- + .../os/arch/riscv64/{tls.c => tls.cpp} | 29 +++++++++------- + 10 files changed, 93 insertions(+), 78 deletions(-) + create mode 100644 src/system/libroot/os/arch/riscv64/stack_frame.S + delete mode 100644 src/system/libroot/os/arch/riscv64/stack_frame.c + delete mode 100644 src/system/libroot/os/arch/riscv64/system_time.c + create mode 100644 src/system/libroot/os/arch/riscv64/system_time.cpp + delete mode 100644 src/system/libroot/os/arch/riscv64/thread.c + create mode 100644 src/system/libroot/os/arch/riscv64/thread.cpp + rename src/system/libroot/os/arch/riscv64/{time.c => time.cpp} (99%) + rename src/system/libroot/os/arch/riscv64/{tls.c => tls.cpp} (61%) + +diff --git a/src/system/libroot/os/arch/riscv64/Jamfile b/src/system/libroot/os/arch/riscv64/Jamfile +index c12c9c6c41..57a3befd34 100644 +--- a/src/system/libroot/os/arch/riscv64/Jamfile ++++ b/src/system/libroot/os/arch/riscv64/Jamfile +@@ -15,12 +15,12 @@ for architectureObject in [ MultiArchSubDirSetup riscv64 ] { + MergeObject <$(architecture)>os_arch_$(TARGET_ARCH).o : + byteorder.S + +- stack_frame.c +- system_time.c ++ stack_frame.S ++ system_time.cpp + +- tls.c +- time.c +- thread.c ++ tls.cpp ++ time.cpp ++ thread.cpp + + generic_atomic.cpp + generic_stack_trace.cpp +diff --git a/src/system/libroot/os/arch/riscv64/stack_frame.S b/src/system/libroot/os/arch/riscv64/stack_frame.S +new file mode 100644 +index 0000000000..a7be0a1a7f +--- /dev/null ++++ b/src/system/libroot/os/arch/riscv64/stack_frame.S +@@ -0,0 +1,14 @@ ++/* ++ * Copyright 2021, Haiku, Inc. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++ ++#include ++ ++ ++/* void* get_stack_frame(void) */ ++FUNCTION(get_stack_frame): ++ mv a0, fp ++ ret ++FUNCTION_END(get_stack_frame) +diff --git a/src/system/libroot/os/arch/riscv64/stack_frame.c b/src/system/libroot/os/arch/riscv64/stack_frame.c +deleted file mode 100644 +index f063449176..0000000000 +--- a/src/system/libroot/os/arch/riscv64/stack_frame.c ++++ /dev/null +@@ -1,17 +0,0 @@ +-/* +- * Copyright 2008, Ingo Weinhold, ingo_weinhold@gmx.de. +- * Distributed under the terms of the MIT License. +-*/ +- +-#include +- +-#include +- +- +-void* +-get_stack_frame(void) +-{ +- // TODO: Implement! +- return NULL; +-} +- +diff --git a/src/system/libroot/os/arch/riscv64/syscalls.inc b/src/system/libroot/os/arch/riscv64/syscalls.inc +index 031585d2d7..76bee643a3 100644 +--- a/src/system/libroot/os/arch/riscv64/syscalls.inc ++++ b/src/system/libroot/os/arch/riscv64/syscalls.inc +@@ -3,12 +3,14 @@ + ** Distributed under the terms of the MIT License. + */ + +-/* TODO actuall syscalls? */ + #define _SYSCALL(name, n) \ + .globl name; \ + .type name,%function; \ + .align 4; \ +-name: ++name: \ ++ li t0, n; \ ++ ecall; \ ++ ret + + #define SYSCALL0(name, n) _SYSCALL(name, n) + #define SYSCALL1(name, n) _SYSCALL(name, n) +diff --git a/src/system/libroot/os/arch/riscv64/system_time.c b/src/system/libroot/os/arch/riscv64/system_time.c +deleted file mode 100644 +index fda8bd75e8..0000000000 +--- a/src/system/libroot/os/arch/riscv64/system_time.c ++++ /dev/null +@@ -1,33 +0,0 @@ +-/* +- * Copyright 2012, Haiku, Inc. +- * Distributed under the terms of the MIT License. +- * +- * Authors: +- * Franรงois Revol +- */ +- +-#include +- +-#include +-#include +-#include +- +-static vint32 *sConversionFactor; +- +-//XXX: this is a hack +-// remove me when platform code works +-static int64 +-__riscv64_get_time_base(void) +-{ +- static uint64 time_dilation_field = 0; +- return time_dilation_field++; +-} +- +-bigtime_t +-system_time(void) +-{ +- uint64 timeBase = __riscv64_get_time_base(); +- +- uint32 cv = sConversionFactor ? *sConversionFactor : 0; +- return (timeBase >> 32) * cv + (((timeBase & 0xffffffff) * cv) >> 32); +-} +diff --git a/src/system/libroot/os/arch/riscv64/system_time.cpp b/src/system/libroot/os/arch/riscv64/system_time.cpp +new file mode 100644 +index 0000000000..8ad65c6944 +--- /dev/null ++++ b/src/system/libroot/os/arch/riscv64/system_time.cpp +@@ -0,0 +1,32 @@ ++/* ++ * Copyright 2012, Haiku, Inc. ++ * Distributed under the terms of the MIT License. ++ * ++ * Authors: ++ * Franรงois Revol ++ */ ++ ++#include ++ ++#include ++#include ++#include ++ ++ ++bigtime_t ++system_time(void) ++{ ++ // TODO: units conversion ++ ++ // Currently TinyEMU implementation just use host system system_time() to ++ // implement `utime` register. Specification don't define units. ++ ++ // Spec says: The execution environment should provide a means of ++ // determining the period of the real-time counter (seconds/tick). ++ // The period must be constant. ++ ++ bigtime_t time; ++ asm volatile("csrr %0, time" : "=r" (time)); ++ return time; ++} ++ +diff --git a/src/system/libroot/os/arch/riscv64/thread.c b/src/system/libroot/os/arch/riscv64/thread.c +deleted file mode 100644 +index df90b6ad6a..0000000000 +--- a/src/system/libroot/os/arch/riscv64/thread.c ++++ /dev/null +@@ -1,9 +0,0 @@ +-#include +-#include "syscalls.h" +- +- +-thread_id +-find_thread(const char *name) +-{ +- return _kern_find_thread(name); +-} +diff --git a/src/system/libroot/os/arch/riscv64/thread.cpp b/src/system/libroot/os/arch/riscv64/thread.cpp +new file mode 100644 +index 0000000000..9cf65eac61 +--- /dev/null ++++ b/src/system/libroot/os/arch/riscv64/thread.cpp +@@ -0,0 +1,19 @@ ++/* ++ * Copyright 2021, Haiku, Inc. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++ ++#include ++#include "syscalls.h" ++#include ++ ++ ++thread_id ++find_thread(const char *name) ++{ ++ if (name == NULL) ++ return (thread_id)(addr_t)tls_get(TLS_THREAD_ID_SLOT); ++ ++ return _kern_find_thread(name); ++} +diff --git a/src/system/libroot/os/arch/riscv64/time.c b/src/system/libroot/os/arch/riscv64/time.cpp +similarity index 99% +rename from src/system/libroot/os/arch/riscv64/time.c +rename to src/system/libroot/os/arch/riscv64/time.cpp +index f365904c03..236080fc79 100644 +--- a/src/system/libroot/os/arch/riscv64/time.c ++++ b/src/system/libroot/os/arch/riscv64/time.cpp +@@ -1,4 +1,4 @@ +-/* ++/* + * Copyright 2006, Ingo Weinhold . + * Distributed under the terms of the MIT License. + */ +diff --git a/src/system/libroot/os/arch/riscv64/tls.c b/src/system/libroot/os/arch/riscv64/tls.cpp +similarity index 61% +rename from src/system/libroot/os/arch/riscv64/tls.c +rename to src/system/libroot/os/arch/riscv64/tls.cpp +index d840a8b692..f4fbd67adf 100644 +--- a/src/system/libroot/os/arch/riscv64/tls.c ++++ b/src/system/libroot/os/arch/riscv64/tls.cpp +@@ -14,44 +14,51 @@ struct tls_index { + unsigned long ti_offset; + }; + +-void* __tls_get_addr(struct tls_index* ti); ++extern "C" void* __tls_get_addr(struct tls_index* ti); + + static int32 gNextSlot = TLS_FIRST_FREE_SLOT; + + +-// TODO: RISCV64 has a dedicated (TP) register for TLS ++static inline void** ++get_tls() ++{ ++ void** tls; ++ __asm__ __volatile__ ("mv %0, tp" : "=r" (tls)); ++ return tls; ++} ++ + + int32 + tls_allocate(void) + { +- int32 next = atomic_add(&gNextSlot, 1); +- if (next >= TLS_MAX_KEYS) +- return B_NO_MEMORY; ++ if (gNextSlot < TLS_MAX_KEYS) { ++ int32 next = gNextSlot++; ++ if (next < TLS_MAX_KEYS) ++ return next; ++ } + +- return next; ++ return B_NO_MEMORY; + } + + + void * + tls_get(int32 index) + { +- debugger("Implement TLS support before SMP"); +- return NULL; ++ return get_tls()[index]; + } + + + void ** + tls_address(int32 index) + { +- debugger("Implement TLS support before SMP"); +- return NULL; ++ return get_tls() + index; + } + + + void + tls_set(int32 index, void *value) + { +- debugger("Implement TLS support before SMP"); ++ get_tls()[index] = value; + } + + +-- +2.30.2 + diff --git a/patchset-hrev55144/0053-drivers-vesa-fix-for-RISC-V.patch b/patchset-hrev55144/0053-drivers-vesa-fix-for-RISC-V.patch new file mode 100644 index 0000000..2f437bb --- /dev/null +++ b/patchset-hrev55144/0053-drivers-vesa-fix-for-RISC-V.patch @@ -0,0 +1,55 @@ +From e8f0a569dbae8856874742c594e2be15223183fd Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 24 May 2021 03:34:56 +0900 +Subject: drivers/vesa: fix for RISC-V + +Change-Id: I1f38f92d81fbfe47224893e1d9dbf6a74306e2f0 +--- + src/add-ons/kernel/drivers/graphics/vesa/driver.cpp | 7 ++++++- + src/add-ons/kernel/drivers/graphics/vesa/vesa.cpp | 2 +- + 2 files changed, 7 insertions(+), 2 deletions(-) + +diff --git a/src/add-ons/kernel/drivers/graphics/vesa/driver.cpp b/src/add-ons/kernel/drivers/graphics/vesa/driver.cpp +index 28cb549589..54070bb5e5 100644 +--- a/src/add-ons/kernel/drivers/graphics/vesa/driver.cpp ++++ b/src/add-ons/kernel/drivers/graphics/vesa/driver.cpp +@@ -68,9 +68,12 @@ init_driver(void) + + memset(gDeviceInfo[0], 0, sizeof(vesa_info)); + +- status_t status = get_module(B_ISA_MODULE_NAME, (module_info**)&gISA); ++ status_t status; ++#ifndef __riscv ++ status = get_module(B_ISA_MODULE_NAME, (module_info**)&gISA); + if (status != B_OK) + goto err1; ++#endif + + gDeviceNames[0] = strdup("graphics/vesa"); + if (gDeviceNames[0] == NULL) { +@@ -85,7 +88,9 @@ init_driver(void) + + err2: + put_module(B_ISA_MODULE_NAME); ++#ifndef __riscv + err1: ++#endif + free(gDeviceInfo[0]); + return status; + } +diff --git a/src/add-ons/kernel/drivers/graphics/vesa/vesa.cpp b/src/add-ons/kernel/drivers/graphics/vesa/vesa.cpp +index dc155aec29..5004c4b0be 100644 +--- a/src/add-ons/kernel/drivers/graphics/vesa/vesa.cpp ++++ b/src/add-ons/kernel/drivers/graphics/vesa/vesa.cpp +@@ -289,7 +289,7 @@ remap_frame_buffer(vesa_info& info, addr_t physicalBase, uint32 width, + if (!info.complete_frame_buffer_mapped) { + addr_t base = physicalBase; + size_t size = bytesPerRow * height; +- bool remap = !initializing; ++ bool remap = true; + + if (info.physical_frame_buffer_size != 0) { + // we can map the complete frame buffer +-- +2.30.2 + diff --git a/patchset-hrev55144/0054-lua-add.patch b/patchset-hrev55144/0054-lua-add.patch new file mode 100644 index 0000000..77e02d7 --- /dev/null +++ b/patchset-hrev55144/0054-lua-add.patch @@ -0,0 +1,30046 @@ +From 85f712c5eedaa39c551addd50ad1692e2b8806e0 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 24 May 2021 04:08:00 +0900 +Subject: lua: add + +Change-Id: I5ee6a7b9defb1465db41f03d4507f3afa4eec737 +--- + src/bin/Jamfile | 1 + + src/bin/lua/Jamfile | 39 + + src/bin/lua/lapi.c | 1455 ++++++++++++++++++++++++++++++ + src/bin/lua/lapi.h | 49 + + src/bin/lua/lauxlib.c | 1105 +++++++++++++++++++++++ + src/bin/lua/lauxlib.h | 293 ++++++ + src/bin/lua/lbaselib.c | 528 +++++++++++ + src/bin/lua/lcode.c | 1814 +++++++++++++++++++++++++++++++++++++ + src/bin/lua/lcode.h | 104 +++ + src/bin/lua/lcorolib.c | 210 +++++ + src/bin/lua/lctype.c | 64 ++ + src/bin/lua/lctype.h | 101 +++ + src/bin/lua/ldblib.c | 483 ++++++++++ + src/bin/lua/ldebug.c | 877 ++++++++++++++++++ + src/bin/lua/ldebug.h | 63 ++ + src/bin/lua/ldo.c | 963 ++++++++++++++++++++ + src/bin/lua/ldo.h | 79 ++ + src/bin/lua/ldump.c | 226 +++++ + src/bin/lua/lfunc.c | 294 ++++++ + src/bin/lua/lfunc.h | 64 ++ + src/bin/lua/lgc.c | 1728 +++++++++++++++++++++++++++++++++++ + src/bin/lua/lgc.h | 189 ++++ + src/bin/lua/linit.c | 65 ++ + src/bin/lua/liolib.c | 828 +++++++++++++++++ + src/bin/lua/ljumptab.h | 112 +++ + src/bin/lua/llex.c | 581 ++++++++++++ + src/bin/lua/llex.h | 91 ++ + src/bin/lua/llimits.h | 353 ++++++++ + src/bin/lua/lmathlib.c | 764 ++++++++++++++++ + src/bin/lua/lmem.c | 201 +++++ + src/bin/lua/lmem.h | 93 ++ + src/bin/lua/loadlib.c | 762 ++++++++++++++++ + src/bin/lua/lobject.c | 592 ++++++++++++ + src/bin/lua/lobject.h | 800 ++++++++++++++++ + src/bin/lua/lopcodes.c | 104 +++ + src/bin/lua/lopcodes.h | 392 ++++++++ + src/bin/lua/lopnames.h | 103 +++ + src/bin/lua/loslib.c | 430 +++++++++ + src/bin/lua/lparser.c | 1956 ++++++++++++++++++++++++++++++++++++++++ + src/bin/lua/lparser.h | 171 ++++ + src/bin/lua/lprefix.h | 45 + + src/bin/lua/lstate.c | 439 +++++++++ + src/bin/lua/lstate.h | 404 +++++++++ + src/bin/lua/lstring.c | 273 ++++++ + src/bin/lua/lstring.h | 57 ++ + src/bin/lua/lstrlib.c | 1817 +++++++++++++++++++++++++++++++++++++ + src/bin/lua/ltable.c | 971 ++++++++++++++++++++ + src/bin/lua/ltable.h | 66 ++ + src/bin/lua/ltablib.c | 429 +++++++++ + src/bin/lua/ltm.c | 271 ++++++ + src/bin/lua/ltm.h | 103 +++ + src/bin/lua/lua.c | 659 ++++++++++++++ + src/bin/lua/lua.h | 518 +++++++++++ + src/bin/lua/lua.hpp | 9 + + src/bin/lua/luac.c | 724 +++++++++++++++ + src/bin/lua/luaconf.h | 790 ++++++++++++++++ + src/bin/lua/lualib.h | 52 ++ + src/bin/lua/lundump.c | 333 +++++++ + src/bin/lua/lundump.h | 36 + + src/bin/lua/lutf8lib.c | 289 ++++++ + src/bin/lua/lvm.c | 1836 +++++++++++++++++++++++++++++++++++++ + src/bin/lua/lvm.h | 136 +++ + src/bin/lua/lzio.c | 68 ++ + src/bin/lua/lzio.h | 66 ++ + 64 files changed, 29518 insertions(+) + create mode 100644 src/bin/lua/Jamfile + create mode 100644 src/bin/lua/lapi.c + create mode 100644 src/bin/lua/lapi.h + create mode 100644 src/bin/lua/lauxlib.c + create mode 100644 src/bin/lua/lauxlib.h + create mode 100644 src/bin/lua/lbaselib.c + create mode 100644 src/bin/lua/lcode.c + create mode 100644 src/bin/lua/lcode.h + create mode 100644 src/bin/lua/lcorolib.c + create mode 100644 src/bin/lua/lctype.c + create mode 100644 src/bin/lua/lctype.h + create mode 100644 src/bin/lua/ldblib.c + create mode 100644 src/bin/lua/ldebug.c + create mode 100644 src/bin/lua/ldebug.h + create mode 100644 src/bin/lua/ldo.c + create mode 100644 src/bin/lua/ldo.h + create mode 100644 src/bin/lua/ldump.c + create mode 100644 src/bin/lua/lfunc.c + create mode 100644 src/bin/lua/lfunc.h + create mode 100644 src/bin/lua/lgc.c + create mode 100644 src/bin/lua/lgc.h + create mode 100644 src/bin/lua/linit.c + create mode 100644 src/bin/lua/liolib.c + create mode 100644 src/bin/lua/ljumptab.h + create mode 100644 src/bin/lua/llex.c + create mode 100644 src/bin/lua/llex.h + create mode 100644 src/bin/lua/llimits.h + create mode 100644 src/bin/lua/lmathlib.c + create mode 100644 src/bin/lua/lmem.c + create mode 100644 src/bin/lua/lmem.h + create mode 100644 src/bin/lua/loadlib.c + create mode 100644 src/bin/lua/lobject.c + create mode 100644 src/bin/lua/lobject.h + create mode 100644 src/bin/lua/lopcodes.c + create mode 100644 src/bin/lua/lopcodes.h + create mode 100644 src/bin/lua/lopnames.h + create mode 100644 src/bin/lua/loslib.c + create mode 100644 src/bin/lua/lparser.c + create mode 100644 src/bin/lua/lparser.h + create mode 100644 src/bin/lua/lprefix.h + create mode 100644 src/bin/lua/lstate.c + create mode 100644 src/bin/lua/lstate.h + create mode 100644 src/bin/lua/lstring.c + create mode 100644 src/bin/lua/lstring.h + create mode 100644 src/bin/lua/lstrlib.c + create mode 100644 src/bin/lua/ltable.c + create mode 100644 src/bin/lua/ltable.h + create mode 100644 src/bin/lua/ltablib.c + create mode 100644 src/bin/lua/ltm.c + create mode 100644 src/bin/lua/ltm.h + create mode 100644 src/bin/lua/lua.c + create mode 100644 src/bin/lua/lua.h + create mode 100644 src/bin/lua/lua.hpp + create mode 100644 src/bin/lua/luac.c + create mode 100644 src/bin/lua/luaconf.h + create mode 100644 src/bin/lua/lualib.h + create mode 100644 src/bin/lua/lundump.c + create mode 100644 src/bin/lua/lundump.h + create mode 100644 src/bin/lua/lutf8lib.c + create mode 100644 src/bin/lua/lvm.c + create mode 100644 src/bin/lua/lvm.h + create mode 100644 src/bin/lua/lzio.c + create mode 100644 src/bin/lua/lzio.h + +diff --git a/src/bin/Jamfile b/src/bin/Jamfile +index 3bf2496840..4fd2028d55 100644 +--- a/src/bin/Jamfile ++++ b/src/bin/Jamfile +@@ -277,6 +277,7 @@ SubInclude HAIKU_TOP src bin rc ; + SubInclude HAIKU_TOP src bin screen_blanker ; + SubInclude HAIKU_TOP src bin screenmode ; + SubInclude HAIKU_TOP src bin writembr ; ++SubInclude HAIKU_TOP src bin lua ; + + # debugging tools + SubInclude HAIKU_TOP src bin debug ; +diff --git a/src/bin/lua/Jamfile b/src/bin/lua/Jamfile +new file mode 100644 +index 0000000000..c4a06ee1f4 +--- /dev/null ++++ b/src/bin/lua/Jamfile +@@ -0,0 +1,39 @@ ++SubDir HAIKU_TOP src bin lua ; ++ ++DEFINES += LUA_USE_POSIX ; ++ ++BinCommand lua : ++ lapi.c ++ lauxlib.c ++ lbaselib.c ++ lcode.c ++ lcorolib.c ++ lctype.c ++ ldblib.c ++ ldebug.c ++ ldo.c ++ ldump.c ++ lfunc.c ++ lgc.c ++ linit.c ++ liolib.c ++ llex.c ++ lmathlib.c ++ lmem.c ++ loadlib.c ++ lobject.c ++ lopcodes.c ++ loslib.c ++ lparser.c ++ lstate.c ++ lstring.c ++ lstrlib.c ++ ltable.c ++ ltablib.c ++ ltm.c ++ lua.c ++ lundump.c ++ lutf8lib.c ++ lvm.c ++ lzio.c ++; +diff --git a/src/bin/lua/lapi.c b/src/bin/lua/lapi.c +new file mode 100644 +index 0000000000..f8f70cd008 +--- /dev/null ++++ b/src/bin/lua/lapi.c +@@ -0,0 +1,1455 @@ ++/* ++** $Id: lapi.c $ ++** Lua API ++** See Copyright Notice in lua.h ++*/ ++ ++#define lapi_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++#include ++ ++#include "lua.h" ++ ++#include "lapi.h" ++#include "ldebug.h" ++#include "ldo.h" ++#include "lfunc.h" ++#include "lgc.h" ++#include "lmem.h" ++#include "lobject.h" ++#include "lstate.h" ++#include "lstring.h" ++#include "ltable.h" ++#include "ltm.h" ++#include "lundump.h" ++#include "lvm.h" ++ ++ ++ ++const char lua_ident[] = ++ "$LuaVersion: " LUA_COPYRIGHT " $" ++ "$LuaAuthors: " LUA_AUTHORS " $"; ++ ++ ++ ++/* ++** Test for a valid index (one that is not the 'nilvalue'). ++** '!ttisnil(o)' implies 'o != &G(L)->nilvalue', so it is not needed. ++** However, it covers the most common cases in a faster way. ++*/ ++#define isvalid(L, o) (!ttisnil(o) || o != &G(L)->nilvalue) ++ ++ ++/* test for pseudo index */ ++#define ispseudo(i) ((i) <= LUA_REGISTRYINDEX) ++ ++/* test for upvalue */ ++#define isupvalue(i) ((i) < LUA_REGISTRYINDEX) ++ ++ ++static TValue *index2value (lua_State *L, int idx) { ++ CallInfo *ci = L->ci; ++ if (idx > 0) { ++ StkId o = ci->func + idx; ++ api_check(L, idx <= L->ci->top - (ci->func + 1), "unacceptable index"); ++ if (o >= L->top) return &G(L)->nilvalue; ++ else return s2v(o); ++ } ++ else if (!ispseudo(idx)) { /* negative index */ ++ api_check(L, idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index"); ++ return s2v(L->top + idx); ++ } ++ else if (idx == LUA_REGISTRYINDEX) ++ return &G(L)->l_registry; ++ else { /* upvalues */ ++ idx = LUA_REGISTRYINDEX - idx; ++ api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large"); ++ if (ttislcf(s2v(ci->func))) /* light C function? */ ++ return &G(L)->nilvalue; /* it has no upvalues */ ++ else { ++ CClosure *func = clCvalue(s2v(ci->func)); ++ return (idx <= func->nupvalues) ? &func->upvalue[idx-1] ++ : &G(L)->nilvalue; ++ } ++ } ++} ++ ++ ++static StkId index2stack (lua_State *L, int idx) { ++ CallInfo *ci = L->ci; ++ if (idx > 0) { ++ StkId o = ci->func + idx; ++ api_check(L, o < L->top, "unacceptable index"); ++ return o; ++ } ++ else { /* non-positive index */ ++ api_check(L, idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index"); ++ api_check(L, !ispseudo(idx), "invalid index"); ++ return L->top + idx; ++ } ++} ++ ++ ++LUA_API int lua_checkstack (lua_State *L, int n) { ++ int res; ++ CallInfo *ci; ++ lua_lock(L); ++ ci = L->ci; ++ api_check(L, n >= 0, "negative 'n'"); ++ if (L->stack_last - L->top > n) /* stack large enough? */ ++ res = 1; /* yes; check is OK */ ++ else { /* no; need to grow stack */ ++ int inuse = cast_int(L->top - L->stack) + EXTRA_STACK; ++ if (inuse > LUAI_MAXSTACK - n) /* can grow without overflow? */ ++ res = 0; /* no */ ++ else /* try to grow stack */ ++ res = luaD_growstack(L, n, 0); ++ } ++ if (res && ci->top < L->top + n) ++ ci->top = L->top + n; /* adjust frame top */ ++ lua_unlock(L); ++ return res; ++} ++ ++ ++LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) { ++ int i; ++ if (from == to) return; ++ lua_lock(to); ++ api_checknelems(from, n); ++ api_check(from, G(from) == G(to), "moving among independent states"); ++ api_check(from, to->ci->top - to->top >= n, "stack overflow"); ++ from->top -= n; ++ for (i = 0; i < n; i++) { ++ setobjs2s(to, to->top, from->top + i); ++ to->top++; /* stack already checked by previous 'api_check' */ ++ } ++ lua_unlock(to); ++} ++ ++ ++LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) { ++ lua_CFunction old; ++ lua_lock(L); ++ old = G(L)->panic; ++ G(L)->panic = panicf; ++ lua_unlock(L); ++ return old; ++} ++ ++ ++LUA_API lua_Number lua_version (lua_State *L) { ++ UNUSED(L); ++ return LUA_VERSION_NUM; ++} ++ ++ ++ ++/* ++** basic stack manipulation ++*/ ++ ++ ++/* ++** convert an acceptable stack index into an absolute index ++*/ ++LUA_API int lua_absindex (lua_State *L, int idx) { ++ return (idx > 0 || ispseudo(idx)) ++ ? idx ++ : cast_int(L->top - L->ci->func) + idx; ++} ++ ++ ++LUA_API int lua_gettop (lua_State *L) { ++ return cast_int(L->top - (L->ci->func + 1)); ++} ++ ++ ++LUA_API void lua_settop (lua_State *L, int idx) { ++ CallInfo *ci; ++ StkId func, newtop; ++ ptrdiff_t diff; /* difference for new top */ ++ lua_lock(L); ++ ci = L->ci; ++ func = ci->func; ++ if (idx >= 0) { ++ api_check(L, idx <= ci->top - (func + 1), "new top too large"); ++ diff = ((func + 1) + idx) - L->top; ++ for (; diff > 0; diff--) ++ setnilvalue(s2v(L->top++)); /* clear new slots */ ++ } ++ else { ++ api_check(L, -(idx+1) <= (L->top - (func + 1)), "invalid new top"); ++ diff = idx + 1; /* will "subtract" index (as it is negative) */ ++ } ++ api_check(L, L->tbclist < L->top, "previous pop of an unclosed slot"); ++ newtop = L->top + diff; ++ if (diff < 0 && L->tbclist >= newtop) { ++ lua_assert(hastocloseCfunc(ci->nresults)); ++ luaF_close(L, newtop, CLOSEKTOP, 0); ++ } ++ L->top = newtop; /* correct top only after closing any upvalue */ ++ lua_unlock(L); ++} ++ ++ ++LUA_API void lua_closeslot (lua_State *L, int idx) { ++ StkId level; ++ lua_lock(L); ++ level = index2stack(L, idx); ++ api_check(L, hastocloseCfunc(L->ci->nresults) && L->tbclist == level, ++ "no variable to close at given level"); ++ luaF_close(L, level, CLOSEKTOP, 0); ++ level = index2stack(L, idx); /* stack may be moved */ ++ setnilvalue(s2v(level)); ++ lua_unlock(L); ++} ++ ++ ++/* ++** Reverse the stack segment from 'from' to 'to' ++** (auxiliary to 'lua_rotate') ++** Note that we move(copy) only the value inside the stack. ++** (We do not move additional fields that may exist.) ++*/ ++static void reverse (lua_State *L, StkId from, StkId to) { ++ for (; from < to; from++, to--) { ++ TValue temp; ++ setobj(L, &temp, s2v(from)); ++ setobjs2s(L, from, to); ++ setobj2s(L, to, &temp); ++ } ++} ++ ++ ++/* ++** Let x = AB, where A is a prefix of length 'n'. Then, ++** rotate x n == BA. But BA == (A^r . B^r)^r. ++*/ ++LUA_API void lua_rotate (lua_State *L, int idx, int n) { ++ StkId p, t, m; ++ lua_lock(L); ++ t = L->top - 1; /* end of stack segment being rotated */ ++ p = index2stack(L, idx); /* start of segment */ ++ api_check(L, (n >= 0 ? n : -n) <= (t - p + 1), "invalid 'n'"); ++ m = (n >= 0 ? t - n : p - n - 1); /* end of prefix */ ++ reverse(L, p, m); /* reverse the prefix with length 'n' */ ++ reverse(L, m + 1, t); /* reverse the suffix */ ++ reverse(L, p, t); /* reverse the entire segment */ ++ lua_unlock(L); ++} ++ ++ ++LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) { ++ TValue *fr, *to; ++ lua_lock(L); ++ fr = index2value(L, fromidx); ++ to = index2value(L, toidx); ++ api_check(L, isvalid(L, to), "invalid index"); ++ setobj(L, to, fr); ++ if (isupvalue(toidx)) /* function upvalue? */ ++ luaC_barrier(L, clCvalue(s2v(L->ci->func)), fr); ++ /* LUA_REGISTRYINDEX does not need gc barrier ++ (collector revisits it before finishing collection) */ ++ lua_unlock(L); ++} ++ ++ ++LUA_API void lua_pushvalue (lua_State *L, int idx) { ++ lua_lock(L); ++ setobj2s(L, L->top, index2value(L, idx)); ++ api_incr_top(L); ++ lua_unlock(L); ++} ++ ++ ++ ++/* ++** access functions (stack -> C) ++*/ ++ ++ ++LUA_API int lua_type (lua_State *L, int idx) { ++ const TValue *o = index2value(L, idx); ++ return (isvalid(L, o) ? ttype(o) : LUA_TNONE); ++} ++ ++ ++LUA_API const char *lua_typename (lua_State *L, int t) { ++ UNUSED(L); ++ api_check(L, LUA_TNONE <= t && t < LUA_NUMTYPES, "invalid type"); ++ return ttypename(t); ++} ++ ++ ++LUA_API int lua_iscfunction (lua_State *L, int idx) { ++ const TValue *o = index2value(L, idx); ++ return (ttislcf(o) || (ttisCclosure(o))); ++} ++ ++ ++LUA_API int lua_isinteger (lua_State *L, int idx) { ++ const TValue *o = index2value(L, idx); ++ return ttisinteger(o); ++} ++ ++ ++LUA_API int lua_isnumber (lua_State *L, int idx) { ++ lua_Number n; ++ const TValue *o = index2value(L, idx); ++ return tonumber(o, &n); ++} ++ ++ ++LUA_API int lua_isstring (lua_State *L, int idx) { ++ const TValue *o = index2value(L, idx); ++ return (ttisstring(o) || cvt2str(o)); ++} ++ ++ ++LUA_API int lua_isuserdata (lua_State *L, int idx) { ++ const TValue *o = index2value(L, idx); ++ return (ttisfulluserdata(o) || ttislightuserdata(o)); ++} ++ ++ ++LUA_API int lua_rawequal (lua_State *L, int index1, int index2) { ++ const TValue *o1 = index2value(L, index1); ++ const TValue *o2 = index2value(L, index2); ++ return (isvalid(L, o1) && isvalid(L, o2)) ? luaV_rawequalobj(o1, o2) : 0; ++} ++ ++ ++LUA_API void lua_arith (lua_State *L, int op) { ++ lua_lock(L); ++ if (op != LUA_OPUNM && op != LUA_OPBNOT) ++ api_checknelems(L, 2); /* all other operations expect two operands */ ++ else { /* for unary operations, add fake 2nd operand */ ++ api_checknelems(L, 1); ++ setobjs2s(L, L->top, L->top - 1); ++ api_incr_top(L); ++ } ++ /* first operand at top - 2, second at top - 1; result go to top - 2 */ ++ luaO_arith(L, op, s2v(L->top - 2), s2v(L->top - 1), L->top - 2); ++ L->top--; /* remove second operand */ ++ lua_unlock(L); ++} ++ ++ ++LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) { ++ const TValue *o1; ++ const TValue *o2; ++ int i = 0; ++ lua_lock(L); /* may call tag method */ ++ o1 = index2value(L, index1); ++ o2 = index2value(L, index2); ++ if (isvalid(L, o1) && isvalid(L, o2)) { ++ switch (op) { ++ case LUA_OPEQ: i = luaV_equalobj(L, o1, o2); break; ++ case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break; ++ case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break; ++ default: api_check(L, 0, "invalid option"); ++ } ++ } ++ lua_unlock(L); ++ return i; ++} ++ ++ ++LUA_API size_t lua_stringtonumber (lua_State *L, const char *s) { ++ size_t sz = luaO_str2num(s, s2v(L->top)); ++ if (sz != 0) ++ api_incr_top(L); ++ return sz; ++} ++ ++ ++LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) { ++ lua_Number n = 0; ++ const TValue *o = index2value(L, idx); ++ int isnum = tonumber(o, &n); ++ if (pisnum) ++ *pisnum = isnum; ++ return n; ++} ++ ++ ++LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *pisnum) { ++ lua_Integer res = 0; ++ const TValue *o = index2value(L, idx); ++ int isnum = tointeger(o, &res); ++ if (pisnum) ++ *pisnum = isnum; ++ return res; ++} ++ ++ ++LUA_API int lua_toboolean (lua_State *L, int idx) { ++ const TValue *o = index2value(L, idx); ++ return !l_isfalse(o); ++} ++ ++ ++LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) { ++ TValue *o; ++ lua_lock(L); ++ o = index2value(L, idx); ++ if (!ttisstring(o)) { ++ if (!cvt2str(o)) { /* not convertible? */ ++ if (len != NULL) *len = 0; ++ lua_unlock(L); ++ return NULL; ++ } ++ luaO_tostring(L, o); ++ luaC_checkGC(L); ++ o = index2value(L, idx); /* previous call may reallocate the stack */ ++ } ++ if (len != NULL) ++ *len = vslen(o); ++ lua_unlock(L); ++ return svalue(o); ++} ++ ++ ++LUA_API lua_Unsigned lua_rawlen (lua_State *L, int idx) { ++ const TValue *o = index2value(L, idx); ++ switch (ttypetag(o)) { ++ case LUA_VSHRSTR: return tsvalue(o)->shrlen; ++ case LUA_VLNGSTR: return tsvalue(o)->u.lnglen; ++ case LUA_VUSERDATA: return uvalue(o)->len; ++ case LUA_VTABLE: return luaH_getn(hvalue(o)); ++ default: return 0; ++ } ++} ++ ++ ++LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) { ++ const TValue *o = index2value(L, idx); ++ if (ttislcf(o)) return fvalue(o); ++ else if (ttisCclosure(o)) ++ return clCvalue(o)->f; ++ else return NULL; /* not a C function */ ++} ++ ++ ++static void *touserdata (const TValue *o) { ++ switch (ttype(o)) { ++ case LUA_TUSERDATA: return getudatamem(uvalue(o)); ++ case LUA_TLIGHTUSERDATA: return pvalue(o); ++ default: return NULL; ++ } ++} ++ ++ ++LUA_API void *lua_touserdata (lua_State *L, int idx) { ++ const TValue *o = index2value(L, idx); ++ return touserdata(o); ++} ++ ++ ++LUA_API lua_State *lua_tothread (lua_State *L, int idx) { ++ const TValue *o = index2value(L, idx); ++ return (!ttisthread(o)) ? NULL : thvalue(o); ++} ++ ++ ++/* ++** Returns a pointer to the internal representation of an object. ++** Note that ANSI C does not allow the conversion of a pointer to ++** function to a 'void*', so the conversion here goes through ++** a 'size_t'. (As the returned pointer is only informative, this ++** conversion should not be a problem.) ++*/ ++LUA_API const void *lua_topointer (lua_State *L, int idx) { ++ const TValue *o = index2value(L, idx); ++ switch (ttypetag(o)) { ++ case LUA_VLCF: return cast_voidp(cast_sizet(fvalue(o))); ++ case LUA_VUSERDATA: case LUA_VLIGHTUSERDATA: ++ return touserdata(o); ++ default: { ++ if (iscollectable(o)) ++ return gcvalue(o); ++ else ++ return NULL; ++ } ++ } ++} ++ ++ ++ ++/* ++** push functions (C -> stack) ++*/ ++ ++ ++LUA_API void lua_pushnil (lua_State *L) { ++ lua_lock(L); ++ setnilvalue(s2v(L->top)); ++ api_incr_top(L); ++ lua_unlock(L); ++} ++ ++ ++LUA_API void lua_pushnumber (lua_State *L, lua_Number n) { ++ lua_lock(L); ++ setfltvalue(s2v(L->top), n); ++ api_incr_top(L); ++ lua_unlock(L); ++} ++ ++ ++LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) { ++ lua_lock(L); ++ setivalue(s2v(L->top), n); ++ api_incr_top(L); ++ lua_unlock(L); ++} ++ ++ ++/* ++** Pushes on the stack a string with given length. Avoid using 's' when ++** 'len' == 0 (as 's' can be NULL in that case), due to later use of ++** 'memcmp' and 'memcpy'. ++*/ ++LUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) { ++ TString *ts; ++ lua_lock(L); ++ ts = (len == 0) ? luaS_new(L, "") : luaS_newlstr(L, s, len); ++ setsvalue2s(L, L->top, ts); ++ api_incr_top(L); ++ luaC_checkGC(L); ++ lua_unlock(L); ++ return getstr(ts); ++} ++ ++ ++LUA_API const char *lua_pushstring (lua_State *L, const char *s) { ++ lua_lock(L); ++ if (s == NULL) ++ setnilvalue(s2v(L->top)); ++ else { ++ TString *ts; ++ ts = luaS_new(L, s); ++ setsvalue2s(L, L->top, ts); ++ s = getstr(ts); /* internal copy's address */ ++ } ++ api_incr_top(L); ++ luaC_checkGC(L); ++ lua_unlock(L); ++ return s; ++} ++ ++ ++LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt, ++ va_list argp) { ++ const char *ret; ++ lua_lock(L); ++ ret = luaO_pushvfstring(L, fmt, argp); ++ luaC_checkGC(L); ++ lua_unlock(L); ++ return ret; ++} ++ ++ ++LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) { ++ const char *ret; ++ va_list argp; ++ lua_lock(L); ++ va_start(argp, fmt); ++ ret = luaO_pushvfstring(L, fmt, argp); ++ va_end(argp); ++ luaC_checkGC(L); ++ lua_unlock(L); ++ return ret; ++} ++ ++ ++LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) { ++ lua_lock(L); ++ if (n == 0) { ++ setfvalue(s2v(L->top), fn); ++ api_incr_top(L); ++ } ++ else { ++ CClosure *cl; ++ api_checknelems(L, n); ++ api_check(L, n <= MAXUPVAL, "upvalue index too large"); ++ cl = luaF_newCclosure(L, n); ++ cl->f = fn; ++ L->top -= n; ++ while (n--) { ++ setobj2n(L, &cl->upvalue[n], s2v(L->top + n)); ++ /* does not need barrier because closure is white */ ++ lua_assert(iswhite(cl)); ++ } ++ setclCvalue(L, s2v(L->top), cl); ++ api_incr_top(L); ++ luaC_checkGC(L); ++ } ++ lua_unlock(L); ++} ++ ++ ++LUA_API void lua_pushboolean (lua_State *L, int b) { ++ lua_lock(L); ++ if (b) ++ setbtvalue(s2v(L->top)); ++ else ++ setbfvalue(s2v(L->top)); ++ api_incr_top(L); ++ lua_unlock(L); ++} ++ ++ ++LUA_API void lua_pushlightuserdata (lua_State *L, void *p) { ++ lua_lock(L); ++ setpvalue(s2v(L->top), p); ++ api_incr_top(L); ++ lua_unlock(L); ++} ++ ++ ++LUA_API int lua_pushthread (lua_State *L) { ++ lua_lock(L); ++ setthvalue(L, s2v(L->top), L); ++ api_incr_top(L); ++ lua_unlock(L); ++ return (G(L)->mainthread == L); ++} ++ ++ ++ ++/* ++** get functions (Lua -> stack) ++*/ ++ ++ ++static int auxgetstr (lua_State *L, const TValue *t, const char *k) { ++ const TValue *slot; ++ TString *str = luaS_new(L, k); ++ if (luaV_fastget(L, t, str, slot, luaH_getstr)) { ++ setobj2s(L, L->top, slot); ++ api_incr_top(L); ++ } ++ else { ++ setsvalue2s(L, L->top, str); ++ api_incr_top(L); ++ luaV_finishget(L, t, s2v(L->top - 1), L->top - 1, slot); ++ } ++ lua_unlock(L); ++ return ttype(s2v(L->top - 1)); ++} ++ ++ ++/* ++** Get the global table in the registry. Since all predefined ++** indices in the registry were inserted right when the registry ++** was created and never removed, they must always be in the array ++** part of the registry. ++*/ ++#define getGtable(L) \ ++ (&hvalue(&G(L)->l_registry)->array[LUA_RIDX_GLOBALS - 1]) ++ ++ ++LUA_API int lua_getglobal (lua_State *L, const char *name) { ++ const TValue *G; ++ lua_lock(L); ++ G = getGtable(L); ++ return auxgetstr(L, G, name); ++} ++ ++ ++LUA_API int lua_gettable (lua_State *L, int idx) { ++ const TValue *slot; ++ TValue *t; ++ lua_lock(L); ++ t = index2value(L, idx); ++ if (luaV_fastget(L, t, s2v(L->top - 1), slot, luaH_get)) { ++ setobj2s(L, L->top - 1, slot); ++ } ++ else ++ luaV_finishget(L, t, s2v(L->top - 1), L->top - 1, slot); ++ lua_unlock(L); ++ return ttype(s2v(L->top - 1)); ++} ++ ++ ++LUA_API int lua_getfield (lua_State *L, int idx, const char *k) { ++ lua_lock(L); ++ return auxgetstr(L, index2value(L, idx), k); ++} ++ ++ ++LUA_API int lua_geti (lua_State *L, int idx, lua_Integer n) { ++ TValue *t; ++ const TValue *slot; ++ lua_lock(L); ++ t = index2value(L, idx); ++ if (luaV_fastgeti(L, t, n, slot)) { ++ setobj2s(L, L->top, slot); ++ } ++ else { ++ TValue aux; ++ setivalue(&aux, n); ++ luaV_finishget(L, t, &aux, L->top, slot); ++ } ++ api_incr_top(L); ++ lua_unlock(L); ++ return ttype(s2v(L->top - 1)); ++} ++ ++ ++static int finishrawget (lua_State *L, const TValue *val) { ++ if (isempty(val)) /* avoid copying empty items to the stack */ ++ setnilvalue(s2v(L->top)); ++ else ++ setobj2s(L, L->top, val); ++ api_incr_top(L); ++ lua_unlock(L); ++ return ttype(s2v(L->top - 1)); ++} ++ ++ ++static Table *gettable (lua_State *L, int idx) { ++ TValue *t = index2value(L, idx); ++ api_check(L, ttistable(t), "table expected"); ++ return hvalue(t); ++} ++ ++ ++LUA_API int lua_rawget (lua_State *L, int idx) { ++ Table *t; ++ const TValue *val; ++ lua_lock(L); ++ api_checknelems(L, 1); ++ t = gettable(L, idx); ++ val = luaH_get(t, s2v(L->top - 1)); ++ L->top--; /* remove key */ ++ return finishrawget(L, val); ++} ++ ++ ++LUA_API int lua_rawgeti (lua_State *L, int idx, lua_Integer n) { ++ Table *t; ++ lua_lock(L); ++ t = gettable(L, idx); ++ return finishrawget(L, luaH_getint(t, n)); ++} ++ ++ ++LUA_API int lua_rawgetp (lua_State *L, int idx, const void *p) { ++ Table *t; ++ TValue k; ++ lua_lock(L); ++ t = gettable(L, idx); ++ setpvalue(&k, cast_voidp(p)); ++ return finishrawget(L, luaH_get(t, &k)); ++} ++ ++ ++LUA_API void lua_createtable (lua_State *L, int narray, int nrec) { ++ Table *t; ++ lua_lock(L); ++ t = luaH_new(L); ++ sethvalue2s(L, L->top, t); ++ api_incr_top(L); ++ if (narray > 0 || nrec > 0) ++ luaH_resize(L, t, narray, nrec); ++ luaC_checkGC(L); ++ lua_unlock(L); ++} ++ ++ ++LUA_API int lua_getmetatable (lua_State *L, int objindex) { ++ const TValue *obj; ++ Table *mt; ++ int res = 0; ++ lua_lock(L); ++ obj = index2value(L, objindex); ++ switch (ttype(obj)) { ++ case LUA_TTABLE: ++ mt = hvalue(obj)->metatable; ++ break; ++ case LUA_TUSERDATA: ++ mt = uvalue(obj)->metatable; ++ break; ++ default: ++ mt = G(L)->mt[ttype(obj)]; ++ break; ++ } ++ if (mt != NULL) { ++ sethvalue2s(L, L->top, mt); ++ api_incr_top(L); ++ res = 1; ++ } ++ lua_unlock(L); ++ return res; ++} ++ ++ ++LUA_API int lua_getiuservalue (lua_State *L, int idx, int n) { ++ TValue *o; ++ int t; ++ lua_lock(L); ++ o = index2value(L, idx); ++ api_check(L, ttisfulluserdata(o), "full userdata expected"); ++ if (n <= 0 || n > uvalue(o)->nuvalue) { ++ setnilvalue(s2v(L->top)); ++ t = LUA_TNONE; ++ } ++ else { ++ setobj2s(L, L->top, &uvalue(o)->uv[n - 1].uv); ++ t = ttype(s2v(L->top)); ++ } ++ api_incr_top(L); ++ lua_unlock(L); ++ return t; ++} ++ ++ ++/* ++** set functions (stack -> Lua) ++*/ ++ ++/* ++** t[k] = value at the top of the stack (where 'k' is a string) ++*/ ++static void auxsetstr (lua_State *L, const TValue *t, const char *k) { ++ const TValue *slot; ++ TString *str = luaS_new(L, k); ++ api_checknelems(L, 1); ++ if (luaV_fastget(L, t, str, slot, luaH_getstr)) { ++ luaV_finishfastset(L, t, slot, s2v(L->top - 1)); ++ L->top--; /* pop value */ ++ } ++ else { ++ setsvalue2s(L, L->top, str); /* push 'str' (to make it a TValue) */ ++ api_incr_top(L); ++ luaV_finishset(L, t, s2v(L->top - 1), s2v(L->top - 2), slot); ++ L->top -= 2; /* pop value and key */ ++ } ++ lua_unlock(L); /* lock done by caller */ ++} ++ ++ ++LUA_API void lua_setglobal (lua_State *L, const char *name) { ++ const TValue *G; ++ lua_lock(L); /* unlock done in 'auxsetstr' */ ++ G = getGtable(L); ++ auxsetstr(L, G, name); ++} ++ ++ ++LUA_API void lua_settable (lua_State *L, int idx) { ++ TValue *t; ++ const TValue *slot; ++ lua_lock(L); ++ api_checknelems(L, 2); ++ t = index2value(L, idx); ++ if (luaV_fastget(L, t, s2v(L->top - 2), slot, luaH_get)) { ++ luaV_finishfastset(L, t, slot, s2v(L->top - 1)); ++ } ++ else ++ luaV_finishset(L, t, s2v(L->top - 2), s2v(L->top - 1), slot); ++ L->top -= 2; /* pop index and value */ ++ lua_unlock(L); ++} ++ ++ ++LUA_API void lua_setfield (lua_State *L, int idx, const char *k) { ++ lua_lock(L); /* unlock done in 'auxsetstr' */ ++ auxsetstr(L, index2value(L, idx), k); ++} ++ ++ ++LUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) { ++ TValue *t; ++ const TValue *slot; ++ lua_lock(L); ++ api_checknelems(L, 1); ++ t = index2value(L, idx); ++ if (luaV_fastgeti(L, t, n, slot)) { ++ luaV_finishfastset(L, t, slot, s2v(L->top - 1)); ++ } ++ else { ++ TValue aux; ++ setivalue(&aux, n); ++ luaV_finishset(L, t, &aux, s2v(L->top - 1), slot); ++ } ++ L->top--; /* pop value */ ++ lua_unlock(L); ++} ++ ++ ++static void aux_rawset (lua_State *L, int idx, TValue *key, int n) { ++ Table *t; ++ lua_lock(L); ++ api_checknelems(L, n); ++ t = gettable(L, idx); ++ luaH_set(L, t, key, s2v(L->top - 1)); ++ invalidateTMcache(t); ++ luaC_barrierback(L, obj2gco(t), s2v(L->top - 1)); ++ L->top -= n; ++ lua_unlock(L); ++} ++ ++ ++LUA_API void lua_rawset (lua_State *L, int idx) { ++ aux_rawset(L, idx, s2v(L->top - 2), 2); ++} ++ ++ ++LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) { ++ TValue k; ++ setpvalue(&k, cast_voidp(p)); ++ aux_rawset(L, idx, &k, 1); ++} ++ ++ ++LUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) { ++ Table *t; ++ lua_lock(L); ++ api_checknelems(L, 1); ++ t = gettable(L, idx); ++ luaH_setint(L, t, n, s2v(L->top - 1)); ++ luaC_barrierback(L, obj2gco(t), s2v(L->top - 1)); ++ L->top--; ++ lua_unlock(L); ++} ++ ++ ++LUA_API int lua_setmetatable (lua_State *L, int objindex) { ++ TValue *obj; ++ Table *mt; ++ lua_lock(L); ++ api_checknelems(L, 1); ++ obj = index2value(L, objindex); ++ if (ttisnil(s2v(L->top - 1))) ++ mt = NULL; ++ else { ++ api_check(L, ttistable(s2v(L->top - 1)), "table expected"); ++ mt = hvalue(s2v(L->top - 1)); ++ } ++ switch (ttype(obj)) { ++ case LUA_TTABLE: { ++ hvalue(obj)->metatable = mt; ++ if (mt) { ++ luaC_objbarrier(L, gcvalue(obj), mt); ++ luaC_checkfinalizer(L, gcvalue(obj), mt); ++ } ++ break; ++ } ++ case LUA_TUSERDATA: { ++ uvalue(obj)->metatable = mt; ++ if (mt) { ++ luaC_objbarrier(L, uvalue(obj), mt); ++ luaC_checkfinalizer(L, gcvalue(obj), mt); ++ } ++ break; ++ } ++ default: { ++ G(L)->mt[ttype(obj)] = mt; ++ break; ++ } ++ } ++ L->top--; ++ lua_unlock(L); ++ return 1; ++} ++ ++ ++LUA_API int lua_setiuservalue (lua_State *L, int idx, int n) { ++ TValue *o; ++ int res; ++ lua_lock(L); ++ api_checknelems(L, 1); ++ o = index2value(L, idx); ++ api_check(L, ttisfulluserdata(o), "full userdata expected"); ++ if (!(cast_uint(n) - 1u < cast_uint(uvalue(o)->nuvalue))) ++ res = 0; /* 'n' not in [1, uvalue(o)->nuvalue] */ ++ else { ++ setobj(L, &uvalue(o)->uv[n - 1].uv, s2v(L->top - 1)); ++ luaC_barrierback(L, gcvalue(o), s2v(L->top - 1)); ++ res = 1; ++ } ++ L->top--; ++ lua_unlock(L); ++ return res; ++} ++ ++ ++/* ++** 'load' and 'call' functions (run Lua code) ++*/ ++ ++ ++#define checkresults(L,na,nr) \ ++ api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)), \ ++ "results from function overflow current stack size") ++ ++ ++LUA_API void lua_callk (lua_State *L, int nargs, int nresults, ++ lua_KContext ctx, lua_KFunction k) { ++ StkId func; ++ lua_lock(L); ++ api_check(L, k == NULL || !isLua(L->ci), ++ "cannot use continuations inside hooks"); ++ api_checknelems(L, nargs+1); ++ api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread"); ++ checkresults(L, nargs, nresults); ++ func = L->top - (nargs+1); ++ if (k != NULL && yieldable(L)) { /* need to prepare continuation? */ ++ L->ci->u.c.k = k; /* save continuation */ ++ L->ci->u.c.ctx = ctx; /* save context */ ++ luaD_call(L, func, nresults); /* do the call */ ++ } ++ else /* no continuation or no yieldable */ ++ luaD_callnoyield(L, func, nresults); /* just do the call */ ++ adjustresults(L, nresults); ++ lua_unlock(L); ++} ++ ++ ++ ++/* ++** Execute a protected call. ++*/ ++struct CallS { /* data to 'f_call' */ ++ StkId func; ++ int nresults; ++}; ++ ++ ++static void f_call (lua_State *L, void *ud) { ++ struct CallS *c = cast(struct CallS *, ud); ++ luaD_callnoyield(L, c->func, c->nresults); ++} ++ ++ ++ ++LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc, ++ lua_KContext ctx, lua_KFunction k) { ++ struct CallS c; ++ int status; ++ ptrdiff_t func; ++ lua_lock(L); ++ api_check(L, k == NULL || !isLua(L->ci), ++ "cannot use continuations inside hooks"); ++ api_checknelems(L, nargs+1); ++ api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread"); ++ checkresults(L, nargs, nresults); ++ if (errfunc == 0) ++ func = 0; ++ else { ++ StkId o = index2stack(L, errfunc); ++ api_check(L, ttisfunction(s2v(o)), "error handler must be a function"); ++ func = savestack(L, o); ++ } ++ c.func = L->top - (nargs+1); /* function to be called */ ++ if (k == NULL || !yieldable(L)) { /* no continuation or no yieldable? */ ++ c.nresults = nresults; /* do a 'conventional' protected call */ ++ status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func); ++ } ++ else { /* prepare continuation (call is already protected by 'resume') */ ++ CallInfo *ci = L->ci; ++ ci->u.c.k = k; /* save continuation */ ++ ci->u.c.ctx = ctx; /* save context */ ++ /* save information for error recovery */ ++ ci->u2.funcidx = cast_int(savestack(L, c.func)); ++ ci->u.c.old_errfunc = L->errfunc; ++ L->errfunc = func; ++ setoah(ci->callstatus, L->allowhook); /* save value of 'allowhook' */ ++ ci->callstatus |= CIST_YPCALL; /* function can do error recovery */ ++ luaD_call(L, c.func, nresults); /* do the call */ ++ ci->callstatus &= ~CIST_YPCALL; ++ L->errfunc = ci->u.c.old_errfunc; ++ status = LUA_OK; /* if it is here, there were no errors */ ++ } ++ adjustresults(L, nresults); ++ lua_unlock(L); ++ return status; ++} ++ ++ ++LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data, ++ const char *chunkname, const char *mode) { ++ ZIO z; ++ int status; ++ lua_lock(L); ++ if (!chunkname) chunkname = "?"; ++ luaZ_init(L, &z, reader, data); ++ status = luaD_protectedparser(L, &z, chunkname, mode); ++ if (status == LUA_OK) { /* no errors? */ ++ LClosure *f = clLvalue(s2v(L->top - 1)); /* get newly created function */ ++ if (f->nupvalues >= 1) { /* does it have an upvalue? */ ++ /* get global table from registry */ ++ const TValue *gt = getGtable(L); ++ /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */ ++ setobj(L, f->upvals[0]->v, gt); ++ luaC_barrier(L, f->upvals[0], gt); ++ } ++ } ++ lua_unlock(L); ++ return status; ++} ++ ++ ++LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip) { ++ int status; ++ TValue *o; ++ lua_lock(L); ++ api_checknelems(L, 1); ++ o = s2v(L->top - 1); ++ if (isLfunction(o)) ++ status = luaU_dump(L, getproto(o), writer, data, strip); ++ else ++ status = 1; ++ lua_unlock(L); ++ return status; ++} ++ ++ ++LUA_API int lua_status (lua_State *L) { ++ return L->status; ++} ++ ++ ++/* ++** Garbage-collection function ++*/ ++LUA_API int lua_gc (lua_State *L, int what, ...) { ++ va_list argp; ++ int res = 0; ++ global_State *g; ++ lua_lock(L); ++ g = G(L); ++ va_start(argp, what); ++ switch (what) { ++ case LUA_GCSTOP: { ++ g->gcrunning = 0; ++ break; ++ } ++ case LUA_GCRESTART: { ++ luaE_setdebt(g, 0); ++ g->gcrunning = 1; ++ break; ++ } ++ case LUA_GCCOLLECT: { ++ luaC_fullgc(L, 0); ++ break; ++ } ++ case LUA_GCCOUNT: { ++ /* GC values are expressed in Kbytes: #bytes/2^10 */ ++ res = cast_int(gettotalbytes(g) >> 10); ++ break; ++ } ++ case LUA_GCCOUNTB: { ++ res = cast_int(gettotalbytes(g) & 0x3ff); ++ break; ++ } ++ case LUA_GCSTEP: { ++ int data = va_arg(argp, int); ++ l_mem debt = 1; /* =1 to signal that it did an actual step */ ++ lu_byte oldrunning = g->gcrunning; ++ g->gcrunning = 1; /* allow GC to run */ ++ if (data == 0) { ++ luaE_setdebt(g, 0); /* do a basic step */ ++ luaC_step(L); ++ } ++ else { /* add 'data' to total debt */ ++ debt = cast(l_mem, data) * 1024 + g->GCdebt; ++ luaE_setdebt(g, debt); ++ luaC_checkGC(L); ++ } ++ g->gcrunning = oldrunning; /* restore previous state */ ++ if (debt > 0 && g->gcstate == GCSpause) /* end of cycle? */ ++ res = 1; /* signal it */ ++ break; ++ } ++ case LUA_GCSETPAUSE: { ++ int data = va_arg(argp, int); ++ res = getgcparam(g->gcpause); ++ setgcparam(g->gcpause, data); ++ break; ++ } ++ case LUA_GCSETSTEPMUL: { ++ int data = va_arg(argp, int); ++ res = getgcparam(g->gcstepmul); ++ setgcparam(g->gcstepmul, data); ++ break; ++ } ++ case LUA_GCISRUNNING: { ++ res = g->gcrunning; ++ break; ++ } ++ case LUA_GCGEN: { ++ int minormul = va_arg(argp, int); ++ int majormul = va_arg(argp, int); ++ res = isdecGCmodegen(g) ? LUA_GCGEN : LUA_GCINC; ++ if (minormul != 0) ++ g->genminormul = minormul; ++ if (majormul != 0) ++ setgcparam(g->genmajormul, majormul); ++ luaC_changemode(L, KGC_GEN); ++ break; ++ } ++ case LUA_GCINC: { ++ int pause = va_arg(argp, int); ++ int stepmul = va_arg(argp, int); ++ int stepsize = va_arg(argp, int); ++ res = isdecGCmodegen(g) ? LUA_GCGEN : LUA_GCINC; ++ if (pause != 0) ++ setgcparam(g->gcpause, pause); ++ if (stepmul != 0) ++ setgcparam(g->gcstepmul, stepmul); ++ if (stepsize != 0) ++ g->gcstepsize = stepsize; ++ luaC_changemode(L, KGC_INC); ++ break; ++ } ++ default: res = -1; /* invalid option */ ++ } ++ va_end(argp); ++ lua_unlock(L); ++ return res; ++} ++ ++ ++ ++/* ++** miscellaneous functions ++*/ ++ ++ ++LUA_API int lua_error (lua_State *L) { ++ TValue *errobj; ++ lua_lock(L); ++ errobj = s2v(L->top - 1); ++ api_checknelems(L, 1); ++ /* error object is the memory error message? */ ++ if (ttisshrstring(errobj) && eqshrstr(tsvalue(errobj), G(L)->memerrmsg)) ++ luaM_error(L); /* raise a memory error */ ++ else ++ luaG_errormsg(L); /* raise a regular error */ ++ /* code unreachable; will unlock when control actually leaves the kernel */ ++ return 0; /* to avoid warnings */ ++} ++ ++ ++LUA_API int lua_next (lua_State *L, int idx) { ++ Table *t; ++ int more; ++ lua_lock(L); ++ api_checknelems(L, 1); ++ t = gettable(L, idx); ++ more = luaH_next(L, t, L->top - 1); ++ if (more) { ++ api_incr_top(L); ++ } ++ else /* no more elements */ ++ L->top -= 1; /* remove key */ ++ lua_unlock(L); ++ return more; ++} ++ ++ ++LUA_API void lua_toclose (lua_State *L, int idx) { ++ int nresults; ++ StkId o; ++ lua_lock(L); ++ o = index2stack(L, idx); ++ nresults = L->ci->nresults; ++ api_check(L, L->tbclist < o, "given index below or equal a marked one"); ++ luaF_newtbcupval(L, o); /* create new to-be-closed upvalue */ ++ if (!hastocloseCfunc(nresults)) /* function not marked yet? */ ++ L->ci->nresults = codeNresults(nresults); /* mark it */ ++ lua_assert(hastocloseCfunc(L->ci->nresults)); ++ lua_unlock(L); ++} ++ ++ ++LUA_API void lua_concat (lua_State *L, int n) { ++ lua_lock(L); ++ api_checknelems(L, n); ++ if (n > 0) ++ luaV_concat(L, n); ++ else { /* nothing to concatenate */ ++ setsvalue2s(L, L->top, luaS_newlstr(L, "", 0)); /* push empty string */ ++ api_incr_top(L); ++ } ++ luaC_checkGC(L); ++ lua_unlock(L); ++} ++ ++ ++LUA_API void lua_len (lua_State *L, int idx) { ++ TValue *t; ++ lua_lock(L); ++ t = index2value(L, idx); ++ luaV_objlen(L, L->top, t); ++ api_incr_top(L); ++ lua_unlock(L); ++} ++ ++ ++LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) { ++ lua_Alloc f; ++ lua_lock(L); ++ if (ud) *ud = G(L)->ud; ++ f = G(L)->frealloc; ++ lua_unlock(L); ++ return f; ++} ++ ++ ++LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) { ++ lua_lock(L); ++ G(L)->ud = ud; ++ G(L)->frealloc = f; ++ lua_unlock(L); ++} ++ ++ ++void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud) { ++ lua_lock(L); ++ G(L)->ud_warn = ud; ++ G(L)->warnf = f; ++ lua_unlock(L); ++} ++ ++ ++void lua_warning (lua_State *L, const char *msg, int tocont) { ++ lua_lock(L); ++ luaE_warning(L, msg, tocont); ++ lua_unlock(L); ++} ++ ++ ++ ++LUA_API void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue) { ++ Udata *u; ++ lua_lock(L); ++ api_check(L, 0 <= nuvalue && nuvalue < USHRT_MAX, "invalid value"); ++ u = luaS_newudata(L, size, nuvalue); ++ setuvalue(L, s2v(L->top), u); ++ api_incr_top(L); ++ luaC_checkGC(L); ++ lua_unlock(L); ++ return getudatamem(u); ++} ++ ++ ++ ++static const char *aux_upvalue (TValue *fi, int n, TValue **val, ++ GCObject **owner) { ++ switch (ttypetag(fi)) { ++ case LUA_VCCL: { /* C closure */ ++ CClosure *f = clCvalue(fi); ++ if (!(cast_uint(n) - 1u < cast_uint(f->nupvalues))) ++ return NULL; /* 'n' not in [1, f->nupvalues] */ ++ *val = &f->upvalue[n-1]; ++ if (owner) *owner = obj2gco(f); ++ return ""; ++ } ++ case LUA_VLCL: { /* Lua closure */ ++ LClosure *f = clLvalue(fi); ++ TString *name; ++ Proto *p = f->p; ++ if (!(cast_uint(n) - 1u < cast_uint(p->sizeupvalues))) ++ return NULL; /* 'n' not in [1, p->sizeupvalues] */ ++ *val = f->upvals[n-1]->v; ++ if (owner) *owner = obj2gco(f->upvals[n - 1]); ++ name = p->upvalues[n-1].name; ++ return (name == NULL) ? "(no name)" : getstr(name); ++ } ++ default: return NULL; /* not a closure */ ++ } ++} ++ ++ ++LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) { ++ const char *name; ++ TValue *val = NULL; /* to avoid warnings */ ++ lua_lock(L); ++ name = aux_upvalue(index2value(L, funcindex), n, &val, NULL); ++ if (name) { ++ setobj2s(L, L->top, val); ++ api_incr_top(L); ++ } ++ lua_unlock(L); ++ return name; ++} ++ ++ ++LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) { ++ const char *name; ++ TValue *val = NULL; /* to avoid warnings */ ++ GCObject *owner = NULL; /* to avoid warnings */ ++ TValue *fi; ++ lua_lock(L); ++ fi = index2value(L, funcindex); ++ api_checknelems(L, 1); ++ name = aux_upvalue(fi, n, &val, &owner); ++ if (name) { ++ L->top--; ++ setobj(L, val, s2v(L->top)); ++ luaC_barrier(L, owner, val); ++ } ++ lua_unlock(L); ++ return name; ++} ++ ++ ++static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) { ++ static const UpVal *const nullup = NULL; ++ LClosure *f; ++ TValue *fi = index2value(L, fidx); ++ api_check(L, ttisLclosure(fi), "Lua function expected"); ++ f = clLvalue(fi); ++ if (pf) *pf = f; ++ if (1 <= n && n <= f->p->sizeupvalues) ++ return &f->upvals[n - 1]; /* get its upvalue pointer */ ++ else ++ return (UpVal**)&nullup; ++} ++ ++ ++LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) { ++ TValue *fi = index2value(L, fidx); ++ switch (ttypetag(fi)) { ++ case LUA_VLCL: { /* lua closure */ ++ return *getupvalref(L, fidx, n, NULL); ++ } ++ case LUA_VCCL: { /* C closure */ ++ CClosure *f = clCvalue(fi); ++ if (1 <= n && n <= f->nupvalues) ++ return &f->upvalue[n - 1]; ++ /* else */ ++ } /* FALLTHROUGH */ ++ case LUA_VLCF: ++ return NULL; /* light C functions have no upvalues */ ++ default: { ++ api_check(L, 0, "function expected"); ++ return NULL; ++ } ++ } ++} ++ ++ ++LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1, ++ int fidx2, int n2) { ++ LClosure *f1; ++ UpVal **up1 = getupvalref(L, fidx1, n1, &f1); ++ UpVal **up2 = getupvalref(L, fidx2, n2, NULL); ++ api_check(L, *up1 != NULL && *up2 != NULL, "invalid upvalue index"); ++ *up1 = *up2; ++ luaC_objbarrier(L, f1, *up1); ++} ++ ++ +diff --git a/src/bin/lua/lapi.h b/src/bin/lua/lapi.h +new file mode 100644 +index 0000000000..9e99cc4482 +--- /dev/null ++++ b/src/bin/lua/lapi.h +@@ -0,0 +1,49 @@ ++/* ++** $Id: lapi.h $ ++** Auxiliary functions from Lua API ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef lapi_h ++#define lapi_h ++ ++ ++#include "llimits.h" ++#include "lstate.h" ++ ++ ++/* Increments 'L->top', checking for stack overflows */ ++#define api_incr_top(L) {L->top++; api_check(L, L->top <= L->ci->top, \ ++ "stack overflow");} ++ ++ ++/* ++** If a call returns too many multiple returns, the callee may not have ++** stack space to accommodate all results. In this case, this macro ++** increases its stack space ('L->ci->top'). ++*/ ++#define adjustresults(L,nres) \ ++ { if ((nres) <= LUA_MULTRET && L->ci->top < L->top) L->ci->top = L->top; } ++ ++ ++/* Ensure the stack has at least 'n' elements */ ++#define api_checknelems(L,n) api_check(L, (n) < (L->top - L->ci->func), \ ++ "not enough elements in the stack") ++ ++ ++/* ++** To reduce the overhead of returning from C functions, the presence of ++** to-be-closed variables in these functions is coded in the CallInfo's ++** field 'nresults', in a way that functions with no to-be-closed variables ++** with zero, one, or "all" wanted results have no overhead. Functions ++** with other number of wanted results, as well as functions with ++** variables to be closed, have an extra check. ++*/ ++ ++#define hastocloseCfunc(n) ((n) < LUA_MULTRET) ++ ++/* Map [-1, inf) (range of 'nresults') into (-inf, -2] */ ++#define codeNresults(n) (-(n) - 3) ++#define decodeNresults(n) (-(n) - 3) ++ ++#endif +diff --git a/src/bin/lua/lauxlib.c b/src/bin/lua/lauxlib.c +new file mode 100644 +index 0000000000..94835ef934 +--- /dev/null ++++ b/src/bin/lua/lauxlib.c +@@ -0,0 +1,1105 @@ ++/* ++** $Id: lauxlib.c $ ++** Auxiliary functions for building Lua libraries ++** See Copyright Notice in lua.h ++*/ ++ ++#define lauxlib_c ++#define LUA_LIB ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++#include ++#include ++#include ++ ++ ++/* ++** This file uses only the official API of Lua. ++** Any function declared here could be written as an application function. ++*/ ++ ++#include "lua.h" ++ ++#include "lauxlib.h" ++ ++ ++#if !defined(MAX_SIZET) ++/* maximum value for size_t */ ++#define MAX_SIZET ((size_t)(~(size_t)0)) ++#endif ++ ++ ++/* ++** {====================================================== ++** Traceback ++** ======================================================= ++*/ ++ ++ ++#define LEVELS1 10 /* size of the first part of the stack */ ++#define LEVELS2 11 /* size of the second part of the stack */ ++ ++ ++ ++/* ++** Search for 'objidx' in table at index -1. ('objidx' must be an ++** absolute index.) Return 1 + string at top if it found a good name. ++*/ ++static int findfield (lua_State *L, int objidx, int level) { ++ if (level == 0 || !lua_istable(L, -1)) ++ return 0; /* not found */ ++ lua_pushnil(L); /* start 'next' loop */ ++ while (lua_next(L, -2)) { /* for each pair in table */ ++ if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */ ++ if (lua_rawequal(L, objidx, -1)) { /* found object? */ ++ lua_pop(L, 1); /* remove value (but keep name) */ ++ return 1; ++ } ++ else if (findfield(L, objidx, level - 1)) { /* try recursively */ ++ /* stack: lib_name, lib_table, field_name (top) */ ++ lua_pushliteral(L, "."); /* place '.' between the two names */ ++ lua_replace(L, -3); /* (in the slot occupied by table) */ ++ lua_concat(L, 3); /* lib_name.field_name */ ++ return 1; ++ } ++ } ++ lua_pop(L, 1); /* remove value */ ++ } ++ return 0; /* not found */ ++} ++ ++ ++/* ++** Search for a name for a function in all loaded modules ++*/ ++static int pushglobalfuncname (lua_State *L, lua_Debug *ar) { ++ int top = lua_gettop(L); ++ lua_getinfo(L, "f", ar); /* push function */ ++ lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); ++ if (findfield(L, top + 1, 2)) { ++ const char *name = lua_tostring(L, -1); ++ if (strncmp(name, LUA_GNAME ".", 3) == 0) { /* name start with '_G.'? */ ++ lua_pushstring(L, name + 3); /* push name without prefix */ ++ lua_remove(L, -2); /* remove original name */ ++ } ++ lua_copy(L, -1, top + 1); /* copy name to proper place */ ++ lua_settop(L, top + 1); /* remove table "loaded" and name copy */ ++ return 1; ++ } ++ else { ++ lua_settop(L, top); /* remove function and global table */ ++ return 0; ++ } ++} ++ ++ ++static void pushfuncname (lua_State *L, lua_Debug *ar) { ++ if (pushglobalfuncname(L, ar)) { /* try first a global name */ ++ lua_pushfstring(L, "function '%s'", lua_tostring(L, -1)); ++ lua_remove(L, -2); /* remove name */ ++ } ++ else if (*ar->namewhat != '\0') /* is there a name from code? */ ++ lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */ ++ else if (*ar->what == 'm') /* main? */ ++ lua_pushliteral(L, "main chunk"); ++ else if (*ar->what != 'C') /* for Lua functions, use */ ++ lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined); ++ else /* nothing left... */ ++ lua_pushliteral(L, "?"); ++} ++ ++ ++static int lastlevel (lua_State *L) { ++ lua_Debug ar; ++ int li = 1, le = 1; ++ /* find an upper bound */ ++ while (lua_getstack(L, le, &ar)) { li = le; le *= 2; } ++ /* do a binary search */ ++ while (li < le) { ++ int m = (li + le)/2; ++ if (lua_getstack(L, m, &ar)) li = m + 1; ++ else le = m; ++ } ++ return le - 1; ++} ++ ++ ++LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, ++ const char *msg, int level) { ++ luaL_Buffer b; ++ lua_Debug ar; ++ int last = lastlevel(L1); ++ int limit2show = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1; ++ luaL_buffinit(L, &b); ++ if (msg) { ++ luaL_addstring(&b, msg); ++ luaL_addchar(&b, '\n'); ++ } ++ luaL_addstring(&b, "stack traceback:"); ++ while (lua_getstack(L1, level++, &ar)) { ++ if (limit2show-- == 0) { /* too many levels? */ ++ int n = last - level - LEVELS2 + 1; /* number of levels to skip */ ++ lua_pushfstring(L, "\n\t...\t(skipping %d levels)", n); ++ luaL_addvalue(&b); /* add warning about skip */ ++ level += n; /* and skip to last levels */ ++ } ++ else { ++ lua_getinfo(L1, "Slnt", &ar); ++ if (ar.currentline <= 0) ++ lua_pushfstring(L, "\n\t%s: in ", ar.short_src); ++ else ++ lua_pushfstring(L, "\n\t%s:%d: in ", ar.short_src, ar.currentline); ++ luaL_addvalue(&b); ++ pushfuncname(L, &ar); ++ luaL_addvalue(&b); ++ if (ar.istailcall) ++ luaL_addstring(&b, "\n\t(...tail calls...)"); ++ } ++ } ++ luaL_pushresult(&b); ++} ++ ++/* }====================================================== */ ++ ++ ++/* ++** {====================================================== ++** Error-report functions ++** ======================================================= ++*/ ++ ++LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) { ++ lua_Debug ar; ++ if (!lua_getstack(L, 0, &ar)) /* no stack frame? */ ++ return luaL_error(L, "bad argument #%d (%s)", arg, extramsg); ++ lua_getinfo(L, "n", &ar); ++ if (strcmp(ar.namewhat, "method") == 0) { ++ arg--; /* do not count 'self' */ ++ if (arg == 0) /* error is in the self argument itself? */ ++ return luaL_error(L, "calling '%s' on bad self (%s)", ++ ar.name, extramsg); ++ } ++ if (ar.name == NULL) ++ ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?"; ++ return luaL_error(L, "bad argument #%d to '%s' (%s)", ++ arg, ar.name, extramsg); ++} ++ ++ ++LUALIB_API int luaL_typeerror (lua_State *L, int arg, const char *tname) { ++ const char *msg; ++ const char *typearg; /* name for the type of the actual argument */ ++ if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING) ++ typearg = lua_tostring(L, -1); /* use the given type name */ ++ else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA) ++ typearg = "light userdata"; /* special name for messages */ ++ else ++ typearg = luaL_typename(L, arg); /* standard name */ ++ msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg); ++ return luaL_argerror(L, arg, msg); ++} ++ ++ ++static void tag_error (lua_State *L, int arg, int tag) { ++ luaL_typeerror(L, arg, lua_typename(L, tag)); ++} ++ ++ ++/* ++** The use of 'lua_pushfstring' ensures this function does not ++** need reserved stack space when called. ++*/ ++LUALIB_API void luaL_where (lua_State *L, int level) { ++ lua_Debug ar; ++ if (lua_getstack(L, level, &ar)) { /* check function at level */ ++ lua_getinfo(L, "Sl", &ar); /* get info about it */ ++ if (ar.currentline > 0) { /* is there info? */ ++ lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline); ++ return; ++ } ++ } ++ lua_pushfstring(L, ""); /* else, no information available... */ ++} ++ ++ ++/* ++** Again, the use of 'lua_pushvfstring' ensures this function does ++** not need reserved stack space when called. (At worst, it generates ++** an error with "stack overflow" instead of the given message.) ++*/ ++LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) { ++ va_list argp; ++ va_start(argp, fmt); ++ luaL_where(L, 1); ++ lua_pushvfstring(L, fmt, argp); ++ va_end(argp); ++ lua_concat(L, 2); ++ return lua_error(L); ++} ++ ++ ++LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) { ++ int en = errno; /* calls to Lua API may change this value */ ++ if (stat) { ++ lua_pushboolean(L, 1); ++ return 1; ++ } ++ else { ++ luaL_pushfail(L); ++ if (fname) ++ lua_pushfstring(L, "%s: %s", fname, strerror(en)); ++ else ++ lua_pushstring(L, strerror(en)); ++ lua_pushinteger(L, en); ++ return 3; ++ } ++} ++ ++ ++#if !defined(l_inspectstat) /* { */ ++ ++#if defined(LUA_USE_POSIX) ++ ++#include ++ ++/* ++** use appropriate macros to interpret 'pclose' return status ++*/ ++#define l_inspectstat(stat,what) \ ++ if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \ ++ else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; } ++ ++#else ++ ++#define l_inspectstat(stat,what) /* no op */ ++ ++#endif ++ ++#endif /* } */ ++ ++ ++LUALIB_API int luaL_execresult (lua_State *L, int stat) { ++ if (stat != 0 && errno != 0) /* error with an 'errno'? */ ++ return luaL_fileresult(L, 0, NULL); ++ else { ++ const char *what = "exit"; /* type of termination */ ++ l_inspectstat(stat, what); /* interpret result */ ++ if (*what == 'e' && stat == 0) /* successful termination? */ ++ lua_pushboolean(L, 1); ++ else ++ luaL_pushfail(L); ++ lua_pushstring(L, what); ++ lua_pushinteger(L, stat); ++ return 3; /* return true/fail,what,code */ ++ } ++} ++ ++/* }====================================================== */ ++ ++ ++ ++/* ++** {====================================================== ++** Userdata's metatable manipulation ++** ======================================================= ++*/ ++ ++LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { ++ if (luaL_getmetatable(L, tname) != LUA_TNIL) /* name already in use? */ ++ return 0; /* leave previous value on top, but return 0 */ ++ lua_pop(L, 1); ++ lua_createtable(L, 0, 2); /* create metatable */ ++ lua_pushstring(L, tname); ++ lua_setfield(L, -2, "__name"); /* metatable.__name = tname */ ++ lua_pushvalue(L, -1); ++ lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */ ++ return 1; ++} ++ ++ ++LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) { ++ luaL_getmetatable(L, tname); ++ lua_setmetatable(L, -2); ++} ++ ++ ++LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) { ++ void *p = lua_touserdata(L, ud); ++ if (p != NULL) { /* value is a userdata? */ ++ if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ ++ luaL_getmetatable(L, tname); /* get correct metatable */ ++ if (!lua_rawequal(L, -1, -2)) /* not the same? */ ++ p = NULL; /* value is a userdata with wrong metatable */ ++ lua_pop(L, 2); /* remove both metatables */ ++ return p; ++ } ++ } ++ return NULL; /* value is not a userdata with a metatable */ ++} ++ ++ ++LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { ++ void *p = luaL_testudata(L, ud, tname); ++ luaL_argexpected(L, p != NULL, ud, tname); ++ return p; ++} ++ ++/* }====================================================== */ ++ ++ ++/* ++** {====================================================== ++** Argument check functions ++** ======================================================= ++*/ ++ ++LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def, ++ const char *const lst[]) { ++ const char *name = (def) ? luaL_optstring(L, arg, def) : ++ luaL_checkstring(L, arg); ++ int i; ++ for (i=0; lst[i]; i++) ++ if (strcmp(lst[i], name) == 0) ++ return i; ++ return luaL_argerror(L, arg, ++ lua_pushfstring(L, "invalid option '%s'", name)); ++} ++ ++ ++/* ++** Ensures the stack has at least 'space' extra slots, raising an error ++** if it cannot fulfill the request. (The error handling needs a few ++** extra slots to format the error message. In case of an error without ++** this extra space, Lua will generate the same 'stack overflow' error, ++** but without 'msg'.) ++*/ ++LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) { ++ if (l_unlikely(!lua_checkstack(L, space))) { ++ if (msg) ++ luaL_error(L, "stack overflow (%s)", msg); ++ else ++ luaL_error(L, "stack overflow"); ++ } ++} ++ ++ ++LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) { ++ if (l_unlikely(lua_type(L, arg) != t)) ++ tag_error(L, arg, t); ++} ++ ++ ++LUALIB_API void luaL_checkany (lua_State *L, int arg) { ++ if (l_unlikely(lua_type(L, arg) == LUA_TNONE)) ++ luaL_argerror(L, arg, "value expected"); ++} ++ ++ ++LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) { ++ const char *s = lua_tolstring(L, arg, len); ++ if (l_unlikely(!s)) tag_error(L, arg, LUA_TSTRING); ++ return s; ++} ++ ++ ++LUALIB_API const char *luaL_optlstring (lua_State *L, int arg, ++ const char *def, size_t *len) { ++ if (lua_isnoneornil(L, arg)) { ++ if (len) ++ *len = (def ? strlen(def) : 0); ++ return def; ++ } ++ else return luaL_checklstring(L, arg, len); ++} ++ ++ ++LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) { ++ int isnum; ++ lua_Number d = lua_tonumberx(L, arg, &isnum); ++ if (l_unlikely(!isnum)) ++ tag_error(L, arg, LUA_TNUMBER); ++ return d; ++} ++ ++ ++LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) { ++ return luaL_opt(L, luaL_checknumber, arg, def); ++} ++ ++ ++static void interror (lua_State *L, int arg) { ++ if (lua_isnumber(L, arg)) ++ luaL_argerror(L, arg, "number has no integer representation"); ++ else ++ tag_error(L, arg, LUA_TNUMBER); ++} ++ ++ ++LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) { ++ int isnum; ++ lua_Integer d = lua_tointegerx(L, arg, &isnum); ++ if (l_unlikely(!isnum)) { ++ interror(L, arg); ++ } ++ return d; ++} ++ ++ ++LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg, ++ lua_Integer def) { ++ return luaL_opt(L, luaL_checkinteger, arg, def); ++} ++ ++/* }====================================================== */ ++ ++ ++/* ++** {====================================================== ++** Generic Buffer manipulation ++** ======================================================= ++*/ ++ ++/* userdata to box arbitrary data */ ++typedef struct UBox { ++ void *box; ++ size_t bsize; ++} UBox; ++ ++ ++static void *resizebox (lua_State *L, int idx, size_t newsize) { ++ void *ud; ++ lua_Alloc allocf = lua_getallocf(L, &ud); ++ UBox *box = (UBox *)lua_touserdata(L, idx); ++ void *temp = allocf(ud, box->box, box->bsize, newsize); ++ if (l_unlikely(temp == NULL && newsize > 0)) { /* allocation error? */ ++ lua_pushliteral(L, "not enough memory"); ++ lua_error(L); /* raise a memory error */ ++ } ++ box->box = temp; ++ box->bsize = newsize; ++ return temp; ++} ++ ++ ++static int boxgc (lua_State *L) { ++ resizebox(L, 1, 0); ++ return 0; ++} ++ ++ ++static const luaL_Reg boxmt[] = { /* box metamethods */ ++ {"__gc", boxgc}, ++ {"__close", boxgc}, ++ {NULL, NULL} ++}; ++ ++ ++static void newbox (lua_State *L) { ++ UBox *box = (UBox *)lua_newuserdatauv(L, sizeof(UBox), 0); ++ box->box = NULL; ++ box->bsize = 0; ++ if (luaL_newmetatable(L, "_UBOX*")) /* creating metatable? */ ++ luaL_setfuncs(L, boxmt, 0); /* set its metamethods */ ++ lua_setmetatable(L, -2); ++} ++ ++ ++/* ++** check whether buffer is using a userdata on the stack as a temporary ++** buffer ++*/ ++#define buffonstack(B) ((B)->b != (B)->init.b) ++ ++ ++/* ++** Whenever buffer is accessed, slot 'idx' must either be a box (which ++** cannot be NULL) or it is a placeholder for the buffer. ++*/ ++#define checkbufferlevel(B,idx) \ ++ lua_assert(buffonstack(B) ? lua_touserdata(B->L, idx) != NULL \ ++ : lua_touserdata(B->L, idx) == (void*)B) ++ ++ ++/* ++** Compute new size for buffer 'B', enough to accommodate extra 'sz' ++** bytes. ++*/ ++static size_t newbuffsize (luaL_Buffer *B, size_t sz) { ++ size_t newsize = B->size * 2; /* double buffer size */ ++ if (l_unlikely(MAX_SIZET - sz < B->n)) /* overflow in (B->n + sz)? */ ++ return luaL_error(B->L, "buffer too large"); ++ if (newsize < B->n + sz) /* double is not big enough? */ ++ newsize = B->n + sz; ++ return newsize; ++} ++ ++ ++/* ++** Returns a pointer to a free area with at least 'sz' bytes in buffer ++** 'B'. 'boxidx' is the relative position in the stack where is the ++** buffer's box or its placeholder. ++*/ ++static char *prepbuffsize (luaL_Buffer *B, size_t sz, int boxidx) { ++ checkbufferlevel(B, boxidx); ++ if (B->size - B->n >= sz) /* enough space? */ ++ return B->b + B->n; ++ else { ++ lua_State *L = B->L; ++ char *newbuff; ++ size_t newsize = newbuffsize(B, sz); ++ /* create larger buffer */ ++ if (buffonstack(B)) /* buffer already has a box? */ ++ newbuff = (char *)resizebox(L, boxidx, newsize); /* resize it */ ++ else { /* no box yet */ ++ lua_remove(L, boxidx); /* remove placeholder */ ++ newbox(L); /* create a new box */ ++ lua_insert(L, boxidx); /* move box to its intended position */ ++ lua_toclose(L, boxidx); ++ newbuff = (char *)resizebox(L, boxidx, newsize); ++ memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */ ++ } ++ B->b = newbuff; ++ B->size = newsize; ++ return newbuff + B->n; ++ } ++} ++ ++/* ++** returns a pointer to a free area with at least 'sz' bytes ++*/ ++LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) { ++ return prepbuffsize(B, sz, -1); ++} ++ ++ ++LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) { ++ if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */ ++ char *b = prepbuffsize(B, l, -1); ++ memcpy(b, s, l * sizeof(char)); ++ luaL_addsize(B, l); ++ } ++} ++ ++ ++LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) { ++ luaL_addlstring(B, s, strlen(s)); ++} ++ ++ ++LUALIB_API void luaL_pushresult (luaL_Buffer *B) { ++ lua_State *L = B->L; ++ checkbufferlevel(B, -1); ++ lua_pushlstring(L, B->b, B->n); ++ if (buffonstack(B)) ++ lua_closeslot(L, -2); /* close the box */ ++ lua_remove(L, -2); /* remove box or placeholder from the stack */ ++} ++ ++ ++LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) { ++ luaL_addsize(B, sz); ++ luaL_pushresult(B); ++} ++ ++ ++/* ++** 'luaL_addvalue' is the only function in the Buffer system where the ++** box (if existent) is not on the top of the stack. So, instead of ++** calling 'luaL_addlstring', it replicates the code using -2 as the ++** last argument to 'prepbuffsize', signaling that the box is (or will ++** be) bellow the string being added to the buffer. (Box creation can ++** trigger an emergency GC, so we should not remove the string from the ++** stack before we have the space guaranteed.) ++*/ ++LUALIB_API void luaL_addvalue (luaL_Buffer *B) { ++ lua_State *L = B->L; ++ size_t len; ++ const char *s = lua_tolstring(L, -1, &len); ++ char *b = prepbuffsize(B, len, -2); ++ memcpy(b, s, len * sizeof(char)); ++ luaL_addsize(B, len); ++ lua_pop(L, 1); /* pop string */ ++} ++ ++ ++LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) { ++ B->L = L; ++ B->b = B->init.b; ++ B->n = 0; ++ B->size = LUAL_BUFFERSIZE; ++ lua_pushlightuserdata(L, (void*)B); /* push placeholder */ ++} ++ ++ ++LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) { ++ luaL_buffinit(L, B); ++ return prepbuffsize(B, sz, -1); ++} ++ ++/* }====================================================== */ ++ ++ ++/* ++** {====================================================== ++** Reference system ++** ======================================================= ++*/ ++ ++/* index of free-list header (after the predefined values) */ ++#define freelist (LUA_RIDX_LAST + 1) ++ ++/* ++** The previously freed references form a linked list: ++** t[freelist] is the index of a first free index, or zero if list is ++** empty; t[t[freelist]] is the index of the second element; etc. ++*/ ++LUALIB_API int luaL_ref (lua_State *L, int t) { ++ int ref; ++ if (lua_isnil(L, -1)) { ++ lua_pop(L, 1); /* remove from stack */ ++ return LUA_REFNIL; /* 'nil' has a unique fixed reference */ ++ } ++ t = lua_absindex(L, t); ++ if (lua_rawgeti(L, t, freelist) == LUA_TNIL) { /* first access? */ ++ ref = 0; /* list is empty */ ++ lua_pushinteger(L, 0); /* initialize as an empty list */ ++ lua_rawseti(L, t, freelist); /* ref = t[freelist] = 0 */ ++ } ++ else { /* already initialized */ ++ lua_assert(lua_isinteger(L, -1)); ++ ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */ ++ } ++ lua_pop(L, 1); /* remove element from stack */ ++ if (ref != 0) { /* any free element? */ ++ lua_rawgeti(L, t, ref); /* remove it from list */ ++ lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */ ++ } ++ else /* no free elements */ ++ ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */ ++ lua_rawseti(L, t, ref); ++ return ref; ++} ++ ++ ++LUALIB_API void luaL_unref (lua_State *L, int t, int ref) { ++ if (ref >= 0) { ++ t = lua_absindex(L, t); ++ lua_rawgeti(L, t, freelist); ++ lua_assert(lua_isinteger(L, -1)); ++ lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */ ++ lua_pushinteger(L, ref); ++ lua_rawseti(L, t, freelist); /* t[freelist] = ref */ ++ } ++} ++ ++/* }====================================================== */ ++ ++ ++/* ++** {====================================================== ++** Load functions ++** ======================================================= ++*/ ++ ++typedef struct LoadF { ++ int n; /* number of pre-read characters */ ++ FILE *f; /* file being read */ ++ char buff[BUFSIZ]; /* area for reading file */ ++} LoadF; ++ ++ ++static const char *getF (lua_State *L, void *ud, size_t *size) { ++ LoadF *lf = (LoadF *)ud; ++ (void)L; /* not used */ ++ if (lf->n > 0) { /* are there pre-read characters to be read? */ ++ *size = lf->n; /* return them (chars already in buffer) */ ++ lf->n = 0; /* no more pre-read characters */ ++ } ++ else { /* read a block from file */ ++ /* 'fread' can return > 0 *and* set the EOF flag. If next call to ++ 'getF' called 'fread', it might still wait for user input. ++ The next check avoids this problem. */ ++ if (feof(lf->f)) return NULL; ++ *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */ ++ } ++ return lf->buff; ++} ++ ++ ++static int errfile (lua_State *L, const char *what, int fnameindex) { ++ const char *serr = strerror(errno); ++ const char *filename = lua_tostring(L, fnameindex) + 1; ++ lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr); ++ lua_remove(L, fnameindex); ++ return LUA_ERRFILE; ++} ++ ++ ++static int skipBOM (LoadF *lf) { ++ const char *p = "\xEF\xBB\xBF"; /* UTF-8 BOM mark */ ++ int c; ++ lf->n = 0; ++ do { ++ c = getc(lf->f); ++ if (c == EOF || c != *(const unsigned char *)p++) return c; ++ lf->buff[lf->n++] = c; /* to be read by the parser */ ++ } while (*p != '\0'); ++ lf->n = 0; /* prefix matched; discard it */ ++ return getc(lf->f); /* return next character */ ++} ++ ++ ++/* ++** reads the first character of file 'f' and skips an optional BOM mark ++** in its beginning plus its first line if it starts with '#'. Returns ++** true if it skipped the first line. In any case, '*cp' has the ++** first "valid" character of the file (after the optional BOM and ++** a first-line comment). ++*/ ++static int skipcomment (LoadF *lf, int *cp) { ++ int c = *cp = skipBOM(lf); ++ if (c == '#') { /* first line is a comment (Unix exec. file)? */ ++ do { /* skip first line */ ++ c = getc(lf->f); ++ } while (c != EOF && c != '\n'); ++ *cp = getc(lf->f); /* skip end-of-line, if present */ ++ return 1; /* there was a comment */ ++ } ++ else return 0; /* no comment */ ++} ++ ++ ++LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename, ++ const char *mode) { ++ LoadF lf; ++ int status, readstatus; ++ int c; ++ int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */ ++ if (filename == NULL) { ++ lua_pushliteral(L, "=stdin"); ++ lf.f = stdin; ++ } ++ else { ++ lua_pushfstring(L, "@%s", filename); ++ lf.f = fopen(filename, "r"); ++ if (lf.f == NULL) return errfile(L, "open", fnameindex); ++ } ++ if (skipcomment(&lf, &c)) /* read initial portion */ ++ lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */ ++ if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */ ++ lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */ ++ if (lf.f == NULL) return errfile(L, "reopen", fnameindex); ++ skipcomment(&lf, &c); /* re-read initial portion */ ++ } ++ if (c != EOF) ++ lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */ ++ status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode); ++ readstatus = ferror(lf.f); ++ if (filename) fclose(lf.f); /* close file (even in case of errors) */ ++ if (readstatus) { ++ lua_settop(L, fnameindex); /* ignore results from 'lua_load' */ ++ return errfile(L, "read", fnameindex); ++ } ++ lua_remove(L, fnameindex); ++ return status; ++} ++ ++ ++typedef struct LoadS { ++ const char *s; ++ size_t size; ++} LoadS; ++ ++ ++static const char *getS (lua_State *L, void *ud, size_t *size) { ++ LoadS *ls = (LoadS *)ud; ++ (void)L; /* not used */ ++ if (ls->size == 0) return NULL; ++ *size = ls->size; ++ ls->size = 0; ++ return ls->s; ++} ++ ++ ++LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size, ++ const char *name, const char *mode) { ++ LoadS ls; ++ ls.s = buff; ++ ls.size = size; ++ return lua_load(L, getS, &ls, name, mode); ++} ++ ++ ++LUALIB_API int luaL_loadstring (lua_State *L, const char *s) { ++ return luaL_loadbuffer(L, s, strlen(s), s); ++} ++ ++/* }====================================================== */ ++ ++ ++ ++LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) { ++ if (!lua_getmetatable(L, obj)) /* no metatable? */ ++ return LUA_TNIL; ++ else { ++ int tt; ++ lua_pushstring(L, event); ++ tt = lua_rawget(L, -2); ++ if (tt == LUA_TNIL) /* is metafield nil? */ ++ lua_pop(L, 2); /* remove metatable and metafield */ ++ else ++ lua_remove(L, -2); /* remove only metatable */ ++ return tt; /* return metafield type */ ++ } ++} ++ ++ ++LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) { ++ obj = lua_absindex(L, obj); ++ if (luaL_getmetafield(L, obj, event) == LUA_TNIL) /* no metafield? */ ++ return 0; ++ lua_pushvalue(L, obj); ++ lua_call(L, 1, 1); ++ return 1; ++} ++ ++ ++LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) { ++ lua_Integer l; ++ int isnum; ++ lua_len(L, idx); ++ l = lua_tointegerx(L, -1, &isnum); ++ if (l_unlikely(!isnum)) ++ luaL_error(L, "object length is not an integer"); ++ lua_pop(L, 1); /* remove object */ ++ return l; ++} ++ ++ ++LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) { ++ if (luaL_callmeta(L, idx, "__tostring")) { /* metafield? */ ++ if (!lua_isstring(L, -1)) ++ luaL_error(L, "'__tostring' must return a string"); ++ } ++ else { ++ switch (lua_type(L, idx)) { ++ case LUA_TNUMBER: { ++ if (lua_isinteger(L, idx)) ++ lua_pushfstring(L, "%I", (LUAI_UACINT)lua_tointeger(L, idx)); ++ else ++ lua_pushfstring(L, "%f", (LUAI_UACNUMBER)lua_tonumber(L, idx)); ++ break; ++ } ++ case LUA_TSTRING: ++ lua_pushvalue(L, idx); ++ break; ++ case LUA_TBOOLEAN: ++ lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false")); ++ break; ++ case LUA_TNIL: ++ lua_pushliteral(L, "nil"); ++ break; ++ default: { ++ int tt = luaL_getmetafield(L, idx, "__name"); /* try name */ ++ const char *kind = (tt == LUA_TSTRING) ? lua_tostring(L, -1) : ++ luaL_typename(L, idx); ++ lua_pushfstring(L, "%s: %p", kind, lua_topointer(L, idx)); ++ if (tt != LUA_TNIL) ++ lua_remove(L, -2); /* remove '__name' */ ++ break; ++ } ++ } ++ } ++ return lua_tolstring(L, -1, len); ++} ++ ++ ++/* ++** set functions from list 'l' into table at top - 'nup'; each ++** function gets the 'nup' elements at the top as upvalues. ++** Returns with only the table at the stack. ++*/ ++LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) { ++ luaL_checkstack(L, nup, "too many upvalues"); ++ for (; l->name != NULL; l++) { /* fill the table with given functions */ ++ if (l->func == NULL) /* place holder? */ ++ lua_pushboolean(L, 0); ++ else { ++ int i; ++ for (i = 0; i < nup; i++) /* copy upvalues to the top */ ++ lua_pushvalue(L, -nup); ++ lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */ ++ } ++ lua_setfield(L, -(nup + 2), l->name); ++ } ++ lua_pop(L, nup); /* remove upvalues */ ++} ++ ++ ++/* ++** ensure that stack[idx][fname] has a table and push that table ++** into the stack ++*/ ++LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) { ++ if (lua_getfield(L, idx, fname) == LUA_TTABLE) ++ return 1; /* table already there */ ++ else { ++ lua_pop(L, 1); /* remove previous result */ ++ idx = lua_absindex(L, idx); ++ lua_newtable(L); ++ lua_pushvalue(L, -1); /* copy to be left at top */ ++ lua_setfield(L, idx, fname); /* assign new table to field */ ++ return 0; /* false, because did not find table there */ ++ } ++} ++ ++ ++/* ++** Stripped-down 'require': After checking "loaded" table, calls 'openf' ++** to open a module, registers the result in 'package.loaded' table and, ++** if 'glb' is true, also registers the result in the global table. ++** Leaves resulting module on the top. ++*/ ++LUALIB_API void luaL_requiref (lua_State *L, const char *modname, ++ lua_CFunction openf, int glb) { ++ luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); ++ lua_getfield(L, -1, modname); /* LOADED[modname] */ ++ if (!lua_toboolean(L, -1)) { /* package not already loaded? */ ++ lua_pop(L, 1); /* remove field */ ++ lua_pushcfunction(L, openf); ++ lua_pushstring(L, modname); /* argument to open function */ ++ lua_call(L, 1, 1); /* call 'openf' to open module */ ++ lua_pushvalue(L, -1); /* make copy of module (call result) */ ++ lua_setfield(L, -3, modname); /* LOADED[modname] = module */ ++ } ++ lua_remove(L, -2); /* remove LOADED table */ ++ if (glb) { ++ lua_pushvalue(L, -1); /* copy of module */ ++ lua_setglobal(L, modname); /* _G[modname] = module */ ++ } ++} ++ ++ ++LUALIB_API void luaL_addgsub (luaL_Buffer *b, const char *s, ++ const char *p, const char *r) { ++ const char *wild; ++ size_t l = strlen(p); ++ while ((wild = strstr(s, p)) != NULL) { ++ luaL_addlstring(b, s, wild - s); /* push prefix */ ++ luaL_addstring(b, r); /* push replacement in place of pattern */ ++ s = wild + l; /* continue after 'p' */ ++ } ++ luaL_addstring(b, s); /* push last suffix */ ++} ++ ++ ++LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, ++ const char *p, const char *r) { ++ luaL_Buffer b; ++ luaL_buffinit(L, &b); ++ luaL_addgsub(&b, s, p, r); ++ luaL_pushresult(&b); ++ return lua_tostring(L, -1); ++} ++ ++ ++static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { ++ (void)ud; (void)osize; /* not used */ ++ if (nsize == 0) { ++ free(ptr); ++ return NULL; ++ } ++ else ++ return realloc(ptr, nsize); ++} ++ ++ ++static int panic (lua_State *L) { ++ const char *msg = lua_tostring(L, -1); ++ if (msg == NULL) msg = "error object is not a string"; ++ lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n", ++ msg); ++ return 0; /* return to Lua to abort */ ++} ++ ++ ++/* ++** Warning functions: ++** warnfoff: warning system is off ++** warnfon: ready to start a new message ++** warnfcont: previous message is to be continued ++*/ ++static void warnfoff (void *ud, const char *message, int tocont); ++static void warnfon (void *ud, const char *message, int tocont); ++static void warnfcont (void *ud, const char *message, int tocont); ++ ++ ++/* ++** Check whether message is a control message. If so, execute the ++** control or ignore it if unknown. ++*/ ++static int checkcontrol (lua_State *L, const char *message, int tocont) { ++ if (tocont || *(message++) != '@') /* not a control message? */ ++ return 0; ++ else { ++ if (strcmp(message, "off") == 0) ++ lua_setwarnf(L, warnfoff, L); /* turn warnings off */ ++ else if (strcmp(message, "on") == 0) ++ lua_setwarnf(L, warnfon, L); /* turn warnings on */ ++ return 1; /* it was a control message */ ++ } ++} ++ ++ ++static void warnfoff (void *ud, const char *message, int tocont) { ++ checkcontrol((lua_State *)ud, message, tocont); ++} ++ ++ ++/* ++** Writes the message and handle 'tocont', finishing the message ++** if needed and setting the next warn function. ++*/ ++static void warnfcont (void *ud, const char *message, int tocont) { ++ lua_State *L = (lua_State *)ud; ++ lua_writestringerror("%s", message); /* write message */ ++ if (tocont) /* not the last part? */ ++ lua_setwarnf(L, warnfcont, L); /* to be continued */ ++ else { /* last part */ ++ lua_writestringerror("%s", "\n"); /* finish message with end-of-line */ ++ lua_setwarnf(L, warnfon, L); /* next call is a new message */ ++ } ++} ++ ++ ++static void warnfon (void *ud, const char *message, int tocont) { ++ if (checkcontrol((lua_State *)ud, message, tocont)) /* control message? */ ++ return; /* nothing else to be done */ ++ lua_writestringerror("%s", "Lua warning: "); /* start a new warning */ ++ warnfcont(ud, message, tocont); /* finish processing */ ++} ++ ++ ++LUALIB_API lua_State *luaL_newstate (void) { ++ lua_State *L = lua_newstate(l_alloc, NULL); ++ if (l_likely(L)) { ++ lua_atpanic(L, &panic); ++ lua_setwarnf(L, warnfoff, L); /* default is warnings off */ ++ } ++ return L; ++} ++ ++ ++LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) { ++ lua_Number v = lua_version(L); ++ if (sz != LUAL_NUMSIZES) /* check numeric types */ ++ luaL_error(L, "core and library have incompatible numeric types"); ++ else if (v != ver) ++ luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f", ++ (LUAI_UACNUMBER)ver, (LUAI_UACNUMBER)v); ++} ++ +diff --git a/src/bin/lua/lauxlib.h b/src/bin/lua/lauxlib.h +new file mode 100644 +index 0000000000..72f70e7d9d +--- /dev/null ++++ b/src/bin/lua/lauxlib.h +@@ -0,0 +1,293 @@ ++/* ++** $Id: lauxlib.h $ ++** Auxiliary functions for building Lua libraries ++** See Copyright Notice in lua.h ++*/ ++ ++ ++#ifndef lauxlib_h ++#define lauxlib_h ++ ++ ++#include ++#include ++ ++#include "luaconf.h" ++#include "lua.h" ++ ++ ++/* global table */ ++#define LUA_GNAME "_G" ++ ++ ++typedef struct luaL_Buffer luaL_Buffer; ++ ++ ++/* extra error code for 'luaL_loadfilex' */ ++#define LUA_ERRFILE (LUA_ERRERR+1) ++ ++ ++/* key, in the registry, for table of loaded modules */ ++#define LUA_LOADED_TABLE "_LOADED" ++ ++ ++/* key, in the registry, for table of preloaded loaders */ ++#define LUA_PRELOAD_TABLE "_PRELOAD" ++ ++ ++typedef struct luaL_Reg { ++ const char *name; ++ lua_CFunction func; ++} luaL_Reg; ++ ++ ++#define LUAL_NUMSIZES (sizeof(lua_Integer)*16 + sizeof(lua_Number)) ++ ++LUALIB_API void (luaL_checkversion_) (lua_State *L, lua_Number ver, size_t sz); ++#define luaL_checkversion(L) \ ++ luaL_checkversion_(L, LUA_VERSION_NUM, LUAL_NUMSIZES) ++ ++LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e); ++LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e); ++LUALIB_API const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len); ++LUALIB_API int (luaL_argerror) (lua_State *L, int arg, const char *extramsg); ++LUALIB_API int (luaL_typeerror) (lua_State *L, int arg, const char *tname); ++LUALIB_API const char *(luaL_checklstring) (lua_State *L, int arg, ++ size_t *l); ++LUALIB_API const char *(luaL_optlstring) (lua_State *L, int arg, ++ const char *def, size_t *l); ++LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int arg); ++LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int arg, lua_Number def); ++ ++LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int arg); ++LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int arg, ++ lua_Integer def); ++ ++LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg); ++LUALIB_API void (luaL_checktype) (lua_State *L, int arg, int t); ++LUALIB_API void (luaL_checkany) (lua_State *L, int arg); ++ ++LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname); ++LUALIB_API void (luaL_setmetatable) (lua_State *L, const char *tname); ++LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname); ++LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname); ++ ++LUALIB_API void (luaL_where) (lua_State *L, int lvl); ++LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...); ++ ++LUALIB_API int (luaL_checkoption) (lua_State *L, int arg, const char *def, ++ const char *const lst[]); ++ ++LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname); ++LUALIB_API int (luaL_execresult) (lua_State *L, int stat); ++ ++ ++/* predefined references */ ++#define LUA_NOREF (-2) ++#define LUA_REFNIL (-1) ++ ++LUALIB_API int (luaL_ref) (lua_State *L, int t); ++LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref); ++ ++LUALIB_API int (luaL_loadfilex) (lua_State *L, const char *filename, ++ const char *mode); ++ ++#define luaL_loadfile(L,f) luaL_loadfilex(L,f,NULL) ++ ++LUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz, ++ const char *name, const char *mode); ++LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s); ++ ++LUALIB_API lua_State *(luaL_newstate) (void); ++ ++LUALIB_API lua_Integer (luaL_len) (lua_State *L, int idx); ++ ++LUALIB_API void luaL_addgsub (luaL_Buffer *b, const char *s, ++ const char *p, const char *r); ++LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, ++ const char *p, const char *r); ++ ++LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup); ++ ++LUALIB_API int (luaL_getsubtable) (lua_State *L, int idx, const char *fname); ++ ++LUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1, ++ const char *msg, int level); ++ ++LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname, ++ lua_CFunction openf, int glb); ++ ++/* ++** =============================================================== ++** some useful macros ++** =============================================================== ++*/ ++ ++ ++#define luaL_newlibtable(L,l) \ ++ lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1) ++ ++#define luaL_newlib(L,l) \ ++ (luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0)) ++ ++#define luaL_argcheck(L, cond,arg,extramsg) \ ++ ((void)(luai_likely(cond) || luaL_argerror(L, (arg), (extramsg)))) ++ ++#define luaL_argexpected(L,cond,arg,tname) \ ++ ((void)(luai_likely(cond) || luaL_typeerror(L, (arg), (tname)))) ++ ++#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) ++#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) ++ ++#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i))) ++ ++#define luaL_dofile(L, fn) \ ++ (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) ++ ++#define luaL_dostring(L, s) \ ++ (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) ++ ++#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n))) ++ ++#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) ++ ++#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL) ++ ++ ++/* push the value used to represent failure/error */ ++#define luaL_pushfail(L) lua_pushnil(L) ++ ++ ++/* ++** Internal assertions for in-house debugging ++*/ ++#if !defined(lua_assert) ++ ++#if defined LUAI_ASSERT ++ #include ++ #define lua_assert(c) assert(c) ++#else ++ #define lua_assert(c) ((void)0) ++#endif ++ ++#endif ++ ++ ++ ++/* ++** {====================================================== ++** Generic Buffer manipulation ++** ======================================================= ++*/ ++ ++struct luaL_Buffer { ++ char *b; /* buffer address */ ++ size_t size; /* buffer size */ ++ size_t n; /* number of characters in buffer */ ++ lua_State *L; ++ union { ++ LUAI_MAXALIGN; /* ensure maximum alignment for buffer */ ++ char b[LUAL_BUFFERSIZE]; /* initial buffer */ ++ } init; ++}; ++ ++ ++#define luaL_bufflen(bf) ((bf)->n) ++#define luaL_buffaddr(bf) ((bf)->b) ++ ++ ++#define luaL_addchar(B,c) \ ++ ((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), \ ++ ((B)->b[(B)->n++] = (c))) ++ ++#define luaL_addsize(B,s) ((B)->n += (s)) ++ ++#define luaL_buffsub(B,s) ((B)->n -= (s)) ++ ++LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B); ++LUALIB_API char *(luaL_prepbuffsize) (luaL_Buffer *B, size_t sz); ++LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l); ++LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s); ++LUALIB_API void (luaL_addvalue) (luaL_Buffer *B); ++LUALIB_API void (luaL_pushresult) (luaL_Buffer *B); ++LUALIB_API void (luaL_pushresultsize) (luaL_Buffer *B, size_t sz); ++LUALIB_API char *(luaL_buffinitsize) (lua_State *L, luaL_Buffer *B, size_t sz); ++ ++#define luaL_prepbuffer(B) luaL_prepbuffsize(B, LUAL_BUFFERSIZE) ++ ++/* }====================================================== */ ++ ++ ++ ++/* ++** {====================================================== ++** File handles for IO library ++** ======================================================= ++*/ ++ ++/* ++** A file handle is a userdata with metatable 'LUA_FILEHANDLE' and ++** initial structure 'luaL_Stream' (it may contain other fields ++** after that initial structure). ++*/ ++ ++#define LUA_FILEHANDLE "FILE*" ++ ++ ++typedef struct luaL_Stream { ++ FILE *f; /* stream (NULL for incompletely created streams) */ ++ lua_CFunction closef; /* to close stream (NULL for closed streams) */ ++} luaL_Stream; ++ ++/* }====================================================== */ ++ ++/* ++** {================================================================== ++** "Abstraction Layer" for basic report of messages and errors ++** =================================================================== ++*/ ++ ++/* print a string */ ++#if !defined(lua_writestring) ++#define lua_writestring(s,l) fwrite((s), sizeof(char), (l), stdout) ++#endif ++ ++/* print a newline and flush the output */ ++#if !defined(lua_writeline) ++#define lua_writeline() (lua_writestring("\n", 1), fflush(stdout)) ++#endif ++ ++/* print an error message */ ++#if !defined(lua_writestringerror) ++#define lua_writestringerror(s,p) \ ++ (fprintf(stderr, (s), (p)), fflush(stderr)) ++#endif ++ ++/* }================================================================== */ ++ ++ ++/* ++** {============================================================ ++** Compatibility with deprecated conversions ++** ============================================================= ++*/ ++#if defined(LUA_COMPAT_APIINTCASTS) ++ ++#define luaL_checkunsigned(L,a) ((lua_Unsigned)luaL_checkinteger(L,a)) ++#define luaL_optunsigned(L,a,d) \ ++ ((lua_Unsigned)luaL_optinteger(L,a,(lua_Integer)(d))) ++ ++#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) ++#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d))) ++ ++#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n))) ++#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d))) ++ ++#endif ++/* }============================================================ */ ++ ++ ++ ++#endif ++ ++ +diff --git a/src/bin/lua/lbaselib.c b/src/bin/lua/lbaselib.c +new file mode 100644 +index 0000000000..83ad306d9c +--- /dev/null ++++ b/src/bin/lua/lbaselib.c +@@ -0,0 +1,528 @@ ++/* ++** $Id: lbaselib.c $ ++** Basic library ++** See Copyright Notice in lua.h ++*/ ++ ++#define lbaselib_c ++#define LUA_LIB ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++#include ++#include ++ ++#include "lua.h" ++ ++#include "lauxlib.h" ++#include "lualib.h" ++ ++ ++static int luaB_print (lua_State *L) { ++ int n = lua_gettop(L); /* number of arguments */ ++ int i; ++ for (i = 1; i <= n; i++) { /* for each argument */ ++ size_t l; ++ const char *s = luaL_tolstring(L, i, &l); /* convert it to string */ ++ if (i > 1) /* not the first element? */ ++ lua_writestring("\t", 1); /* add a tab before it */ ++ lua_writestring(s, l); /* print it */ ++ lua_pop(L, 1); /* pop result */ ++ } ++ lua_writeline(); ++ return 0; ++} ++ ++ ++/* ++** Creates a warning with all given arguments. ++** Check first for errors; otherwise an error may interrupt ++** the composition of a warning, leaving it unfinished. ++*/ ++static int luaB_warn (lua_State *L) { ++ int n = lua_gettop(L); /* number of arguments */ ++ int i; ++ luaL_checkstring(L, 1); /* at least one argument */ ++ for (i = 2; i <= n; i++) ++ luaL_checkstring(L, i); /* make sure all arguments are strings */ ++ for (i = 1; i < n; i++) /* compose warning */ ++ lua_warning(L, lua_tostring(L, i), 1); ++ lua_warning(L, lua_tostring(L, n), 0); /* close warning */ ++ return 0; ++} ++ ++ ++#define SPACECHARS " \f\n\r\t\v" ++ ++static const char *b_str2int (const char *s, int base, lua_Integer *pn) { ++ lua_Unsigned n = 0; ++ int neg = 0; ++ s += strspn(s, SPACECHARS); /* skip initial spaces */ ++ if (*s == '-') { s++; neg = 1; } /* handle sign */ ++ else if (*s == '+') s++; ++ if (!isalnum((unsigned char)*s)) /* no digit? */ ++ return NULL; ++ do { ++ int digit = (isdigit((unsigned char)*s)) ? *s - '0' ++ : (toupper((unsigned char)*s) - 'A') + 10; ++ if (digit >= base) return NULL; /* invalid numeral */ ++ n = n * base + digit; ++ s++; ++ } while (isalnum((unsigned char)*s)); ++ s += strspn(s, SPACECHARS); /* skip trailing spaces */ ++ *pn = (lua_Integer)((neg) ? (0u - n) : n); ++ return s; ++} ++ ++ ++static int luaB_tonumber (lua_State *L) { ++ if (lua_isnoneornil(L, 2)) { /* standard conversion? */ ++ if (lua_type(L, 1) == LUA_TNUMBER) { /* already a number? */ ++ lua_settop(L, 1); /* yes; return it */ ++ return 1; ++ } ++ else { ++ size_t l; ++ const char *s = lua_tolstring(L, 1, &l); ++ if (s != NULL && lua_stringtonumber(L, s) == l + 1) ++ return 1; /* successful conversion to number */ ++ /* else not a number */ ++ luaL_checkany(L, 1); /* (but there must be some parameter) */ ++ } ++ } ++ else { ++ size_t l; ++ const char *s; ++ lua_Integer n = 0; /* to avoid warnings */ ++ lua_Integer base = luaL_checkinteger(L, 2); ++ luaL_checktype(L, 1, LUA_TSTRING); /* no numbers as strings */ ++ s = lua_tolstring(L, 1, &l); ++ luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range"); ++ if (b_str2int(s, (int)base, &n) == s + l) { ++ lua_pushinteger(L, n); ++ return 1; ++ } /* else not a number */ ++ } /* else not a number */ ++ luaL_pushfail(L); /* not a number */ ++ return 1; ++} ++ ++ ++static int luaB_error (lua_State *L) { ++ int level = (int)luaL_optinteger(L, 2, 1); ++ lua_settop(L, 1); ++ if (lua_type(L, 1) == LUA_TSTRING && level > 0) { ++ luaL_where(L, level); /* add extra information */ ++ lua_pushvalue(L, 1); ++ lua_concat(L, 2); ++ } ++ return lua_error(L); ++} ++ ++ ++static int luaB_getmetatable (lua_State *L) { ++ luaL_checkany(L, 1); ++ if (!lua_getmetatable(L, 1)) { ++ lua_pushnil(L); ++ return 1; /* no metatable */ ++ } ++ luaL_getmetafield(L, 1, "__metatable"); ++ return 1; /* returns either __metatable field (if present) or metatable */ ++} ++ ++ ++static int luaB_setmetatable (lua_State *L) { ++ int t = lua_type(L, 2); ++ luaL_checktype(L, 1, LUA_TTABLE); ++ luaL_argexpected(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil or table"); ++ if (l_unlikely(luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL)) ++ return luaL_error(L, "cannot change a protected metatable"); ++ lua_settop(L, 2); ++ lua_setmetatable(L, 1); ++ return 1; ++} ++ ++ ++static int luaB_rawequal (lua_State *L) { ++ luaL_checkany(L, 1); ++ luaL_checkany(L, 2); ++ lua_pushboolean(L, lua_rawequal(L, 1, 2)); ++ return 1; ++} ++ ++ ++static int luaB_rawlen (lua_State *L) { ++ int t = lua_type(L, 1); ++ luaL_argexpected(L, t == LUA_TTABLE || t == LUA_TSTRING, 1, ++ "table or string"); ++ lua_pushinteger(L, lua_rawlen(L, 1)); ++ return 1; ++} ++ ++ ++static int luaB_rawget (lua_State *L) { ++ luaL_checktype(L, 1, LUA_TTABLE); ++ luaL_checkany(L, 2); ++ lua_settop(L, 2); ++ lua_rawget(L, 1); ++ return 1; ++} ++ ++static int luaB_rawset (lua_State *L) { ++ luaL_checktype(L, 1, LUA_TTABLE); ++ luaL_checkany(L, 2); ++ luaL_checkany(L, 3); ++ lua_settop(L, 3); ++ lua_rawset(L, 1); ++ return 1; ++} ++ ++ ++static int pushmode (lua_State *L, int oldmode) { ++ lua_pushstring(L, (oldmode == LUA_GCINC) ? "incremental" ++ : "generational"); ++ return 1; ++} ++ ++ ++static int luaB_collectgarbage (lua_State *L) { ++ static const char *const opts[] = {"stop", "restart", "collect", ++ "count", "step", "setpause", "setstepmul", ++ "isrunning", "generational", "incremental", NULL}; ++ static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT, ++ LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL, ++ LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC}; ++ int o = optsnum[luaL_checkoption(L, 1, "collect", opts)]; ++ switch (o) { ++ case LUA_GCCOUNT: { ++ int k = lua_gc(L, o); ++ int b = lua_gc(L, LUA_GCCOUNTB); ++ lua_pushnumber(L, (lua_Number)k + ((lua_Number)b/1024)); ++ return 1; ++ } ++ case LUA_GCSTEP: { ++ int step = (int)luaL_optinteger(L, 2, 0); ++ int res = lua_gc(L, o, step); ++ lua_pushboolean(L, res); ++ return 1; ++ } ++ case LUA_GCSETPAUSE: ++ case LUA_GCSETSTEPMUL: { ++ int p = (int)luaL_optinteger(L, 2, 0); ++ int previous = lua_gc(L, o, p); ++ lua_pushinteger(L, previous); ++ return 1; ++ } ++ case LUA_GCISRUNNING: { ++ int res = lua_gc(L, o); ++ lua_pushboolean(L, res); ++ return 1; ++ } ++ case LUA_GCGEN: { ++ int minormul = (int)luaL_optinteger(L, 2, 0); ++ int majormul = (int)luaL_optinteger(L, 3, 0); ++ return pushmode(L, lua_gc(L, o, minormul, majormul)); ++ } ++ case LUA_GCINC: { ++ int pause = (int)luaL_optinteger(L, 2, 0); ++ int stepmul = (int)luaL_optinteger(L, 3, 0); ++ int stepsize = (int)luaL_optinteger(L, 4, 0); ++ return pushmode(L, lua_gc(L, o, pause, stepmul, stepsize)); ++ } ++ default: { ++ int res = lua_gc(L, o); ++ lua_pushinteger(L, res); ++ return 1; ++ } ++ } ++} ++ ++ ++static int luaB_type (lua_State *L) { ++ int t = lua_type(L, 1); ++ luaL_argcheck(L, t != LUA_TNONE, 1, "value expected"); ++ lua_pushstring(L, lua_typename(L, t)); ++ return 1; ++} ++ ++ ++static int luaB_next (lua_State *L) { ++ luaL_checktype(L, 1, LUA_TTABLE); ++ lua_settop(L, 2); /* create a 2nd argument if there isn't one */ ++ if (lua_next(L, 1)) ++ return 2; ++ else { ++ lua_pushnil(L); ++ return 1; ++ } ++} ++ ++ ++static int luaB_pairs (lua_State *L) { ++ luaL_checkany(L, 1); ++ if (luaL_getmetafield(L, 1, "__pairs") == LUA_TNIL) { /* no metamethod? */ ++ lua_pushcfunction(L, luaB_next); /* will return generator, */ ++ lua_pushvalue(L, 1); /* state, */ ++ lua_pushnil(L); /* and initial value */ ++ } ++ else { ++ lua_pushvalue(L, 1); /* argument 'self' to metamethod */ ++ lua_call(L, 1, 3); /* get 3 values from metamethod */ ++ } ++ return 3; ++} ++ ++ ++/* ++** Traversal function for 'ipairs' ++*/ ++static int ipairsaux (lua_State *L) { ++ lua_Integer i = luaL_checkinteger(L, 2) + 1; ++ lua_pushinteger(L, i); ++ return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2; ++} ++ ++ ++/* ++** 'ipairs' function. Returns 'ipairsaux', given "table", 0. ++** (The given "table" may not be a table.) ++*/ ++static int luaB_ipairs (lua_State *L) { ++ luaL_checkany(L, 1); ++ lua_pushcfunction(L, ipairsaux); /* iteration function */ ++ lua_pushvalue(L, 1); /* state */ ++ lua_pushinteger(L, 0); /* initial value */ ++ return 3; ++} ++ ++ ++static int load_aux (lua_State *L, int status, int envidx) { ++ if (l_likely(status == LUA_OK)) { ++ if (envidx != 0) { /* 'env' parameter? */ ++ lua_pushvalue(L, envidx); /* environment for loaded function */ ++ if (!lua_setupvalue(L, -2, 1)) /* set it as 1st upvalue */ ++ lua_pop(L, 1); /* remove 'env' if not used by previous call */ ++ } ++ return 1; ++ } ++ else { /* error (message is on top of the stack) */ ++ luaL_pushfail(L); ++ lua_insert(L, -2); /* put before error message */ ++ return 2; /* return fail plus error message */ ++ } ++} ++ ++ ++static int luaB_loadfile (lua_State *L) { ++ const char *fname = luaL_optstring(L, 1, NULL); ++ const char *mode = luaL_optstring(L, 2, NULL); ++ int env = (!lua_isnone(L, 3) ? 3 : 0); /* 'env' index or 0 if no 'env' */ ++ int status = luaL_loadfilex(L, fname, mode); ++ return load_aux(L, status, env); ++} ++ ++ ++/* ++** {====================================================== ++** Generic Read function ++** ======================================================= ++*/ ++ ++ ++/* ++** reserved slot, above all arguments, to hold a copy of the returned ++** string to avoid it being collected while parsed. 'load' has four ++** optional arguments (chunk, source name, mode, and environment). ++*/ ++#define RESERVEDSLOT 5 ++ ++ ++/* ++** Reader for generic 'load' function: 'lua_load' uses the ++** stack for internal stuff, so the reader cannot change the ++** stack top. Instead, it keeps its resulting string in a ++** reserved slot inside the stack. ++*/ ++static const char *generic_reader (lua_State *L, void *ud, size_t *size) { ++ (void)(ud); /* not used */ ++ luaL_checkstack(L, 2, "too many nested functions"); ++ lua_pushvalue(L, 1); /* get function */ ++ lua_call(L, 0, 1); /* call it */ ++ if (lua_isnil(L, -1)) { ++ lua_pop(L, 1); /* pop result */ ++ *size = 0; ++ return NULL; ++ } ++ else if (l_unlikely(!lua_isstring(L, -1))) ++ luaL_error(L, "reader function must return a string"); ++ lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */ ++ return lua_tolstring(L, RESERVEDSLOT, size); ++} ++ ++ ++static int luaB_load (lua_State *L) { ++ int status; ++ size_t l; ++ const char *s = lua_tolstring(L, 1, &l); ++ const char *mode = luaL_optstring(L, 3, "bt"); ++ int env = (!lua_isnone(L, 4) ? 4 : 0); /* 'env' index or 0 if no 'env' */ ++ if (s != NULL) { /* loading a string? */ ++ const char *chunkname = luaL_optstring(L, 2, s); ++ status = luaL_loadbufferx(L, s, l, chunkname, mode); ++ } ++ else { /* loading from a reader function */ ++ const char *chunkname = luaL_optstring(L, 2, "=(load)"); ++ luaL_checktype(L, 1, LUA_TFUNCTION); ++ lua_settop(L, RESERVEDSLOT); /* create reserved slot */ ++ status = lua_load(L, generic_reader, NULL, chunkname, mode); ++ } ++ return load_aux(L, status, env); ++} ++ ++/* }====================================================== */ ++ ++ ++static int dofilecont (lua_State *L, int d1, lua_KContext d2) { ++ (void)d1; (void)d2; /* only to match 'lua_Kfunction' prototype */ ++ return lua_gettop(L) - 1; ++} ++ ++ ++static int luaB_dofile (lua_State *L) { ++ const char *fname = luaL_optstring(L, 1, NULL); ++ lua_settop(L, 1); ++ if (l_unlikely(luaL_loadfile(L, fname) != LUA_OK)) ++ return lua_error(L); ++ lua_callk(L, 0, LUA_MULTRET, 0, dofilecont); ++ return dofilecont(L, 0, 0); ++} ++ ++ ++static int luaB_assert (lua_State *L) { ++ if (l_likely(lua_toboolean(L, 1))) /* condition is true? */ ++ return lua_gettop(L); /* return all arguments */ ++ else { /* error */ ++ luaL_checkany(L, 1); /* there must be a condition */ ++ lua_remove(L, 1); /* remove it */ ++ lua_pushliteral(L, "assertion failed!"); /* default message */ ++ lua_settop(L, 1); /* leave only message (default if no other one) */ ++ return luaB_error(L); /* call 'error' */ ++ } ++} ++ ++ ++static int luaB_select (lua_State *L) { ++ int n = lua_gettop(L); ++ if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') { ++ lua_pushinteger(L, n-1); ++ return 1; ++ } ++ else { ++ lua_Integer i = luaL_checkinteger(L, 1); ++ if (i < 0) i = n + i; ++ else if (i > n) i = n; ++ luaL_argcheck(L, 1 <= i, 1, "index out of range"); ++ return n - (int)i; ++ } ++} ++ ++ ++/* ++** Continuation function for 'pcall' and 'xpcall'. Both functions ++** already pushed a 'true' before doing the call, so in case of success ++** 'finishpcall' only has to return everything in the stack minus ++** 'extra' values (where 'extra' is exactly the number of items to be ++** ignored). ++*/ ++static int finishpcall (lua_State *L, int status, lua_KContext extra) { ++ if (l_unlikely(status != LUA_OK && status != LUA_YIELD)) { /* error? */ ++ lua_pushboolean(L, 0); /* first result (false) */ ++ lua_pushvalue(L, -2); /* error message */ ++ return 2; /* return false, msg */ ++ } ++ else ++ return lua_gettop(L) - (int)extra; /* return all results */ ++} ++ ++ ++static int luaB_pcall (lua_State *L) { ++ int status; ++ luaL_checkany(L, 1); ++ lua_pushboolean(L, 1); /* first result if no errors */ ++ lua_insert(L, 1); /* put it in place */ ++ status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, finishpcall); ++ return finishpcall(L, status, 0); ++} ++ ++ ++/* ++** Do a protected call with error handling. After 'lua_rotate', the ++** stack will have ; so, the function passes ++** 2 to 'finishpcall' to skip the 2 first values when returning results. ++*/ ++static int luaB_xpcall (lua_State *L) { ++ int status; ++ int n = lua_gettop(L); ++ luaL_checktype(L, 2, LUA_TFUNCTION); /* check error function */ ++ lua_pushboolean(L, 1); /* first result */ ++ lua_pushvalue(L, 1); /* function */ ++ lua_rotate(L, 3, 2); /* move them below function's arguments */ ++ status = lua_pcallk(L, n - 2, LUA_MULTRET, 2, 2, finishpcall); ++ return finishpcall(L, status, 2); ++} ++ ++ ++static int luaB_tostring (lua_State *L) { ++ luaL_checkany(L, 1); ++ luaL_tolstring(L, 1, NULL); ++ return 1; ++} ++ ++ ++static const luaL_Reg base_funcs[] = { ++ {"assert", luaB_assert}, ++ {"collectgarbage", luaB_collectgarbage}, ++ {"dofile", luaB_dofile}, ++ {"error", luaB_error}, ++ {"getmetatable", luaB_getmetatable}, ++ {"ipairs", luaB_ipairs}, ++ {"loadfile", luaB_loadfile}, ++ {"load", luaB_load}, ++ {"next", luaB_next}, ++ {"pairs", luaB_pairs}, ++ {"pcall", luaB_pcall}, ++ {"print", luaB_print}, ++ {"warn", luaB_warn}, ++ {"rawequal", luaB_rawequal}, ++ {"rawlen", luaB_rawlen}, ++ {"rawget", luaB_rawget}, ++ {"rawset", luaB_rawset}, ++ {"select", luaB_select}, ++ {"setmetatable", luaB_setmetatable}, ++ {"tonumber", luaB_tonumber}, ++ {"tostring", luaB_tostring}, ++ {"type", luaB_type}, ++ {"xpcall", luaB_xpcall}, ++ /* placeholders */ ++ {LUA_GNAME, NULL}, ++ {"_VERSION", NULL}, ++ {NULL, NULL} ++}; ++ ++ ++LUAMOD_API int luaopen_base (lua_State *L) { ++ /* open lib into global table */ ++ lua_pushglobaltable(L); ++ luaL_setfuncs(L, base_funcs, 0); ++ /* set global _G */ ++ lua_pushvalue(L, -1); ++ lua_setfield(L, -2, LUA_GNAME); ++ /* set global _VERSION */ ++ lua_pushliteral(L, LUA_VERSION); ++ lua_setfield(L, -2, "_VERSION"); ++ return 1; ++} ++ +diff --git a/src/bin/lua/lcode.c b/src/bin/lua/lcode.c +new file mode 100644 +index 0000000000..80d975cb85 +--- /dev/null ++++ b/src/bin/lua/lcode.c +@@ -0,0 +1,1814 @@ ++/* ++** $Id: lcode.c $ ++** Code generator for Lua ++** See Copyright Notice in lua.h ++*/ ++ ++#define lcode_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++#include ++ ++#include "lua.h" ++ ++#include "lcode.h" ++#include "ldebug.h" ++#include "ldo.h" ++#include "lgc.h" ++#include "llex.h" ++#include "lmem.h" ++#include "lobject.h" ++#include "lopcodes.h" ++#include "lparser.h" ++#include "lstring.h" ++#include "ltable.h" ++#include "lvm.h" ++ ++ ++/* Maximum number of registers in a Lua function (must fit in 8 bits) */ ++#define MAXREGS 255 ++ ++ ++#define hasjumps(e) ((e)->t != (e)->f) ++ ++ ++static int codesJ (FuncState *fs, OpCode o, int sj, int k); ++ ++ ++ ++/* semantic error */ ++l_noret luaK_semerror (LexState *ls, const char *msg) { ++ ls->t.token = 0; /* remove "near " from final message */ ++ luaX_syntaxerror(ls, msg); ++} ++ ++ ++/* ++** If expression is a numeric constant, fills 'v' with its value ++** and returns 1. Otherwise, returns 0. ++*/ ++static int tonumeral (const expdesc *e, TValue *v) { ++ if (hasjumps(e)) ++ return 0; /* not a numeral */ ++ switch (e->k) { ++ case VKINT: ++ if (v) setivalue(v, e->u.ival); ++ return 1; ++ case VKFLT: ++ if (v) setfltvalue(v, e->u.nval); ++ return 1; ++ default: return 0; ++ } ++} ++ ++ ++/* ++** Get the constant value from a constant expression ++*/ ++static TValue *const2val (FuncState *fs, const expdesc *e) { ++ lua_assert(e->k == VCONST); ++ return &fs->ls->dyd->actvar.arr[e->u.info].k; ++} ++ ++ ++/* ++** If expression is a constant, fills 'v' with its value ++** and returns 1. Otherwise, returns 0. ++*/ ++int luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v) { ++ if (hasjumps(e)) ++ return 0; /* not a constant */ ++ switch (e->k) { ++ case VFALSE: ++ setbfvalue(v); ++ return 1; ++ case VTRUE: ++ setbtvalue(v); ++ return 1; ++ case VNIL: ++ setnilvalue(v); ++ return 1; ++ case VKSTR: { ++ setsvalue(fs->ls->L, v, e->u.strval); ++ return 1; ++ } ++ case VCONST: { ++ setobj(fs->ls->L, v, const2val(fs, e)); ++ return 1; ++ } ++ default: return tonumeral(e, v); ++ } ++} ++ ++ ++/* ++** Return the previous instruction of the current code. If there ++** may be a jump target between the current instruction and the ++** previous one, return an invalid instruction (to avoid wrong ++** optimizations). ++*/ ++static Instruction *previousinstruction (FuncState *fs) { ++ static const Instruction invalidinstruction = ~(Instruction)0; ++ if (fs->pc > fs->lasttarget) ++ return &fs->f->code[fs->pc - 1]; /* previous instruction */ ++ else ++ return cast(Instruction*, &invalidinstruction); ++} ++ ++ ++/* ++** Create a OP_LOADNIL instruction, but try to optimize: if the previous ++** instruction is also OP_LOADNIL and ranges are compatible, adjust ++** range of previous instruction instead of emitting a new one. (For ++** instance, 'local a; local b' will generate a single opcode.) ++*/ ++void luaK_nil (FuncState *fs, int from, int n) { ++ int l = from + n - 1; /* last register to set nil */ ++ Instruction *previous = previousinstruction(fs); ++ if (GET_OPCODE(*previous) == OP_LOADNIL) { /* previous is LOADNIL? */ ++ int pfrom = GETARG_A(*previous); /* get previous range */ ++ int pl = pfrom + GETARG_B(*previous); ++ if ((pfrom <= from && from <= pl + 1) || ++ (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */ ++ if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */ ++ if (pl > l) l = pl; /* l = max(l, pl) */ ++ SETARG_A(*previous, from); ++ SETARG_B(*previous, l - from); ++ return; ++ } /* else go through */ ++ } ++ luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */ ++} ++ ++ ++/* ++** Gets the destination address of a jump instruction. Used to traverse ++** a list of jumps. ++*/ ++static int getjump (FuncState *fs, int pc) { ++ int offset = GETARG_sJ(fs->f->code[pc]); ++ if (offset == NO_JUMP) /* point to itself represents end of list */ ++ return NO_JUMP; /* end of list */ ++ else ++ return (pc+1)+offset; /* turn offset into absolute position */ ++} ++ ++ ++/* ++** Fix jump instruction at position 'pc' to jump to 'dest'. ++** (Jump addresses are relative in Lua) ++*/ ++static void fixjump (FuncState *fs, int pc, int dest) { ++ Instruction *jmp = &fs->f->code[pc]; ++ int offset = dest - (pc + 1); ++ lua_assert(dest != NO_JUMP); ++ if (!(-OFFSET_sJ <= offset && offset <= MAXARG_sJ - OFFSET_sJ)) ++ luaX_syntaxerror(fs->ls, "control structure too long"); ++ lua_assert(GET_OPCODE(*jmp) == OP_JMP); ++ SETARG_sJ(*jmp, offset); ++} ++ ++ ++/* ++** Concatenate jump-list 'l2' into jump-list 'l1' ++*/ ++void luaK_concat (FuncState *fs, int *l1, int l2) { ++ if (l2 == NO_JUMP) return; /* nothing to concatenate? */ ++ else if (*l1 == NO_JUMP) /* no original list? */ ++ *l1 = l2; /* 'l1' points to 'l2' */ ++ else { ++ int list = *l1; ++ int next; ++ while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */ ++ list = next; ++ fixjump(fs, list, l2); /* last element links to 'l2' */ ++ } ++} ++ ++ ++/* ++** Create a jump instruction and return its position, so its destination ++** can be fixed later (with 'fixjump'). ++*/ ++int luaK_jump (FuncState *fs) { ++ return codesJ(fs, OP_JMP, NO_JUMP, 0); ++} ++ ++ ++/* ++** Code a 'return' instruction ++*/ ++void luaK_ret (FuncState *fs, int first, int nret) { ++ OpCode op; ++ switch (nret) { ++ case 0: op = OP_RETURN0; break; ++ case 1: op = OP_RETURN1; break; ++ default: op = OP_RETURN; break; ++ } ++ luaK_codeABC(fs, op, first, nret + 1, 0); ++} ++ ++ ++/* ++** Code a "conditional jump", that is, a test or comparison opcode ++** followed by a jump. Return jump position. ++*/ ++static int condjump (FuncState *fs, OpCode op, int A, int B, int C, int k) { ++ luaK_codeABCk(fs, op, A, B, C, k); ++ return luaK_jump(fs); ++} ++ ++ ++/* ++** returns current 'pc' and marks it as a jump target (to avoid wrong ++** optimizations with consecutive instructions not in the same basic block). ++*/ ++int luaK_getlabel (FuncState *fs) { ++ fs->lasttarget = fs->pc; ++ return fs->pc; ++} ++ ++ ++/* ++** Returns the position of the instruction "controlling" a given ++** jump (that is, its condition), or the jump itself if it is ++** unconditional. ++*/ ++static Instruction *getjumpcontrol (FuncState *fs, int pc) { ++ Instruction *pi = &fs->f->code[pc]; ++ if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1)))) ++ return pi-1; ++ else ++ return pi; ++} ++ ++ ++/* ++** Patch destination register for a TESTSET instruction. ++** If instruction in position 'node' is not a TESTSET, return 0 ("fails"). ++** Otherwise, if 'reg' is not 'NO_REG', set it as the destination ++** register. Otherwise, change instruction to a simple 'TEST' (produces ++** no register value) ++*/ ++static int patchtestreg (FuncState *fs, int node, int reg) { ++ Instruction *i = getjumpcontrol(fs, node); ++ if (GET_OPCODE(*i) != OP_TESTSET) ++ return 0; /* cannot patch other instructions */ ++ if (reg != NO_REG && reg != GETARG_B(*i)) ++ SETARG_A(*i, reg); ++ else { ++ /* no register to put value or register already has the value; ++ change instruction to simple test */ ++ *i = CREATE_ABCk(OP_TEST, GETARG_B(*i), 0, 0, GETARG_k(*i)); ++ } ++ return 1; ++} ++ ++ ++/* ++** Traverse a list of tests ensuring no one produces a value ++*/ ++static void removevalues (FuncState *fs, int list) { ++ for (; list != NO_JUMP; list = getjump(fs, list)) ++ patchtestreg(fs, list, NO_REG); ++} ++ ++ ++/* ++** Traverse a list of tests, patching their destination address and ++** registers: tests producing values jump to 'vtarget' (and put their ++** values in 'reg'), other tests jump to 'dtarget'. ++*/ ++static void patchlistaux (FuncState *fs, int list, int vtarget, int reg, ++ int dtarget) { ++ while (list != NO_JUMP) { ++ int next = getjump(fs, list); ++ if (patchtestreg(fs, list, reg)) ++ fixjump(fs, list, vtarget); ++ else ++ fixjump(fs, list, dtarget); /* jump to default target */ ++ list = next; ++ } ++} ++ ++ ++/* ++** Path all jumps in 'list' to jump to 'target'. ++** (The assert means that we cannot fix a jump to a forward address ++** because we only know addresses once code is generated.) ++*/ ++void luaK_patchlist (FuncState *fs, int list, int target) { ++ lua_assert(target <= fs->pc); ++ patchlistaux(fs, list, target, NO_REG, target); ++} ++ ++ ++void luaK_patchtohere (FuncState *fs, int list) { ++ int hr = luaK_getlabel(fs); /* mark "here" as a jump target */ ++ luaK_patchlist(fs, list, hr); ++} ++ ++ ++/* limit for difference between lines in relative line info. */ ++#define LIMLINEDIFF 0x80 ++ ++ ++/* ++** Save line info for a new instruction. If difference from last line ++** does not fit in a byte, of after that many instructions, save a new ++** absolute line info; (in that case, the special value 'ABSLINEINFO' ++** in 'lineinfo' signals the existence of this absolute information.) ++** Otherwise, store the difference from last line in 'lineinfo'. ++*/ ++static void savelineinfo (FuncState *fs, Proto *f, int line) { ++ int linedif = line - fs->previousline; ++ int pc = fs->pc - 1; /* last instruction coded */ ++ if (abs(linedif) >= LIMLINEDIFF || fs->iwthabs++ >= MAXIWTHABS) { ++ luaM_growvector(fs->ls->L, f->abslineinfo, fs->nabslineinfo, ++ f->sizeabslineinfo, AbsLineInfo, MAX_INT, "lines"); ++ f->abslineinfo[fs->nabslineinfo].pc = pc; ++ f->abslineinfo[fs->nabslineinfo++].line = line; ++ linedif = ABSLINEINFO; /* signal that there is absolute information */ ++ fs->iwthabs = 1; /* restart counter */ ++ } ++ luaM_growvector(fs->ls->L, f->lineinfo, pc, f->sizelineinfo, ls_byte, ++ MAX_INT, "opcodes"); ++ f->lineinfo[pc] = linedif; ++ fs->previousline = line; /* last line saved */ ++} ++ ++ ++/* ++** Remove line information from the last instruction. ++** If line information for that instruction is absolute, set 'iwthabs' ++** above its max to force the new (replacing) instruction to have ++** absolute line info, too. ++*/ ++static void removelastlineinfo (FuncState *fs) { ++ Proto *f = fs->f; ++ int pc = fs->pc - 1; /* last instruction coded */ ++ if (f->lineinfo[pc] != ABSLINEINFO) { /* relative line info? */ ++ fs->previousline -= f->lineinfo[pc]; /* correct last line saved */ ++ fs->iwthabs--; /* undo previous increment */ ++ } ++ else { /* absolute line information */ ++ lua_assert(f->abslineinfo[fs->nabslineinfo - 1].pc == pc); ++ fs->nabslineinfo--; /* remove it */ ++ fs->iwthabs = MAXIWTHABS + 1; /* force next line info to be absolute */ ++ } ++} ++ ++ ++/* ++** Remove the last instruction created, correcting line information ++** accordingly. ++*/ ++static void removelastinstruction (FuncState *fs) { ++ removelastlineinfo(fs); ++ fs->pc--; ++} ++ ++ ++/* ++** Emit instruction 'i', checking for array sizes and saving also its ++** line information. Return 'i' position. ++*/ ++int luaK_code (FuncState *fs, Instruction i) { ++ Proto *f = fs->f; ++ /* put new instruction in code array */ ++ luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction, ++ MAX_INT, "opcodes"); ++ f->code[fs->pc++] = i; ++ savelineinfo(fs, f, fs->ls->lastline); ++ return fs->pc - 1; /* index of new instruction */ ++} ++ ++ ++/* ++** Format and emit an 'iABC' instruction. (Assertions check consistency ++** of parameters versus opcode.) ++*/ ++int luaK_codeABCk (FuncState *fs, OpCode o, int a, int b, int c, int k) { ++ lua_assert(getOpMode(o) == iABC); ++ lua_assert(a <= MAXARG_A && b <= MAXARG_B && ++ c <= MAXARG_C && (k & ~1) == 0); ++ return luaK_code(fs, CREATE_ABCk(o, a, b, c, k)); ++} ++ ++ ++/* ++** Format and emit an 'iABx' instruction. ++*/ ++int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) { ++ lua_assert(getOpMode(o) == iABx); ++ lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx); ++ return luaK_code(fs, CREATE_ABx(o, a, bc)); ++} ++ ++ ++/* ++** Format and emit an 'iAsBx' instruction. ++*/ ++int luaK_codeAsBx (FuncState *fs, OpCode o, int a, int bc) { ++ unsigned int b = bc + OFFSET_sBx; ++ lua_assert(getOpMode(o) == iAsBx); ++ lua_assert(a <= MAXARG_A && b <= MAXARG_Bx); ++ return luaK_code(fs, CREATE_ABx(o, a, b)); ++} ++ ++ ++/* ++** Format and emit an 'isJ' instruction. ++*/ ++static int codesJ (FuncState *fs, OpCode o, int sj, int k) { ++ unsigned int j = sj + OFFSET_sJ; ++ lua_assert(getOpMode(o) == isJ); ++ lua_assert(j <= MAXARG_sJ && (k & ~1) == 0); ++ return luaK_code(fs, CREATE_sJ(o, j, k)); ++} ++ ++ ++/* ++** Emit an "extra argument" instruction (format 'iAx') ++*/ ++static int codeextraarg (FuncState *fs, int a) { ++ lua_assert(a <= MAXARG_Ax); ++ return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, a)); ++} ++ ++ ++/* ++** Emit a "load constant" instruction, using either 'OP_LOADK' ++** (if constant index 'k' fits in 18 bits) or an 'OP_LOADKX' ++** instruction with "extra argument". ++*/ ++static int luaK_codek (FuncState *fs, int reg, int k) { ++ if (k <= MAXARG_Bx) ++ return luaK_codeABx(fs, OP_LOADK, reg, k); ++ else { ++ int p = luaK_codeABx(fs, OP_LOADKX, reg, 0); ++ codeextraarg(fs, k); ++ return p; ++ } ++} ++ ++ ++/* ++** Check register-stack level, keeping track of its maximum size ++** in field 'maxstacksize' ++*/ ++void luaK_checkstack (FuncState *fs, int n) { ++ int newstack = fs->freereg + n; ++ if (newstack > fs->f->maxstacksize) { ++ if (newstack >= MAXREGS) ++ luaX_syntaxerror(fs->ls, ++ "function or expression needs too many registers"); ++ fs->f->maxstacksize = cast_byte(newstack); ++ } ++} ++ ++ ++/* ++** Reserve 'n' registers in register stack ++*/ ++void luaK_reserveregs (FuncState *fs, int n) { ++ luaK_checkstack(fs, n); ++ fs->freereg += n; ++} ++ ++ ++/* ++** Free register 'reg', if it is neither a constant index nor ++** a local variable. ++) ++*/ ++static void freereg (FuncState *fs, int reg) { ++ if (reg >= luaY_nvarstack(fs)) { ++ fs->freereg--; ++ lua_assert(reg == fs->freereg); ++ } ++} ++ ++ ++/* ++** Free two registers in proper order ++*/ ++static void freeregs (FuncState *fs, int r1, int r2) { ++ if (r1 > r2) { ++ freereg(fs, r1); ++ freereg(fs, r2); ++ } ++ else { ++ freereg(fs, r2); ++ freereg(fs, r1); ++ } ++} ++ ++ ++/* ++** Free register used by expression 'e' (if any) ++*/ ++static void freeexp (FuncState *fs, expdesc *e) { ++ if (e->k == VNONRELOC) ++ freereg(fs, e->u.info); ++} ++ ++ ++/* ++** Free registers used by expressions 'e1' and 'e2' (if any) in proper ++** order. ++*/ ++static void freeexps (FuncState *fs, expdesc *e1, expdesc *e2) { ++ int r1 = (e1->k == VNONRELOC) ? e1->u.info : -1; ++ int r2 = (e2->k == VNONRELOC) ? e2->u.info : -1; ++ freeregs(fs, r1, r2); ++} ++ ++ ++/* ++** Add constant 'v' to prototype's list of constants (field 'k'). ++** Use scanner's table to cache position of constants in constant list ++** and try to reuse constants. Because some values should not be used ++** as keys (nil cannot be a key, integer keys can collapse with float ++** keys), the caller must provide a useful 'key' for indexing the cache. ++** Note that all functions share the same table, so entering or exiting ++** a function can make some indices wrong. ++*/ ++static int addk (FuncState *fs, TValue *key, TValue *v) { ++ TValue val; ++ lua_State *L = fs->ls->L; ++ Proto *f = fs->f; ++ const TValue *idx = luaH_get(fs->ls->h, key); /* query scanner table */ ++ int k, oldsize; ++ if (ttisinteger(idx)) { /* is there an index there? */ ++ k = cast_int(ivalue(idx)); ++ /* correct value? (warning: must distinguish floats from integers!) */ ++ if (k < fs->nk && ttypetag(&f->k[k]) == ttypetag(v) && ++ luaV_rawequalobj(&f->k[k], v)) ++ return k; /* reuse index */ ++ } ++ /* constant not found; create a new entry */ ++ oldsize = f->sizek; ++ k = fs->nk; ++ /* numerical value does not need GC barrier; ++ table has no metatable, so it does not need to invalidate cache */ ++ setivalue(&val, k); ++ luaH_finishset(L, fs->ls->h, key, idx, &val); ++ luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants"); ++ while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]); ++ setobj(L, &f->k[k], v); ++ fs->nk++; ++ luaC_barrier(L, f, v); ++ return k; ++} ++ ++ ++/* ++** Add a string to list of constants and return its index. ++*/ ++static int stringK (FuncState *fs, TString *s) { ++ TValue o; ++ setsvalue(fs->ls->L, &o, s); ++ return addk(fs, &o, &o); /* use string itself as key */ ++} ++ ++ ++/* ++** Add an integer to list of constants and return its index. ++** Integers use userdata as keys to avoid collision with floats with ++** same value; conversion to 'void*' is used only for hashing, so there ++** are no "precision" problems. ++*/ ++static int luaK_intK (FuncState *fs, lua_Integer n) { ++ TValue k, o; ++ setpvalue(&k, cast_voidp(cast_sizet(n))); ++ setivalue(&o, n); ++ return addk(fs, &k, &o); ++} ++ ++/* ++** Add a float to list of constants and return its index. ++*/ ++static int luaK_numberK (FuncState *fs, lua_Number r) { ++ TValue o; ++ setfltvalue(&o, r); ++ return addk(fs, &o, &o); /* use number itself as key */ ++} ++ ++ ++/* ++** Add a false to list of constants and return its index. ++*/ ++static int boolF (FuncState *fs) { ++ TValue o; ++ setbfvalue(&o); ++ return addk(fs, &o, &o); /* use boolean itself as key */ ++} ++ ++ ++/* ++** Add a true to list of constants and return its index. ++*/ ++static int boolT (FuncState *fs) { ++ TValue o; ++ setbtvalue(&o); ++ return addk(fs, &o, &o); /* use boolean itself as key */ ++} ++ ++ ++/* ++** Add nil to list of constants and return its index. ++*/ ++static int nilK (FuncState *fs) { ++ TValue k, v; ++ setnilvalue(&v); ++ /* cannot use nil as key; instead use table itself to represent nil */ ++ sethvalue(fs->ls->L, &k, fs->ls->h); ++ return addk(fs, &k, &v); ++} ++ ++ ++/* ++** Check whether 'i' can be stored in an 'sC' operand. Equivalent to ++** (0 <= int2sC(i) && int2sC(i) <= MAXARG_C) but without risk of ++** overflows in the hidden addition inside 'int2sC'. ++*/ ++static int fitsC (lua_Integer i) { ++ return (l_castS2U(i) + OFFSET_sC <= cast_uint(MAXARG_C)); ++} ++ ++ ++/* ++** Check whether 'i' can be stored in an 'sBx' operand. ++*/ ++static int fitsBx (lua_Integer i) { ++ return (-OFFSET_sBx <= i && i <= MAXARG_Bx - OFFSET_sBx); ++} ++ ++ ++void luaK_int (FuncState *fs, int reg, lua_Integer i) { ++ if (fitsBx(i)) ++ luaK_codeAsBx(fs, OP_LOADI, reg, cast_int(i)); ++ else ++ luaK_codek(fs, reg, luaK_intK(fs, i)); ++} ++ ++ ++static void luaK_float (FuncState *fs, int reg, lua_Number f) { ++ lua_Integer fi; ++ if (luaV_flttointeger(f, &fi, F2Ieq) && fitsBx(fi)) ++ luaK_codeAsBx(fs, OP_LOADF, reg, cast_int(fi)); ++ else ++ luaK_codek(fs, reg, luaK_numberK(fs, f)); ++} ++ ++ ++/* ++** Convert a constant in 'v' into an expression description 'e' ++*/ ++static void const2exp (TValue *v, expdesc *e) { ++ switch (ttypetag(v)) { ++ case LUA_VNUMINT: ++ e->k = VKINT; e->u.ival = ivalue(v); ++ break; ++ case LUA_VNUMFLT: ++ e->k = VKFLT; e->u.nval = fltvalue(v); ++ break; ++ case LUA_VFALSE: ++ e->k = VFALSE; ++ break; ++ case LUA_VTRUE: ++ e->k = VTRUE; ++ break; ++ case LUA_VNIL: ++ e->k = VNIL; ++ break; ++ case LUA_VSHRSTR: case LUA_VLNGSTR: ++ e->k = VKSTR; e->u.strval = tsvalue(v); ++ break; ++ default: lua_assert(0); ++ } ++} ++ ++ ++/* ++** Fix an expression to return the number of results 'nresults'. ++** 'e' must be a multi-ret expression (function call or vararg). ++*/ ++void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) { ++ Instruction *pc = &getinstruction(fs, e); ++ if (e->k == VCALL) /* expression is an open function call? */ ++ SETARG_C(*pc, nresults + 1); ++ else { ++ lua_assert(e->k == VVARARG); ++ SETARG_C(*pc, nresults + 1); ++ SETARG_A(*pc, fs->freereg); ++ luaK_reserveregs(fs, 1); ++ } ++} ++ ++ ++/* ++** Convert a VKSTR to a VK ++*/ ++static void str2K (FuncState *fs, expdesc *e) { ++ lua_assert(e->k == VKSTR); ++ e->u.info = stringK(fs, e->u.strval); ++ e->k = VK; ++} ++ ++ ++/* ++** Fix an expression to return one result. ++** If expression is not a multi-ret expression (function call or ++** vararg), it already returns one result, so nothing needs to be done. ++** Function calls become VNONRELOC expressions (as its result comes ++** fixed in the base register of the call), while vararg expressions ++** become VRELOC (as OP_VARARG puts its results where it wants). ++** (Calls are created returning one result, so that does not need ++** to be fixed.) ++*/ ++void luaK_setoneret (FuncState *fs, expdesc *e) { ++ if (e->k == VCALL) { /* expression is an open function call? */ ++ /* already returns 1 value */ ++ lua_assert(GETARG_C(getinstruction(fs, e)) == 2); ++ e->k = VNONRELOC; /* result has fixed position */ ++ e->u.info = GETARG_A(getinstruction(fs, e)); ++ } ++ else if (e->k == VVARARG) { ++ SETARG_C(getinstruction(fs, e), 2); ++ e->k = VRELOC; /* can relocate its simple result */ ++ } ++} ++ ++ ++/* ++** Ensure that expression 'e' is not a variable (nor a ). ++** (Expression still may have jump lists.) ++*/ ++void luaK_dischargevars (FuncState *fs, expdesc *e) { ++ switch (e->k) { ++ case VCONST: { ++ const2exp(const2val(fs, e), e); ++ break; ++ } ++ case VLOCAL: { /* already in a register */ ++ e->u.info = e->u.var.ridx; ++ e->k = VNONRELOC; /* becomes a non-relocatable value */ ++ break; ++ } ++ case VUPVAL: { /* move value to some (pending) register */ ++ e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0); ++ e->k = VRELOC; ++ break; ++ } ++ case VINDEXUP: { ++ e->u.info = luaK_codeABC(fs, OP_GETTABUP, 0, e->u.ind.t, e->u.ind.idx); ++ e->k = VRELOC; ++ break; ++ } ++ case VINDEXI: { ++ freereg(fs, e->u.ind.t); ++ e->u.info = luaK_codeABC(fs, OP_GETI, 0, e->u.ind.t, e->u.ind.idx); ++ e->k = VRELOC; ++ break; ++ } ++ case VINDEXSTR: { ++ freereg(fs, e->u.ind.t); ++ e->u.info = luaK_codeABC(fs, OP_GETFIELD, 0, e->u.ind.t, e->u.ind.idx); ++ e->k = VRELOC; ++ break; ++ } ++ case VINDEXED: { ++ freeregs(fs, e->u.ind.t, e->u.ind.idx); ++ e->u.info = luaK_codeABC(fs, OP_GETTABLE, 0, e->u.ind.t, e->u.ind.idx); ++ e->k = VRELOC; ++ break; ++ } ++ case VVARARG: case VCALL: { ++ luaK_setoneret(fs, e); ++ break; ++ } ++ default: break; /* there is one value available (somewhere) */ ++ } ++} ++ ++ ++/* ++** Ensure expression value is in register 'reg', making 'e' a ++** non-relocatable expression. ++** (Expression still may have jump lists.) ++*/ ++static void discharge2reg (FuncState *fs, expdesc *e, int reg) { ++ luaK_dischargevars(fs, e); ++ switch (e->k) { ++ case VNIL: { ++ luaK_nil(fs, reg, 1); ++ break; ++ } ++ case VFALSE: { ++ luaK_codeABC(fs, OP_LOADFALSE, reg, 0, 0); ++ break; ++ } ++ case VTRUE: { ++ luaK_codeABC(fs, OP_LOADTRUE, reg, 0, 0); ++ break; ++ } ++ case VKSTR: { ++ str2K(fs, e); ++ } /* FALLTHROUGH */ ++ case VK: { ++ luaK_codek(fs, reg, e->u.info); ++ break; ++ } ++ case VKFLT: { ++ luaK_float(fs, reg, e->u.nval); ++ break; ++ } ++ case VKINT: { ++ luaK_int(fs, reg, e->u.ival); ++ break; ++ } ++ case VRELOC: { ++ Instruction *pc = &getinstruction(fs, e); ++ SETARG_A(*pc, reg); /* instruction will put result in 'reg' */ ++ break; ++ } ++ case VNONRELOC: { ++ if (reg != e->u.info) ++ luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0); ++ break; ++ } ++ default: { ++ lua_assert(e->k == VJMP); ++ return; /* nothing to do... */ ++ } ++ } ++ e->u.info = reg; ++ e->k = VNONRELOC; ++} ++ ++ ++/* ++** Ensure expression value is in a register, making 'e' a ++** non-relocatable expression. ++** (Expression still may have jump lists.) ++*/ ++static void discharge2anyreg (FuncState *fs, expdesc *e) { ++ if (e->k != VNONRELOC) { /* no fixed register yet? */ ++ luaK_reserveregs(fs, 1); /* get a register */ ++ discharge2reg(fs, e, fs->freereg-1); /* put value there */ ++ } ++} ++ ++ ++static int code_loadbool (FuncState *fs, int A, OpCode op) { ++ luaK_getlabel(fs); /* those instructions may be jump targets */ ++ return luaK_codeABC(fs, op, A, 0, 0); ++} ++ ++ ++/* ++** check whether list has any jump that do not produce a value ++** or produce an inverted value ++*/ ++static int need_value (FuncState *fs, int list) { ++ for (; list != NO_JUMP; list = getjump(fs, list)) { ++ Instruction i = *getjumpcontrol(fs, list); ++ if (GET_OPCODE(i) != OP_TESTSET) return 1; ++ } ++ return 0; /* not found */ ++} ++ ++ ++/* ++** Ensures final expression result (which includes results from its ++** jump lists) is in register 'reg'. ++** If expression has jumps, need to patch these jumps either to ++** its final position or to "load" instructions (for those tests ++** that do not produce values). ++*/ ++static void exp2reg (FuncState *fs, expdesc *e, int reg) { ++ discharge2reg(fs, e, reg); ++ if (e->k == VJMP) /* expression itself is a test? */ ++ luaK_concat(fs, &e->t, e->u.info); /* put this jump in 't' list */ ++ if (hasjumps(e)) { ++ int final; /* position after whole expression */ ++ int p_f = NO_JUMP; /* position of an eventual LOAD false */ ++ int p_t = NO_JUMP; /* position of an eventual LOAD true */ ++ if (need_value(fs, e->t) || need_value(fs, e->f)) { ++ int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs); ++ p_f = code_loadbool(fs, reg, OP_LFALSESKIP); /* skip next inst. */ ++ p_t = code_loadbool(fs, reg, OP_LOADTRUE); ++ /* jump around these booleans if 'e' is not a test */ ++ luaK_patchtohere(fs, fj); ++ } ++ final = luaK_getlabel(fs); ++ patchlistaux(fs, e->f, final, reg, p_f); ++ patchlistaux(fs, e->t, final, reg, p_t); ++ } ++ e->f = e->t = NO_JUMP; ++ e->u.info = reg; ++ e->k = VNONRELOC; ++} ++ ++ ++/* ++** Ensures final expression result is in next available register. ++*/ ++void luaK_exp2nextreg (FuncState *fs, expdesc *e) { ++ luaK_dischargevars(fs, e); ++ freeexp(fs, e); ++ luaK_reserveregs(fs, 1); ++ exp2reg(fs, e, fs->freereg - 1); ++} ++ ++ ++/* ++** Ensures final expression result is in some (any) register ++** and return that register. ++*/ ++int luaK_exp2anyreg (FuncState *fs, expdesc *e) { ++ luaK_dischargevars(fs, e); ++ if (e->k == VNONRELOC) { /* expression already has a register? */ ++ if (!hasjumps(e)) /* no jumps? */ ++ return e->u.info; /* result is already in a register */ ++ if (e->u.info >= luaY_nvarstack(fs)) { /* reg. is not a local? */ ++ exp2reg(fs, e, e->u.info); /* put final result in it */ ++ return e->u.info; ++ } ++ /* else expression has jumps and cannot change its register ++ to hold the jump values, because it is a local variable. ++ Go through to the default case. */ ++ } ++ luaK_exp2nextreg(fs, e); /* default: use next available register */ ++ return e->u.info; ++} ++ ++ ++/* ++** Ensures final expression result is either in a register ++** or in an upvalue. ++*/ ++void luaK_exp2anyregup (FuncState *fs, expdesc *e) { ++ if (e->k != VUPVAL || hasjumps(e)) ++ luaK_exp2anyreg(fs, e); ++} ++ ++ ++/* ++** Ensures final expression result is either in a register ++** or it is a constant. ++*/ ++void luaK_exp2val (FuncState *fs, expdesc *e) { ++ if (hasjumps(e)) ++ luaK_exp2anyreg(fs, e); ++ else ++ luaK_dischargevars(fs, e); ++} ++ ++ ++/* ++** Try to make 'e' a K expression with an index in the range of R/K ++** indices. Return true iff succeeded. ++*/ ++static int luaK_exp2K (FuncState *fs, expdesc *e) { ++ if (!hasjumps(e)) { ++ int info; ++ switch (e->k) { /* move constants to 'k' */ ++ case VTRUE: info = boolT(fs); break; ++ case VFALSE: info = boolF(fs); break; ++ case VNIL: info = nilK(fs); break; ++ case VKINT: info = luaK_intK(fs, e->u.ival); break; ++ case VKFLT: info = luaK_numberK(fs, e->u.nval); break; ++ case VKSTR: info = stringK(fs, e->u.strval); break; ++ case VK: info = e->u.info; break; ++ default: return 0; /* not a constant */ ++ } ++ if (info <= MAXINDEXRK) { /* does constant fit in 'argC'? */ ++ e->k = VK; /* make expression a 'K' expression */ ++ e->u.info = info; ++ return 1; ++ } ++ } ++ /* else, expression doesn't fit; leave it unchanged */ ++ return 0; ++} ++ ++ ++/* ++** Ensures final expression result is in a valid R/K index ++** (that is, it is either in a register or in 'k' with an index ++** in the range of R/K indices). ++** Returns 1 iff expression is K. ++*/ ++int luaK_exp2RK (FuncState *fs, expdesc *e) { ++ if (luaK_exp2K(fs, e)) ++ return 1; ++ else { /* not a constant in the right range: put it in a register */ ++ luaK_exp2anyreg(fs, e); ++ return 0; ++ } ++} ++ ++ ++static void codeABRK (FuncState *fs, OpCode o, int a, int b, ++ expdesc *ec) { ++ int k = luaK_exp2RK(fs, ec); ++ luaK_codeABCk(fs, o, a, b, ec->u.info, k); ++} ++ ++ ++/* ++** Generate code to store result of expression 'ex' into variable 'var'. ++*/ ++void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) { ++ switch (var->k) { ++ case VLOCAL: { ++ freeexp(fs, ex); ++ exp2reg(fs, ex, var->u.var.ridx); /* compute 'ex' into proper place */ ++ return; ++ } ++ case VUPVAL: { ++ int e = luaK_exp2anyreg(fs, ex); ++ luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0); ++ break; ++ } ++ case VINDEXUP: { ++ codeABRK(fs, OP_SETTABUP, var->u.ind.t, var->u.ind.idx, ex); ++ break; ++ } ++ case VINDEXI: { ++ codeABRK(fs, OP_SETI, var->u.ind.t, var->u.ind.idx, ex); ++ break; ++ } ++ case VINDEXSTR: { ++ codeABRK(fs, OP_SETFIELD, var->u.ind.t, var->u.ind.idx, ex); ++ break; ++ } ++ case VINDEXED: { ++ codeABRK(fs, OP_SETTABLE, var->u.ind.t, var->u.ind.idx, ex); ++ break; ++ } ++ default: lua_assert(0); /* invalid var kind to store */ ++ } ++ freeexp(fs, ex); ++} ++ ++ ++/* ++** Emit SELF instruction (convert expression 'e' into 'e:key(e,'). ++*/ ++void luaK_self (FuncState *fs, expdesc *e, expdesc *key) { ++ int ereg; ++ luaK_exp2anyreg(fs, e); ++ ereg = e->u.info; /* register where 'e' was placed */ ++ freeexp(fs, e); ++ e->u.info = fs->freereg; /* base register for op_self */ ++ e->k = VNONRELOC; /* self expression has a fixed register */ ++ luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */ ++ codeABRK(fs, OP_SELF, e->u.info, ereg, key); ++ freeexp(fs, key); ++} ++ ++ ++/* ++** Negate condition 'e' (where 'e' is a comparison). ++*/ ++static void negatecondition (FuncState *fs, expdesc *e) { ++ Instruction *pc = getjumpcontrol(fs, e->u.info); ++ lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET && ++ GET_OPCODE(*pc) != OP_TEST); ++ SETARG_k(*pc, (GETARG_k(*pc) ^ 1)); ++} ++ ++ ++/* ++** Emit instruction to jump if 'e' is 'cond' (that is, if 'cond' ++** is true, code will jump if 'e' is true.) Return jump position. ++** Optimize when 'e' is 'not' something, inverting the condition ++** and removing the 'not'. ++*/ ++static int jumponcond (FuncState *fs, expdesc *e, int cond) { ++ if (e->k == VRELOC) { ++ Instruction ie = getinstruction(fs, e); ++ if (GET_OPCODE(ie) == OP_NOT) { ++ removelastinstruction(fs); /* remove previous OP_NOT */ ++ return condjump(fs, OP_TEST, GETARG_B(ie), 0, 0, !cond); ++ } ++ /* else go through */ ++ } ++ discharge2anyreg(fs, e); ++ freeexp(fs, e); ++ return condjump(fs, OP_TESTSET, NO_REG, e->u.info, 0, cond); ++} ++ ++ ++/* ++** Emit code to go through if 'e' is true, jump otherwise. ++*/ ++void luaK_goiftrue (FuncState *fs, expdesc *e) { ++ int pc; /* pc of new jump */ ++ luaK_dischargevars(fs, e); ++ switch (e->k) { ++ case VJMP: { /* condition? */ ++ negatecondition(fs, e); /* jump when it is false */ ++ pc = e->u.info; /* save jump position */ ++ break; ++ } ++ case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: { ++ pc = NO_JUMP; /* always true; do nothing */ ++ break; ++ } ++ default: { ++ pc = jumponcond(fs, e, 0); /* jump when false */ ++ break; ++ } ++ } ++ luaK_concat(fs, &e->f, pc); /* insert new jump in false list */ ++ luaK_patchtohere(fs, e->t); /* true list jumps to here (to go through) */ ++ e->t = NO_JUMP; ++} ++ ++ ++/* ++** Emit code to go through if 'e' is false, jump otherwise. ++*/ ++void luaK_goiffalse (FuncState *fs, expdesc *e) { ++ int pc; /* pc of new jump */ ++ luaK_dischargevars(fs, e); ++ switch (e->k) { ++ case VJMP: { ++ pc = e->u.info; /* already jump if true */ ++ break; ++ } ++ case VNIL: case VFALSE: { ++ pc = NO_JUMP; /* always false; do nothing */ ++ break; ++ } ++ default: { ++ pc = jumponcond(fs, e, 1); /* jump if true */ ++ break; ++ } ++ } ++ luaK_concat(fs, &e->t, pc); /* insert new jump in 't' list */ ++ luaK_patchtohere(fs, e->f); /* false list jumps to here (to go through) */ ++ e->f = NO_JUMP; ++} ++ ++ ++/* ++** Code 'not e', doing constant folding. ++*/ ++static void codenot (FuncState *fs, expdesc *e) { ++ switch (e->k) { ++ case VNIL: case VFALSE: { ++ e->k = VTRUE; /* true == not nil == not false */ ++ break; ++ } ++ case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: { ++ e->k = VFALSE; /* false == not "x" == not 0.5 == not 1 == not true */ ++ break; ++ } ++ case VJMP: { ++ negatecondition(fs, e); ++ break; ++ } ++ case VRELOC: ++ case VNONRELOC: { ++ discharge2anyreg(fs, e); ++ freeexp(fs, e); ++ e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0); ++ e->k = VRELOC; ++ break; ++ } ++ default: lua_assert(0); /* cannot happen */ ++ } ++ /* interchange true and false lists */ ++ { int temp = e->f; e->f = e->t; e->t = temp; } ++ removevalues(fs, e->f); /* values are useless when negated */ ++ removevalues(fs, e->t); ++} ++ ++ ++/* ++** Check whether expression 'e' is a small literal string ++*/ ++static int isKstr (FuncState *fs, expdesc *e) { ++ return (e->k == VK && !hasjumps(e) && e->u.info <= MAXARG_B && ++ ttisshrstring(&fs->f->k[e->u.info])); ++} ++ ++/* ++** Check whether expression 'e' is a literal integer. ++*/ ++int luaK_isKint (expdesc *e) { ++ return (e->k == VKINT && !hasjumps(e)); ++} ++ ++ ++/* ++** Check whether expression 'e' is a literal integer in ++** proper range to fit in register C ++*/ ++static int isCint (expdesc *e) { ++ return luaK_isKint(e) && (l_castS2U(e->u.ival) <= l_castS2U(MAXARG_C)); ++} ++ ++ ++/* ++** Check whether expression 'e' is a literal integer in ++** proper range to fit in register sC ++*/ ++static int isSCint (expdesc *e) { ++ return luaK_isKint(e) && fitsC(e->u.ival); ++} ++ ++ ++/* ++** Check whether expression 'e' is a literal integer or float in ++** proper range to fit in a register (sB or sC). ++*/ ++static int isSCnumber (expdesc *e, int *pi, int *isfloat) { ++ lua_Integer i; ++ if (e->k == VKINT) ++ i = e->u.ival; ++ else if (e->k == VKFLT && luaV_flttointeger(e->u.nval, &i, F2Ieq)) ++ *isfloat = 1; ++ else ++ return 0; /* not a number */ ++ if (!hasjumps(e) && fitsC(i)) { ++ *pi = int2sC(cast_int(i)); ++ return 1; ++ } ++ else ++ return 0; ++} ++ ++ ++/* ++** Create expression 't[k]'. 't' must have its final result already in a ++** register or upvalue. Upvalues can only be indexed by literal strings. ++** Keys can be literal strings in the constant table or arbitrary ++** values in registers. ++*/ ++void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) { ++ if (k->k == VKSTR) ++ str2K(fs, k); ++ lua_assert(!hasjumps(t) && ++ (t->k == VLOCAL || t->k == VNONRELOC || t->k == VUPVAL)); ++ if (t->k == VUPVAL && !isKstr(fs, k)) /* upvalue indexed by non 'Kstr'? */ ++ luaK_exp2anyreg(fs, t); /* put it in a register */ ++ if (t->k == VUPVAL) { ++ t->u.ind.t = t->u.info; /* upvalue index */ ++ t->u.ind.idx = k->u.info; /* literal string */ ++ t->k = VINDEXUP; ++ } ++ else { ++ /* register index of the table */ ++ t->u.ind.t = (t->k == VLOCAL) ? t->u.var.ridx: t->u.info; ++ if (isKstr(fs, k)) { ++ t->u.ind.idx = k->u.info; /* literal string */ ++ t->k = VINDEXSTR; ++ } ++ else if (isCint(k)) { ++ t->u.ind.idx = cast_int(k->u.ival); /* int. constant in proper range */ ++ t->k = VINDEXI; ++ } ++ else { ++ t->u.ind.idx = luaK_exp2anyreg(fs, k); /* register */ ++ t->k = VINDEXED; ++ } ++ } ++} ++ ++ ++/* ++** Return false if folding can raise an error. ++** Bitwise operations need operands convertible to integers; division ++** operations cannot have 0 as divisor. ++*/ ++static int validop (int op, TValue *v1, TValue *v2) { ++ switch (op) { ++ case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR: ++ case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* conversion errors */ ++ lua_Integer i; ++ return (luaV_tointegerns(v1, &i, LUA_FLOORN2I) && ++ luaV_tointegerns(v2, &i, LUA_FLOORN2I)); ++ } ++ case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */ ++ return (nvalue(v2) != 0); ++ default: return 1; /* everything else is valid */ ++ } ++} ++ ++ ++/* ++** Try to "constant-fold" an operation; return 1 iff successful. ++** (In this case, 'e1' has the final result.) ++*/ ++static int constfolding (FuncState *fs, int op, expdesc *e1, ++ const expdesc *e2) { ++ TValue v1, v2, res; ++ if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2)) ++ return 0; /* non-numeric operands or not safe to fold */ ++ luaO_rawarith(fs->ls->L, op, &v1, &v2, &res); /* does operation */ ++ if (ttisinteger(&res)) { ++ e1->k = VKINT; ++ e1->u.ival = ivalue(&res); ++ } ++ else { /* folds neither NaN nor 0.0 (to avoid problems with -0.0) */ ++ lua_Number n = fltvalue(&res); ++ if (luai_numisnan(n) || n == 0) ++ return 0; ++ e1->k = VKFLT; ++ e1->u.nval = n; ++ } ++ return 1; ++} ++ ++ ++/* ++** Emit code for unary expressions that "produce values" ++** (everything but 'not'). ++** Expression to produce final result will be encoded in 'e'. ++*/ ++static void codeunexpval (FuncState *fs, OpCode op, expdesc *e, int line) { ++ int r = luaK_exp2anyreg(fs, e); /* opcodes operate only on registers */ ++ freeexp(fs, e); ++ e->u.info = luaK_codeABC(fs, op, 0, r, 0); /* generate opcode */ ++ e->k = VRELOC; /* all those operations are relocatable */ ++ luaK_fixline(fs, line); ++} ++ ++ ++/* ++** Emit code for binary expressions that "produce values" ++** (everything but logical operators 'and'/'or' and comparison ++** operators). ++** Expression to produce final result will be encoded in 'e1'. ++*/ ++static void finishbinexpval (FuncState *fs, expdesc *e1, expdesc *e2, ++ OpCode op, int v2, int flip, int line, ++ OpCode mmop, TMS event) { ++ int v1 = luaK_exp2anyreg(fs, e1); ++ int pc = luaK_codeABCk(fs, op, 0, v1, v2, 0); ++ freeexps(fs, e1, e2); ++ e1->u.info = pc; ++ e1->k = VRELOC; /* all those operations are relocatable */ ++ luaK_fixline(fs, line); ++ luaK_codeABCk(fs, mmop, v1, v2, event, flip); /* to call metamethod */ ++ luaK_fixline(fs, line); ++} ++ ++ ++/* ++** Emit code for binary expressions that "produce values" over ++** two registers. ++*/ ++static void codebinexpval (FuncState *fs, OpCode op, ++ expdesc *e1, expdesc *e2, int line) { ++ int v2 = luaK_exp2anyreg(fs, e2); /* both operands are in registers */ ++ lua_assert(OP_ADD <= op && op <= OP_SHR); ++ finishbinexpval(fs, e1, e2, op, v2, 0, line, OP_MMBIN, ++ cast(TMS, (op - OP_ADD) + TM_ADD)); ++} ++ ++ ++/* ++** Code binary operators with immediate operands. ++*/ ++static void codebini (FuncState *fs, OpCode op, ++ expdesc *e1, expdesc *e2, int flip, int line, ++ TMS event) { ++ int v2 = int2sC(cast_int(e2->u.ival)); /* immediate operand */ ++ lua_assert(e2->k == VKINT); ++ finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINI, event); ++} ++ ++ ++/* Try to code a binary operator negating its second operand. ++** For the metamethod, 2nd operand must keep its original value. ++*/ ++static int finishbinexpneg (FuncState *fs, expdesc *e1, expdesc *e2, ++ OpCode op, int line, TMS event) { ++ if (!luaK_isKint(e2)) ++ return 0; /* not an integer constant */ ++ else { ++ lua_Integer i2 = e2->u.ival; ++ if (!(fitsC(i2) && fitsC(-i2))) ++ return 0; /* not in the proper range */ ++ else { /* operating a small integer constant */ ++ int v2 = cast_int(i2); ++ finishbinexpval(fs, e1, e2, op, int2sC(-v2), 0, line, OP_MMBINI, event); ++ /* correct metamethod argument */ ++ SETARG_B(fs->f->code[fs->pc - 1], int2sC(v2)); ++ return 1; /* successfully coded */ ++ } ++ } ++} ++ ++ ++static void swapexps (expdesc *e1, expdesc *e2) { ++ expdesc temp = *e1; *e1 = *e2; *e2 = temp; /* swap 'e1' and 'e2' */ ++} ++ ++ ++/* ++** Code arithmetic operators ('+', '-', ...). If second operand is a ++** constant in the proper range, use variant opcodes with K operands. ++*/ ++static void codearith (FuncState *fs, BinOpr opr, ++ expdesc *e1, expdesc *e2, int flip, int line) { ++ TMS event = cast(TMS, opr + TM_ADD); ++ if (tonumeral(e2, NULL) && luaK_exp2K(fs, e2)) { /* K operand? */ ++ int v2 = e2->u.info; /* K index */ ++ OpCode op = cast(OpCode, opr + OP_ADDK); ++ finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINK, event); ++ } ++ else { /* 'e2' is neither an immediate nor a K operand */ ++ OpCode op = cast(OpCode, opr + OP_ADD); ++ if (flip) ++ swapexps(e1, e2); /* back to original order */ ++ codebinexpval(fs, op, e1, e2, line); /* use standard operators */ ++ } ++} ++ ++ ++/* ++** Code commutative operators ('+', '*'). If first operand is a ++** numeric constant, change order of operands to try to use an ++** immediate or K operator. ++*/ ++static void codecommutative (FuncState *fs, BinOpr op, ++ expdesc *e1, expdesc *e2, int line) { ++ int flip = 0; ++ if (tonumeral(e1, NULL)) { /* is first operand a numeric constant? */ ++ swapexps(e1, e2); /* change order */ ++ flip = 1; ++ } ++ if (op == OPR_ADD && isSCint(e2)) /* immediate operand? */ ++ codebini(fs, cast(OpCode, OP_ADDI), e1, e2, flip, line, TM_ADD); ++ else ++ codearith(fs, op, e1, e2, flip, line); ++} ++ ++ ++/* ++** Code bitwise operations; they are all associative, so the function ++** tries to put an integer constant as the 2nd operand (a K operand). ++*/ ++static void codebitwise (FuncState *fs, BinOpr opr, ++ expdesc *e1, expdesc *e2, int line) { ++ int flip = 0; ++ int v2; ++ OpCode op; ++ if (e1->k == VKINT && luaK_exp2RK(fs, e1)) { ++ swapexps(e1, e2); /* 'e2' will be the constant operand */ ++ flip = 1; ++ } ++ else if (!(e2->k == VKINT && luaK_exp2RK(fs, e2))) { /* no constants? */ ++ op = cast(OpCode, opr + OP_ADD); ++ codebinexpval(fs, op, e1, e2, line); /* all-register opcodes */ ++ return; ++ } ++ v2 = e2->u.info; /* index in K array */ ++ op = cast(OpCode, opr + OP_ADDK); ++ lua_assert(ttisinteger(&fs->f->k[v2])); ++ finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINK, ++ cast(TMS, opr + TM_ADD)); ++} ++ ++ ++/* ++** Emit code for order comparisons. When using an immediate operand, ++** 'isfloat' tells whether the original value was a float. ++*/ ++static void codeorder (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2) { ++ int r1, r2; ++ int im; ++ int isfloat = 0; ++ if (isSCnumber(e2, &im, &isfloat)) { ++ /* use immediate operand */ ++ r1 = luaK_exp2anyreg(fs, e1); ++ r2 = im; ++ op = cast(OpCode, (op - OP_LT) + OP_LTI); ++ } ++ else if (isSCnumber(e1, &im, &isfloat)) { ++ /* transform (A < B) to (B > A) and (A <= B) to (B >= A) */ ++ r1 = luaK_exp2anyreg(fs, e2); ++ r2 = im; ++ op = (op == OP_LT) ? OP_GTI : OP_GEI; ++ } ++ else { /* regular case, compare two registers */ ++ r1 = luaK_exp2anyreg(fs, e1); ++ r2 = luaK_exp2anyreg(fs, e2); ++ } ++ freeexps(fs, e1, e2); ++ e1->u.info = condjump(fs, op, r1, r2, isfloat, 1); ++ e1->k = VJMP; ++} ++ ++ ++/* ++** Emit code for equality comparisons ('==', '~='). ++** 'e1' was already put as RK by 'luaK_infix'. ++*/ ++static void codeeq (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) { ++ int r1, r2; ++ int im; ++ int isfloat = 0; /* not needed here, but kept for symmetry */ ++ OpCode op; ++ if (e1->k != VNONRELOC) { ++ lua_assert(e1->k == VK || e1->k == VKINT || e1->k == VKFLT); ++ swapexps(e1, e2); ++ } ++ r1 = luaK_exp2anyreg(fs, e1); /* 1st expression must be in register */ ++ if (isSCnumber(e2, &im, &isfloat)) { ++ op = OP_EQI; ++ r2 = im; /* immediate operand */ ++ } ++ else if (luaK_exp2RK(fs, e2)) { /* 1st expression is constant? */ ++ op = OP_EQK; ++ r2 = e2->u.info; /* constant index */ ++ } ++ else { ++ op = OP_EQ; /* will compare two registers */ ++ r2 = luaK_exp2anyreg(fs, e2); ++ } ++ freeexps(fs, e1, e2); ++ e1->u.info = condjump(fs, op, r1, r2, isfloat, (opr == OPR_EQ)); ++ e1->k = VJMP; ++} ++ ++ ++/* ++** Apply prefix operation 'op' to expression 'e'. ++*/ ++void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) { ++ static const expdesc ef = {VKINT, {0}, NO_JUMP, NO_JUMP}; ++ luaK_dischargevars(fs, e); ++ switch (op) { ++ case OPR_MINUS: case OPR_BNOT: /* use 'ef' as fake 2nd operand */ ++ if (constfolding(fs, op + LUA_OPUNM, e, &ef)) ++ break; ++ /* else */ /* FALLTHROUGH */ ++ case OPR_LEN: ++ codeunexpval(fs, cast(OpCode, op + OP_UNM), e, line); ++ break; ++ case OPR_NOT: codenot(fs, e); break; ++ default: lua_assert(0); ++ } ++} ++ ++ ++/* ++** Process 1st operand 'v' of binary operation 'op' before reading ++** 2nd operand. ++*/ ++void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) { ++ luaK_dischargevars(fs, v); ++ switch (op) { ++ case OPR_AND: { ++ luaK_goiftrue(fs, v); /* go ahead only if 'v' is true */ ++ break; ++ } ++ case OPR_OR: { ++ luaK_goiffalse(fs, v); /* go ahead only if 'v' is false */ ++ break; ++ } ++ case OPR_CONCAT: { ++ luaK_exp2nextreg(fs, v); /* operand must be on the stack */ ++ break; ++ } ++ case OPR_ADD: case OPR_SUB: ++ case OPR_MUL: case OPR_DIV: case OPR_IDIV: ++ case OPR_MOD: case OPR_POW: ++ case OPR_BAND: case OPR_BOR: case OPR_BXOR: ++ case OPR_SHL: case OPR_SHR: { ++ if (!tonumeral(v, NULL)) ++ luaK_exp2anyreg(fs, v); ++ /* else keep numeral, which may be folded with 2nd operand */ ++ break; ++ } ++ case OPR_EQ: case OPR_NE: { ++ if (!tonumeral(v, NULL)) ++ luaK_exp2RK(fs, v); ++ /* else keep numeral, which may be an immediate operand */ ++ break; ++ } ++ case OPR_LT: case OPR_LE: ++ case OPR_GT: case OPR_GE: { ++ int dummy, dummy2; ++ if (!isSCnumber(v, &dummy, &dummy2)) ++ luaK_exp2anyreg(fs, v); ++ /* else keep numeral, which may be an immediate operand */ ++ break; ++ } ++ default: lua_assert(0); ++ } ++} ++ ++/* ++** Create code for '(e1 .. e2)'. ++** For '(e1 .. e2.1 .. e2.2)' (which is '(e1 .. (e2.1 .. e2.2))', ++** because concatenation is right associative), merge both CONCATs. ++*/ ++static void codeconcat (FuncState *fs, expdesc *e1, expdesc *e2, int line) { ++ Instruction *ie2 = previousinstruction(fs); ++ if (GET_OPCODE(*ie2) == OP_CONCAT) { /* is 'e2' a concatenation? */ ++ int n = GETARG_B(*ie2); /* # of elements concatenated in 'e2' */ ++ lua_assert(e1->u.info + 1 == GETARG_A(*ie2)); ++ freeexp(fs, e2); ++ SETARG_A(*ie2, e1->u.info); /* correct first element ('e1') */ ++ SETARG_B(*ie2, n + 1); /* will concatenate one more element */ ++ } ++ else { /* 'e2' is not a concatenation */ ++ luaK_codeABC(fs, OP_CONCAT, e1->u.info, 2, 0); /* new concat opcode */ ++ freeexp(fs, e2); ++ luaK_fixline(fs, line); ++ } ++} ++ ++ ++/* ++** Finalize code for binary operation, after reading 2nd operand. ++*/ ++void luaK_posfix (FuncState *fs, BinOpr opr, ++ expdesc *e1, expdesc *e2, int line) { ++ luaK_dischargevars(fs, e2); ++ if (foldbinop(opr) && constfolding(fs, opr + LUA_OPADD, e1, e2)) ++ return; /* done by folding */ ++ switch (opr) { ++ case OPR_AND: { ++ lua_assert(e1->t == NO_JUMP); /* list closed by 'luaK_infix' */ ++ luaK_concat(fs, &e2->f, e1->f); ++ *e1 = *e2; ++ break; ++ } ++ case OPR_OR: { ++ lua_assert(e1->f == NO_JUMP); /* list closed by 'luaK_infix' */ ++ luaK_concat(fs, &e2->t, e1->t); ++ *e1 = *e2; ++ break; ++ } ++ case OPR_CONCAT: { /* e1 .. e2 */ ++ luaK_exp2nextreg(fs, e2); ++ codeconcat(fs, e1, e2, line); ++ break; ++ } ++ case OPR_ADD: case OPR_MUL: { ++ codecommutative(fs, opr, e1, e2, line); ++ break; ++ } ++ case OPR_SUB: { ++ if (finishbinexpneg(fs, e1, e2, OP_ADDI, line, TM_SUB)) ++ break; /* coded as (r1 + -I) */ ++ /* ELSE */ ++ } /* FALLTHROUGH */ ++ case OPR_DIV: case OPR_IDIV: case OPR_MOD: case OPR_POW: { ++ codearith(fs, opr, e1, e2, 0, line); ++ break; ++ } ++ case OPR_BAND: case OPR_BOR: case OPR_BXOR: { ++ codebitwise(fs, opr, e1, e2, line); ++ break; ++ } ++ case OPR_SHL: { ++ if (isSCint(e1)) { ++ swapexps(e1, e2); ++ codebini(fs, OP_SHLI, e1, e2, 1, line, TM_SHL); /* I << r2 */ ++ } ++ else if (finishbinexpneg(fs, e1, e2, OP_SHRI, line, TM_SHL)) { ++ /* coded as (r1 >> -I) */; ++ } ++ else /* regular case (two registers) */ ++ codebinexpval(fs, OP_SHL, e1, e2, line); ++ break; ++ } ++ case OPR_SHR: { ++ if (isSCint(e2)) ++ codebini(fs, OP_SHRI, e1, e2, 0, line, TM_SHR); /* r1 >> I */ ++ else /* regular case (two registers) */ ++ codebinexpval(fs, OP_SHR, e1, e2, line); ++ break; ++ } ++ case OPR_EQ: case OPR_NE: { ++ codeeq(fs, opr, e1, e2); ++ break; ++ } ++ case OPR_LT: case OPR_LE: { ++ OpCode op = cast(OpCode, (opr - OPR_EQ) + OP_EQ); ++ codeorder(fs, op, e1, e2); ++ break; ++ } ++ case OPR_GT: case OPR_GE: { ++ /* '(a > b)' <=> '(b < a)'; '(a >= b)' <=> '(b <= a)' */ ++ OpCode op = cast(OpCode, (opr - OPR_NE) + OP_EQ); ++ swapexps(e1, e2); ++ codeorder(fs, op, e1, e2); ++ break; ++ } ++ default: lua_assert(0); ++ } ++} ++ ++ ++/* ++** Change line information associated with current position, by removing ++** previous info and adding it again with new line. ++*/ ++void luaK_fixline (FuncState *fs, int line) { ++ removelastlineinfo(fs); ++ savelineinfo(fs, fs->f, line); ++} ++ ++ ++void luaK_settablesize (FuncState *fs, int pc, int ra, int asize, int hsize) { ++ Instruction *inst = &fs->f->code[pc]; ++ int rb = (hsize != 0) ? luaO_ceillog2(hsize) + 1 : 0; /* hash size */ ++ int extra = asize / (MAXARG_C + 1); /* higher bits of array size */ ++ int rc = asize % (MAXARG_C + 1); /* lower bits of array size */ ++ int k = (extra > 0); /* true iff needs extra argument */ ++ *inst = CREATE_ABCk(OP_NEWTABLE, ra, rb, rc, k); ++ *(inst + 1) = CREATE_Ax(OP_EXTRAARG, extra); ++} ++ ++ ++/* ++** Emit a SETLIST instruction. ++** 'base' is register that keeps table; ++** 'nelems' is #table plus those to be stored now; ++** 'tostore' is number of values (in registers 'base + 1',...) to add to ++** table (or LUA_MULTRET to add up to stack top). ++*/ ++void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) { ++ lua_assert(tostore != 0 && tostore <= LFIELDS_PER_FLUSH); ++ if (tostore == LUA_MULTRET) ++ tostore = 0; ++ if (nelems <= MAXARG_C) ++ luaK_codeABC(fs, OP_SETLIST, base, tostore, nelems); ++ else { ++ int extra = nelems / (MAXARG_C + 1); ++ nelems %= (MAXARG_C + 1); ++ luaK_codeABCk(fs, OP_SETLIST, base, tostore, nelems, 1); ++ codeextraarg(fs, extra); ++ } ++ fs->freereg = base + 1; /* free registers with list values */ ++} ++ ++ ++/* ++** return the final target of a jump (skipping jumps to jumps) ++*/ ++static int finaltarget (Instruction *code, int i) { ++ int count; ++ for (count = 0; count < 100; count++) { /* avoid infinite loops */ ++ Instruction pc = code[i]; ++ if (GET_OPCODE(pc) != OP_JMP) ++ break; ++ else ++ i += GETARG_sJ(pc) + 1; ++ } ++ return i; ++} ++ ++ ++/* ++** Do a final pass over the code of a function, doing small peephole ++** optimizations and adjustments. ++*/ ++void luaK_finish (FuncState *fs) { ++ int i; ++ Proto *p = fs->f; ++ for (i = 0; i < fs->pc; i++) { ++ Instruction *pc = &p->code[i]; ++ lua_assert(i == 0 || isOT(*(pc - 1)) == isIT(*pc)); ++ switch (GET_OPCODE(*pc)) { ++ case OP_RETURN0: case OP_RETURN1: { ++ if (!(fs->needclose || p->is_vararg)) ++ break; /* no extra work */ ++ /* else use OP_RETURN to do the extra work */ ++ SET_OPCODE(*pc, OP_RETURN); ++ } /* FALLTHROUGH */ ++ case OP_RETURN: case OP_TAILCALL: { ++ if (fs->needclose) ++ SETARG_k(*pc, 1); /* signal that it needs to close */ ++ if (p->is_vararg) ++ SETARG_C(*pc, p->numparams + 1); /* signal that it is vararg */ ++ break; ++ } ++ case OP_JMP: { ++ int target = finaltarget(p->code, i); ++ fixjump(fs, i, target); ++ break; ++ } ++ default: break; ++ } ++ } ++} +diff --git a/src/bin/lua/lcode.h b/src/bin/lua/lcode.h +new file mode 100644 +index 0000000000..3265824452 +--- /dev/null ++++ b/src/bin/lua/lcode.h +@@ -0,0 +1,104 @@ ++/* ++** $Id: lcode.h $ ++** Code generator for Lua ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef lcode_h ++#define lcode_h ++ ++#include "llex.h" ++#include "lobject.h" ++#include "lopcodes.h" ++#include "lparser.h" ++ ++ ++/* ++** Marks the end of a patch list. It is an invalid value both as an absolute ++** address, and as a list link (would link an element to itself). ++*/ ++#define NO_JUMP (-1) ++ ++ ++/* ++** grep "ORDER OPR" if you change these enums (ORDER OP) ++*/ ++typedef enum BinOpr { ++ /* arithmetic operators */ ++ OPR_ADD, OPR_SUB, OPR_MUL, OPR_MOD, OPR_POW, ++ OPR_DIV, OPR_IDIV, ++ /* bitwise operators */ ++ OPR_BAND, OPR_BOR, OPR_BXOR, ++ OPR_SHL, OPR_SHR, ++ /* string operator */ ++ OPR_CONCAT, ++ /* comparison operators */ ++ OPR_EQ, OPR_LT, OPR_LE, ++ OPR_NE, OPR_GT, OPR_GE, ++ /* logical operators */ ++ OPR_AND, OPR_OR, ++ OPR_NOBINOPR ++} BinOpr; ++ ++ ++/* true if operation is foldable (that is, it is arithmetic or bitwise) */ ++#define foldbinop(op) ((op) <= OPR_SHR) ++ ++ ++#define luaK_codeABC(fs,o,a,b,c) luaK_codeABCk(fs,o,a,b,c,0) ++ ++ ++typedef enum UnOpr { OPR_MINUS, OPR_BNOT, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr; ++ ++ ++/* get (pointer to) instruction of given 'expdesc' */ ++#define getinstruction(fs,e) ((fs)->f->code[(e)->u.info]) ++ ++ ++#define luaK_setmultret(fs,e) luaK_setreturns(fs, e, LUA_MULTRET) ++ ++#define luaK_jumpto(fs,t) luaK_patchlist(fs, luaK_jump(fs), t) ++ ++LUAI_FUNC int luaK_code (FuncState *fs, Instruction i); ++LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx); ++LUAI_FUNC int luaK_codeAsBx (FuncState *fs, OpCode o, int A, int Bx); ++LUAI_FUNC int luaK_codeABCk (FuncState *fs, OpCode o, int A, ++ int B, int C, int k); ++LUAI_FUNC int luaK_isKint (expdesc *e); ++LUAI_FUNC int luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v); ++LUAI_FUNC void luaK_fixline (FuncState *fs, int line); ++LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n); ++LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n); ++LUAI_FUNC void luaK_checkstack (FuncState *fs, int n); ++LUAI_FUNC void luaK_int (FuncState *fs, int reg, lua_Integer n); ++LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e); ++LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e); ++LUAI_FUNC void luaK_exp2anyregup (FuncState *fs, expdesc *e); ++LUAI_FUNC void luaK_exp2nextreg (FuncState *fs, expdesc *e); ++LUAI_FUNC void luaK_exp2val (FuncState *fs, expdesc *e); ++LUAI_FUNC int luaK_exp2RK (FuncState *fs, expdesc *e); ++LUAI_FUNC void luaK_self (FuncState *fs, expdesc *e, expdesc *key); ++LUAI_FUNC void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k); ++LUAI_FUNC void luaK_goiftrue (FuncState *fs, expdesc *e); ++LUAI_FUNC void luaK_goiffalse (FuncState *fs, expdesc *e); ++LUAI_FUNC void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e); ++LUAI_FUNC void luaK_setreturns (FuncState *fs, expdesc *e, int nresults); ++LUAI_FUNC void luaK_setoneret (FuncState *fs, expdesc *e); ++LUAI_FUNC int luaK_jump (FuncState *fs); ++LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret); ++LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target); ++LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list); ++LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2); ++LUAI_FUNC int luaK_getlabel (FuncState *fs); ++LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v, int line); ++LUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v); ++LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1, ++ expdesc *v2, int line); ++LUAI_FUNC void luaK_settablesize (FuncState *fs, int pc, ++ int ra, int asize, int hsize); ++LUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore); ++LUAI_FUNC void luaK_finish (FuncState *fs); ++LUAI_FUNC l_noret luaK_semerror (LexState *ls, const char *msg); ++ ++ ++#endif +diff --git a/src/bin/lua/lcorolib.c b/src/bin/lua/lcorolib.c +new file mode 100644 +index 0000000000..fedbebec39 +--- /dev/null ++++ b/src/bin/lua/lcorolib.c +@@ -0,0 +1,210 @@ ++/* ++** $Id: lcorolib.c $ ++** Coroutine Library ++** See Copyright Notice in lua.h ++*/ ++ ++#define lcorolib_c ++#define LUA_LIB ++ ++#include "lprefix.h" ++ ++ ++#include ++ ++#include "lua.h" ++ ++#include "lauxlib.h" ++#include "lualib.h" ++ ++ ++static lua_State *getco (lua_State *L) { ++ lua_State *co = lua_tothread(L, 1); ++ luaL_argexpected(L, co, 1, "thread"); ++ return co; ++} ++ ++ ++/* ++** Resumes a coroutine. Returns the number of results for non-error ++** cases or -1 for errors. ++*/ ++static int auxresume (lua_State *L, lua_State *co, int narg) { ++ int status, nres; ++ if (l_unlikely(!lua_checkstack(co, narg))) { ++ lua_pushliteral(L, "too many arguments to resume"); ++ return -1; /* error flag */ ++ } ++ lua_xmove(L, co, narg); ++ status = lua_resume(co, L, narg, &nres); ++ if (l_likely(status == LUA_OK || status == LUA_YIELD)) { ++ if (l_unlikely(!lua_checkstack(L, nres + 1))) { ++ lua_pop(co, nres); /* remove results anyway */ ++ lua_pushliteral(L, "too many results to resume"); ++ return -1; /* error flag */ ++ } ++ lua_xmove(co, L, nres); /* move yielded values */ ++ return nres; ++ } ++ else { ++ lua_xmove(co, L, 1); /* move error message */ ++ return -1; /* error flag */ ++ } ++} ++ ++ ++static int luaB_coresume (lua_State *L) { ++ lua_State *co = getco(L); ++ int r; ++ r = auxresume(L, co, lua_gettop(L) - 1); ++ if (l_unlikely(r < 0)) { ++ lua_pushboolean(L, 0); ++ lua_insert(L, -2); ++ return 2; /* return false + error message */ ++ } ++ else { ++ lua_pushboolean(L, 1); ++ lua_insert(L, -(r + 1)); ++ return r + 1; /* return true + 'resume' returns */ ++ } ++} ++ ++ ++static int luaB_auxwrap (lua_State *L) { ++ lua_State *co = lua_tothread(L, lua_upvalueindex(1)); ++ int r = auxresume(L, co, lua_gettop(L)); ++ if (l_unlikely(r < 0)) { /* error? */ ++ int stat = lua_status(co); ++ if (stat != LUA_OK && stat != LUA_YIELD) { /* error in the coroutine? */ ++ stat = lua_resetthread(co); /* close its tbc variables */ ++ lua_assert(stat != LUA_OK); ++ lua_xmove(co, L, 1); /* copy error message */ ++ } ++ if (stat != LUA_ERRMEM && /* not a memory error and ... */ ++ lua_type(L, -1) == LUA_TSTRING) { /* ... error object is a string? */ ++ luaL_where(L, 1); /* add extra info, if available */ ++ lua_insert(L, -2); ++ lua_concat(L, 2); ++ } ++ return lua_error(L); /* propagate error */ ++ } ++ return r; ++} ++ ++ ++static int luaB_cocreate (lua_State *L) { ++ lua_State *NL; ++ luaL_checktype(L, 1, LUA_TFUNCTION); ++ NL = lua_newthread(L); ++ lua_pushvalue(L, 1); /* move function to top */ ++ lua_xmove(L, NL, 1); /* move function from L to NL */ ++ return 1; ++} ++ ++ ++static int luaB_cowrap (lua_State *L) { ++ luaB_cocreate(L); ++ lua_pushcclosure(L, luaB_auxwrap, 1); ++ return 1; ++} ++ ++ ++static int luaB_yield (lua_State *L) { ++ return lua_yield(L, lua_gettop(L)); ++} ++ ++ ++#define COS_RUN 0 ++#define COS_DEAD 1 ++#define COS_YIELD 2 ++#define COS_NORM 3 ++ ++ ++static const char *const statname[] = ++ {"running", "dead", "suspended", "normal"}; ++ ++ ++static int auxstatus (lua_State *L, lua_State *co) { ++ if (L == co) return COS_RUN; ++ else { ++ switch (lua_status(co)) { ++ case LUA_YIELD: ++ return COS_YIELD; ++ case LUA_OK: { ++ lua_Debug ar; ++ if (lua_getstack(co, 0, &ar)) /* does it have frames? */ ++ return COS_NORM; /* it is running */ ++ else if (lua_gettop(co) == 0) ++ return COS_DEAD; ++ else ++ return COS_YIELD; /* initial state */ ++ } ++ default: /* some error occurred */ ++ return COS_DEAD; ++ } ++ } ++} ++ ++ ++static int luaB_costatus (lua_State *L) { ++ lua_State *co = getco(L); ++ lua_pushstring(L, statname[auxstatus(L, co)]); ++ return 1; ++} ++ ++ ++static int luaB_yieldable (lua_State *L) { ++ lua_State *co = lua_isnone(L, 1) ? L : getco(L); ++ lua_pushboolean(L, lua_isyieldable(co)); ++ return 1; ++} ++ ++ ++static int luaB_corunning (lua_State *L) { ++ int ismain = lua_pushthread(L); ++ lua_pushboolean(L, ismain); ++ return 2; ++} ++ ++ ++static int luaB_close (lua_State *L) { ++ lua_State *co = getco(L); ++ int status = auxstatus(L, co); ++ switch (status) { ++ case COS_DEAD: case COS_YIELD: { ++ status = lua_resetthread(co); ++ if (status == LUA_OK) { ++ lua_pushboolean(L, 1); ++ return 1; ++ } ++ else { ++ lua_pushboolean(L, 0); ++ lua_xmove(co, L, 1); /* copy error message */ ++ return 2; ++ } ++ } ++ default: /* normal or running coroutine */ ++ return luaL_error(L, "cannot close a %s coroutine", statname[status]); ++ } ++} ++ ++ ++static const luaL_Reg co_funcs[] = { ++ {"create", luaB_cocreate}, ++ {"resume", luaB_coresume}, ++ {"running", luaB_corunning}, ++ {"status", luaB_costatus}, ++ {"wrap", luaB_cowrap}, ++ {"yield", luaB_yield}, ++ {"isyieldable", luaB_yieldable}, ++ {"close", luaB_close}, ++ {NULL, NULL} ++}; ++ ++ ++ ++LUAMOD_API int luaopen_coroutine (lua_State *L) { ++ luaL_newlib(L, co_funcs); ++ return 1; ++} ++ +diff --git a/src/bin/lua/lctype.c b/src/bin/lua/lctype.c +new file mode 100644 +index 0000000000..9542280942 +--- /dev/null ++++ b/src/bin/lua/lctype.c +@@ -0,0 +1,64 @@ ++/* ++** $Id: lctype.c $ ++** 'ctype' functions for Lua ++** See Copyright Notice in lua.h ++*/ ++ ++#define lctype_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++#include "lctype.h" ++ ++#if !LUA_USE_CTYPE /* { */ ++ ++#include ++ ++ ++#if defined (LUA_UCID) /* accept UniCode IDentifiers? */ ++/* consider all non-ascii codepoints to be alphabetic */ ++#define NONA 0x01 ++#else ++#define NONA 0x00 /* default */ ++#endif ++ ++ ++LUAI_DDEF const lu_byte luai_ctype_[UCHAR_MAX + 2] = { ++ 0x00, /* EOZ */ ++ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0. */ ++ 0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, ++ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1. */ ++ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ++ 0x0c, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, /* 2. */ ++ 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, ++ 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, /* 3. */ ++ 0x16, 0x16, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, ++ 0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 4. */ ++ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, ++ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 5. */ ++ 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x05, ++ 0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 6. */ ++ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, ++ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 7. */ ++ 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x00, ++ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* 8. */ ++ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, ++ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* 9. */ ++ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, ++ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* a. */ ++ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, ++ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* b. */ ++ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, ++ 0x00, 0x00, NONA, NONA, NONA, NONA, NONA, NONA, /* c. */ ++ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, ++ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* d. */ ++ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, ++ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* e. */ ++ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, ++ NONA, NONA, NONA, NONA, NONA, 0x00, 0x00, 0x00, /* f. */ ++ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ++}; ++ ++#endif /* } */ +diff --git a/src/bin/lua/lctype.h b/src/bin/lua/lctype.h +new file mode 100644 +index 0000000000..864e190188 +--- /dev/null ++++ b/src/bin/lua/lctype.h +@@ -0,0 +1,101 @@ ++/* ++** $Id: lctype.h $ ++** 'ctype' functions for Lua ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef lctype_h ++#define lctype_h ++ ++#include "lua.h" ++ ++ ++/* ++** WARNING: the functions defined here do not necessarily correspond ++** to the similar functions in the standard C ctype.h. They are ++** optimized for the specific needs of Lua. ++*/ ++ ++#if !defined(LUA_USE_CTYPE) ++ ++#if 'A' == 65 && '0' == 48 ++/* ASCII case: can use its own tables; faster and fixed */ ++#define LUA_USE_CTYPE 0 ++#else ++/* must use standard C ctype */ ++#define LUA_USE_CTYPE 1 ++#endif ++ ++#endif ++ ++ ++#if !LUA_USE_CTYPE /* { */ ++ ++#include ++ ++#include "llimits.h" ++ ++ ++#define ALPHABIT 0 ++#define DIGITBIT 1 ++#define PRINTBIT 2 ++#define SPACEBIT 3 ++#define XDIGITBIT 4 ++ ++ ++#define MASK(B) (1 << (B)) ++ ++ ++/* ++** add 1 to char to allow index -1 (EOZ) ++*/ ++#define testprop(c,p) (luai_ctype_[(c)+1] & (p)) ++ ++/* ++** 'lalpha' (Lua alphabetic) and 'lalnum' (Lua alphanumeric) both include '_' ++*/ ++#define lislalpha(c) testprop(c, MASK(ALPHABIT)) ++#define lislalnum(c) testprop(c, (MASK(ALPHABIT) | MASK(DIGITBIT))) ++#define lisdigit(c) testprop(c, MASK(DIGITBIT)) ++#define lisspace(c) testprop(c, MASK(SPACEBIT)) ++#define lisprint(c) testprop(c, MASK(PRINTBIT)) ++#define lisxdigit(c) testprop(c, MASK(XDIGITBIT)) ++ ++ ++/* ++** In ASCII, this 'ltolower' is correct for alphabetic characters and ++** for '.'. That is enough for Lua needs. ('check_exp' ensures that ++** the character either is an upper-case letter or is unchanged by ++** the transformation, which holds for lower-case letters and '.'.) ++*/ ++#define ltolower(c) \ ++ check_exp(('A' <= (c) && (c) <= 'Z') || (c) == ((c) | ('A' ^ 'a')), \ ++ (c) | ('A' ^ 'a')) ++ ++ ++/* one entry for each character and for -1 (EOZ) */ ++LUAI_DDEC(const lu_byte luai_ctype_[UCHAR_MAX + 2];) ++ ++ ++#else /* }{ */ ++ ++/* ++** use standard C ctypes ++*/ ++ ++#include ++ ++ ++#define lislalpha(c) (isalpha(c) || (c) == '_') ++#define lislalnum(c) (isalnum(c) || (c) == '_') ++#define lisdigit(c) (isdigit(c)) ++#define lisspace(c) (isspace(c)) ++#define lisprint(c) (isprint(c)) ++#define lisxdigit(c) (isxdigit(c)) ++ ++#define ltolower(c) (tolower(c)) ++ ++#endif /* } */ ++ ++#endif ++ +diff --git a/src/bin/lua/ldblib.c b/src/bin/lua/ldblib.c +new file mode 100644 +index 0000000000..6dcbaa9824 +--- /dev/null ++++ b/src/bin/lua/ldblib.c +@@ -0,0 +1,483 @@ ++/* ++** $Id: ldblib.c $ ++** Interface from Lua to its debug API ++** See Copyright Notice in lua.h ++*/ ++ ++#define ldblib_c ++#define LUA_LIB ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++#include ++ ++#include "lua.h" ++ ++#include "lauxlib.h" ++#include "lualib.h" ++ ++ ++/* ++** The hook table at registry[HOOKKEY] maps threads to their current ++** hook function. ++*/ ++static const char *const HOOKKEY = "_HOOKKEY"; ++ ++ ++/* ++** If L1 != L, L1 can be in any state, and therefore there are no ++** guarantees about its stack space; any push in L1 must be ++** checked. ++*/ ++static void checkstack (lua_State *L, lua_State *L1, int n) { ++ if (l_unlikely(L != L1 && !lua_checkstack(L1, n))) ++ luaL_error(L, "stack overflow"); ++} ++ ++ ++static int db_getregistry (lua_State *L) { ++ lua_pushvalue(L, LUA_REGISTRYINDEX); ++ return 1; ++} ++ ++ ++static int db_getmetatable (lua_State *L) { ++ luaL_checkany(L, 1); ++ if (!lua_getmetatable(L, 1)) { ++ lua_pushnil(L); /* no metatable */ ++ } ++ return 1; ++} ++ ++ ++static int db_setmetatable (lua_State *L) { ++ int t = lua_type(L, 2); ++ luaL_argexpected(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil or table"); ++ lua_settop(L, 2); ++ lua_setmetatable(L, 1); ++ return 1; /* return 1st argument */ ++} ++ ++ ++static int db_getuservalue (lua_State *L) { ++ int n = (int)luaL_optinteger(L, 2, 1); ++ if (lua_type(L, 1) != LUA_TUSERDATA) ++ luaL_pushfail(L); ++ else if (lua_getiuservalue(L, 1, n) != LUA_TNONE) { ++ lua_pushboolean(L, 1); ++ return 2; ++ } ++ return 1; ++} ++ ++ ++static int db_setuservalue (lua_State *L) { ++ int n = (int)luaL_optinteger(L, 3, 1); ++ luaL_checktype(L, 1, LUA_TUSERDATA); ++ luaL_checkany(L, 2); ++ lua_settop(L, 2); ++ if (!lua_setiuservalue(L, 1, n)) ++ luaL_pushfail(L); ++ return 1; ++} ++ ++ ++/* ++** Auxiliary function used by several library functions: check for ++** an optional thread as function's first argument and set 'arg' with ++** 1 if this argument is present (so that functions can skip it to ++** access their other arguments) ++*/ ++static lua_State *getthread (lua_State *L, int *arg) { ++ if (lua_isthread(L, 1)) { ++ *arg = 1; ++ return lua_tothread(L, 1); ++ } ++ else { ++ *arg = 0; ++ return L; /* function will operate over current thread */ ++ } ++} ++ ++ ++/* ++** Variations of 'lua_settable', used by 'db_getinfo' to put results ++** from 'lua_getinfo' into result table. Key is always a string; ++** value can be a string, an int, or a boolean. ++*/ ++static void settabss (lua_State *L, const char *k, const char *v) { ++ lua_pushstring(L, v); ++ lua_setfield(L, -2, k); ++} ++ ++static void settabsi (lua_State *L, const char *k, int v) { ++ lua_pushinteger(L, v); ++ lua_setfield(L, -2, k); ++} ++ ++static void settabsb (lua_State *L, const char *k, int v) { ++ lua_pushboolean(L, v); ++ lua_setfield(L, -2, k); ++} ++ ++ ++/* ++** In function 'db_getinfo', the call to 'lua_getinfo' may push ++** results on the stack; later it creates the result table to put ++** these objects. Function 'treatstackoption' puts the result from ++** 'lua_getinfo' on top of the result table so that it can call ++** 'lua_setfield'. ++*/ ++static void treatstackoption (lua_State *L, lua_State *L1, const char *fname) { ++ if (L == L1) ++ lua_rotate(L, -2, 1); /* exchange object and table */ ++ else ++ lua_xmove(L1, L, 1); /* move object to the "main" stack */ ++ lua_setfield(L, -2, fname); /* put object into table */ ++} ++ ++ ++/* ++** Calls 'lua_getinfo' and collects all results in a new table. ++** L1 needs stack space for an optional input (function) plus ++** two optional outputs (function and line table) from function ++** 'lua_getinfo'. ++*/ ++static int db_getinfo (lua_State *L) { ++ lua_Debug ar; ++ int arg; ++ lua_State *L1 = getthread(L, &arg); ++ const char *options = luaL_optstring(L, arg+2, "flnSrtu"); ++ checkstack(L, L1, 3); ++ luaL_argcheck(L, options[0] != '>', arg + 2, "invalid option '>'"); ++ if (lua_isfunction(L, arg + 1)) { /* info about a function? */ ++ options = lua_pushfstring(L, ">%s", options); /* add '>' to 'options' */ ++ lua_pushvalue(L, arg + 1); /* move function to 'L1' stack */ ++ lua_xmove(L, L1, 1); ++ } ++ else { /* stack level */ ++ if (!lua_getstack(L1, (int)luaL_checkinteger(L, arg + 1), &ar)) { ++ luaL_pushfail(L); /* level out of range */ ++ return 1; ++ } ++ } ++ if (!lua_getinfo(L1, options, &ar)) ++ return luaL_argerror(L, arg+2, "invalid option"); ++ lua_newtable(L); /* table to collect results */ ++ if (strchr(options, 'S')) { ++ lua_pushlstring(L, ar.source, ar.srclen); ++ lua_setfield(L, -2, "source"); ++ settabss(L, "short_src", ar.short_src); ++ settabsi(L, "linedefined", ar.linedefined); ++ settabsi(L, "lastlinedefined", ar.lastlinedefined); ++ settabss(L, "what", ar.what); ++ } ++ if (strchr(options, 'l')) ++ settabsi(L, "currentline", ar.currentline); ++ if (strchr(options, 'u')) { ++ settabsi(L, "nups", ar.nups); ++ settabsi(L, "nparams", ar.nparams); ++ settabsb(L, "isvararg", ar.isvararg); ++ } ++ if (strchr(options, 'n')) { ++ settabss(L, "name", ar.name); ++ settabss(L, "namewhat", ar.namewhat); ++ } ++ if (strchr(options, 'r')) { ++ settabsi(L, "ftransfer", ar.ftransfer); ++ settabsi(L, "ntransfer", ar.ntransfer); ++ } ++ if (strchr(options, 't')) ++ settabsb(L, "istailcall", ar.istailcall); ++ if (strchr(options, 'L')) ++ treatstackoption(L, L1, "activelines"); ++ if (strchr(options, 'f')) ++ treatstackoption(L, L1, "func"); ++ return 1; /* return table */ ++} ++ ++ ++static int db_getlocal (lua_State *L) { ++ int arg; ++ lua_State *L1 = getthread(L, &arg); ++ int nvar = (int)luaL_checkinteger(L, arg + 2); /* local-variable index */ ++ if (lua_isfunction(L, arg + 1)) { /* function argument? */ ++ lua_pushvalue(L, arg + 1); /* push function */ ++ lua_pushstring(L, lua_getlocal(L, NULL, nvar)); /* push local name */ ++ return 1; /* return only name (there is no value) */ ++ } ++ else { /* stack-level argument */ ++ lua_Debug ar; ++ const char *name; ++ int level = (int)luaL_checkinteger(L, arg + 1); ++ if (l_unlikely(!lua_getstack(L1, level, &ar))) /* out of range? */ ++ return luaL_argerror(L, arg+1, "level out of range"); ++ checkstack(L, L1, 1); ++ name = lua_getlocal(L1, &ar, nvar); ++ if (name) { ++ lua_xmove(L1, L, 1); /* move local value */ ++ lua_pushstring(L, name); /* push name */ ++ lua_rotate(L, -2, 1); /* re-order */ ++ return 2; ++ } ++ else { ++ luaL_pushfail(L); /* no name (nor value) */ ++ return 1; ++ } ++ } ++} ++ ++ ++static int db_setlocal (lua_State *L) { ++ int arg; ++ const char *name; ++ lua_State *L1 = getthread(L, &arg); ++ lua_Debug ar; ++ int level = (int)luaL_checkinteger(L, arg + 1); ++ int nvar = (int)luaL_checkinteger(L, arg + 2); ++ if (l_unlikely(!lua_getstack(L1, level, &ar))) /* out of range? */ ++ return luaL_argerror(L, arg+1, "level out of range"); ++ luaL_checkany(L, arg+3); ++ lua_settop(L, arg+3); ++ checkstack(L, L1, 1); ++ lua_xmove(L, L1, 1); ++ name = lua_setlocal(L1, &ar, nvar); ++ if (name == NULL) ++ lua_pop(L1, 1); /* pop value (if not popped by 'lua_setlocal') */ ++ lua_pushstring(L, name); ++ return 1; ++} ++ ++ ++/* ++** get (if 'get' is true) or set an upvalue from a closure ++*/ ++static int auxupvalue (lua_State *L, int get) { ++ const char *name; ++ int n = (int)luaL_checkinteger(L, 2); /* upvalue index */ ++ luaL_checktype(L, 1, LUA_TFUNCTION); /* closure */ ++ name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n); ++ if (name == NULL) return 0; ++ lua_pushstring(L, name); ++ lua_insert(L, -(get+1)); /* no-op if get is false */ ++ return get + 1; ++} ++ ++ ++static int db_getupvalue (lua_State *L) { ++ return auxupvalue(L, 1); ++} ++ ++ ++static int db_setupvalue (lua_State *L) { ++ luaL_checkany(L, 3); ++ return auxupvalue(L, 0); ++} ++ ++ ++/* ++** Check whether a given upvalue from a given closure exists and ++** returns its index ++*/ ++static void *checkupval (lua_State *L, int argf, int argnup, int *pnup) { ++ void *id; ++ int nup = (int)luaL_checkinteger(L, argnup); /* upvalue index */ ++ luaL_checktype(L, argf, LUA_TFUNCTION); /* closure */ ++ id = lua_upvalueid(L, argf, nup); ++ if (pnup) { ++ luaL_argcheck(L, id != NULL, argnup, "invalid upvalue index"); ++ *pnup = nup; ++ } ++ return id; ++} ++ ++ ++static int db_upvalueid (lua_State *L) { ++ void *id = checkupval(L, 1, 2, NULL); ++ if (id != NULL) ++ lua_pushlightuserdata(L, id); ++ else ++ luaL_pushfail(L); ++ return 1; ++} ++ ++ ++static int db_upvaluejoin (lua_State *L) { ++ int n1, n2; ++ checkupval(L, 1, 2, &n1); ++ checkupval(L, 3, 4, &n2); ++ luaL_argcheck(L, !lua_iscfunction(L, 1), 1, "Lua function expected"); ++ luaL_argcheck(L, !lua_iscfunction(L, 3), 3, "Lua function expected"); ++ lua_upvaluejoin(L, 1, n1, 3, n2); ++ return 0; ++} ++ ++ ++/* ++** Call hook function registered at hook table for the current ++** thread (if there is one) ++*/ ++static void hookf (lua_State *L, lua_Debug *ar) { ++ static const char *const hooknames[] = ++ {"call", "return", "line", "count", "tail call"}; ++ lua_getfield(L, LUA_REGISTRYINDEX, HOOKKEY); ++ lua_pushthread(L); ++ if (lua_rawget(L, -2) == LUA_TFUNCTION) { /* is there a hook function? */ ++ lua_pushstring(L, hooknames[(int)ar->event]); /* push event name */ ++ if (ar->currentline >= 0) ++ lua_pushinteger(L, ar->currentline); /* push current line */ ++ else lua_pushnil(L); ++ lua_assert(lua_getinfo(L, "lS", ar)); ++ lua_call(L, 2, 0); /* call hook function */ ++ } ++} ++ ++ ++/* ++** Convert a string mask (for 'sethook') into a bit mask ++*/ ++static int makemask (const char *smask, int count) { ++ int mask = 0; ++ if (strchr(smask, 'c')) mask |= LUA_MASKCALL; ++ if (strchr(smask, 'r')) mask |= LUA_MASKRET; ++ if (strchr(smask, 'l')) mask |= LUA_MASKLINE; ++ if (count > 0) mask |= LUA_MASKCOUNT; ++ return mask; ++} ++ ++ ++/* ++** Convert a bit mask (for 'gethook') into a string mask ++*/ ++static char *unmakemask (int mask, char *smask) { ++ int i = 0; ++ if (mask & LUA_MASKCALL) smask[i++] = 'c'; ++ if (mask & LUA_MASKRET) smask[i++] = 'r'; ++ if (mask & LUA_MASKLINE) smask[i++] = 'l'; ++ smask[i] = '\0'; ++ return smask; ++} ++ ++ ++static int db_sethook (lua_State *L) { ++ int arg, mask, count; ++ lua_Hook func; ++ lua_State *L1 = getthread(L, &arg); ++ if (lua_isnoneornil(L, arg+1)) { /* no hook? */ ++ lua_settop(L, arg+1); ++ func = NULL; mask = 0; count = 0; /* turn off hooks */ ++ } ++ else { ++ const char *smask = luaL_checkstring(L, arg+2); ++ luaL_checktype(L, arg+1, LUA_TFUNCTION); ++ count = (int)luaL_optinteger(L, arg + 3, 0); ++ func = hookf; mask = makemask(smask, count); ++ } ++ if (!luaL_getsubtable(L, LUA_REGISTRYINDEX, HOOKKEY)) { ++ /* table just created; initialize it */ ++ lua_pushliteral(L, "k"); ++ lua_setfield(L, -2, "__mode"); /** hooktable.__mode = "k" */ ++ lua_pushvalue(L, -1); ++ lua_setmetatable(L, -2); /* metatable(hooktable) = hooktable */ ++ } ++ checkstack(L, L1, 1); ++ lua_pushthread(L1); lua_xmove(L1, L, 1); /* key (thread) */ ++ lua_pushvalue(L, arg + 1); /* value (hook function) */ ++ lua_rawset(L, -3); /* hooktable[L1] = new Lua hook */ ++ lua_sethook(L1, func, mask, count); ++ return 0; ++} ++ ++ ++static int db_gethook (lua_State *L) { ++ int arg; ++ lua_State *L1 = getthread(L, &arg); ++ char buff[5]; ++ int mask = lua_gethookmask(L1); ++ lua_Hook hook = lua_gethook(L1); ++ if (hook == NULL) { /* no hook? */ ++ luaL_pushfail(L); ++ return 1; ++ } ++ else if (hook != hookf) /* external hook? */ ++ lua_pushliteral(L, "external hook"); ++ else { /* hook table must exist */ ++ lua_getfield(L, LUA_REGISTRYINDEX, HOOKKEY); ++ checkstack(L, L1, 1); ++ lua_pushthread(L1); lua_xmove(L1, L, 1); ++ lua_rawget(L, -2); /* 1st result = hooktable[L1] */ ++ lua_remove(L, -2); /* remove hook table */ ++ } ++ lua_pushstring(L, unmakemask(mask, buff)); /* 2nd result = mask */ ++ lua_pushinteger(L, lua_gethookcount(L1)); /* 3rd result = count */ ++ return 3; ++} ++ ++ ++static int db_debug (lua_State *L) { ++ for (;;) { ++ char buffer[250]; ++ lua_writestringerror("%s", "lua_debug> "); ++ if (fgets(buffer, sizeof(buffer), stdin) == NULL || ++ strcmp(buffer, "cont\n") == 0) ++ return 0; ++ if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") || ++ lua_pcall(L, 0, 0, 0)) ++ lua_writestringerror("%s\n", luaL_tolstring(L, -1, NULL)); ++ lua_settop(L, 0); /* remove eventual returns */ ++ } ++} ++ ++ ++static int db_traceback (lua_State *L) { ++ int arg; ++ lua_State *L1 = getthread(L, &arg); ++ const char *msg = lua_tostring(L, arg + 1); ++ if (msg == NULL && !lua_isnoneornil(L, arg + 1)) /* non-string 'msg'? */ ++ lua_pushvalue(L, arg + 1); /* return it untouched */ ++ else { ++ int level = (int)luaL_optinteger(L, arg + 2, (L == L1) ? 1 : 0); ++ luaL_traceback(L, L1, msg, level); ++ } ++ return 1; ++} ++ ++ ++static int db_setcstacklimit (lua_State *L) { ++ int limit = (int)luaL_checkinteger(L, 1); ++ int res = lua_setcstacklimit(L, limit); ++ lua_pushinteger(L, res); ++ return 1; ++} ++ ++ ++static const luaL_Reg dblib[] = { ++ {"debug", db_debug}, ++ {"getuservalue", db_getuservalue}, ++ {"gethook", db_gethook}, ++ {"getinfo", db_getinfo}, ++ {"getlocal", db_getlocal}, ++ {"getregistry", db_getregistry}, ++ {"getmetatable", db_getmetatable}, ++ {"getupvalue", db_getupvalue}, ++ {"upvaluejoin", db_upvaluejoin}, ++ {"upvalueid", db_upvalueid}, ++ {"setuservalue", db_setuservalue}, ++ {"sethook", db_sethook}, ++ {"setlocal", db_setlocal}, ++ {"setmetatable", db_setmetatable}, ++ {"setupvalue", db_setupvalue}, ++ {"traceback", db_traceback}, ++ {"setcstacklimit", db_setcstacklimit}, ++ {NULL, NULL} ++}; ++ ++ ++LUAMOD_API int luaopen_debug (lua_State *L) { ++ luaL_newlib(L, dblib); ++ return 1; ++} ++ +diff --git a/src/bin/lua/ldebug.c b/src/bin/lua/ldebug.c +new file mode 100644 +index 0000000000..1feaab229f +--- /dev/null ++++ b/src/bin/lua/ldebug.c +@@ -0,0 +1,877 @@ ++/* ++** $Id: ldebug.c $ ++** Debug Interface ++** See Copyright Notice in lua.h ++*/ ++ ++#define ldebug_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++#include ++ ++#include "lua.h" ++ ++#include "lapi.h" ++#include "lcode.h" ++#include "ldebug.h" ++#include "ldo.h" ++#include "lfunc.h" ++#include "lobject.h" ++#include "lopcodes.h" ++#include "lstate.h" ++#include "lstring.h" ++#include "ltable.h" ++#include "ltm.h" ++#include "lvm.h" ++ ++ ++ ++#define noLuaClosure(f) ((f) == NULL || (f)->c.tt == LUA_VCCL) ++ ++ ++static const char *funcnamefromcode (lua_State *L, CallInfo *ci, ++ const char **name); ++ ++ ++static int currentpc (CallInfo *ci) { ++ lua_assert(isLua(ci)); ++ return pcRel(ci->u.l.savedpc, ci_func(ci)->p); ++} ++ ++ ++/* ++** Get a "base line" to find the line corresponding to an instruction. ++** Base lines are regularly placed at MAXIWTHABS intervals, so usually ++** an integer division gets the right place. When the source file has ++** large sequences of empty/comment lines, it may need extra entries, ++** so the original estimate needs a correction. ++** If the original estimate is -1, the initial 'if' ensures that the ++** 'while' will run at least once. ++** The assertion that the estimate is a lower bound for the correct base ++** is valid as long as the debug info has been generated with the same ++** value for MAXIWTHABS or smaller. (Previous releases use a little ++** smaller value.) ++*/ ++static int getbaseline (const Proto *f, int pc, int *basepc) { ++ if (f->sizeabslineinfo == 0 || pc < f->abslineinfo[0].pc) { ++ *basepc = -1; /* start from the beginning */ ++ return f->linedefined; ++ } ++ else { ++ int i = cast_uint(pc) / MAXIWTHABS - 1; /* get an estimate */ ++ /* estimate must be a lower bond of the correct base */ ++ lua_assert(i < 0 || ++ (i < f->sizeabslineinfo && f->abslineinfo[i].pc <= pc)); ++ while (i + 1 < f->sizeabslineinfo && pc >= f->abslineinfo[i + 1].pc) ++ i++; /* low estimate; adjust it */ ++ *basepc = f->abslineinfo[i].pc; ++ return f->abslineinfo[i].line; ++ } ++} ++ ++ ++/* ++** Get the line corresponding to instruction 'pc' in function 'f'; ++** first gets a base line and from there does the increments until ++** the desired instruction. ++*/ ++int luaG_getfuncline (const Proto *f, int pc) { ++ if (f->lineinfo == NULL) /* no debug information? */ ++ return -1; ++ else { ++ int basepc; ++ int baseline = getbaseline(f, pc, &basepc); ++ while (basepc++ < pc) { /* walk until given instruction */ ++ lua_assert(f->lineinfo[basepc] != ABSLINEINFO); ++ baseline += f->lineinfo[basepc]; /* correct line */ ++ } ++ return baseline; ++ } ++} ++ ++ ++static int getcurrentline (CallInfo *ci) { ++ return luaG_getfuncline(ci_func(ci)->p, currentpc(ci)); ++} ++ ++ ++/* ++** Set 'trap' for all active Lua frames. ++** This function can be called during a signal, under "reasonable" ++** assumptions. A new 'ci' is completely linked in the list before it ++** becomes part of the "active" list, and we assume that pointers are ++** atomic; see comment in next function. ++** (A compiler doing interprocedural optimizations could, theoretically, ++** reorder memory writes in such a way that the list could be ++** temporarily broken while inserting a new element. We simply assume it ++** has no good reasons to do that.) ++*/ ++static void settraps (CallInfo *ci) { ++ for (; ci != NULL; ci = ci->previous) ++ if (isLua(ci)) ++ ci->u.l.trap = 1; ++} ++ ++ ++/* ++** This function can be called during a signal, under "reasonable" ++** assumptions. ++** Fields 'basehookcount' and 'hookcount' (set by 'resethookcount') ++** are for debug only, and it is no problem if they get arbitrary ++** values (causes at most one wrong hook call). 'hookmask' is an atomic ++** value. We assume that pointers are atomic too (e.g., gcc ensures that ++** for all platforms where it runs). Moreover, 'hook' is always checked ++** before being called (see 'luaD_hook'). ++*/ ++LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) { ++ if (func == NULL || mask == 0) { /* turn off hooks? */ ++ mask = 0; ++ func = NULL; ++ } ++ L->hook = func; ++ L->basehookcount = count; ++ resethookcount(L); ++ L->hookmask = cast_byte(mask); ++ if (mask) ++ settraps(L->ci); /* to trace inside 'luaV_execute' */ ++} ++ ++ ++LUA_API lua_Hook lua_gethook (lua_State *L) { ++ return L->hook; ++} ++ ++ ++LUA_API int lua_gethookmask (lua_State *L) { ++ return L->hookmask; ++} ++ ++ ++LUA_API int lua_gethookcount (lua_State *L) { ++ return L->basehookcount; ++} ++ ++ ++LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) { ++ int status; ++ CallInfo *ci; ++ if (level < 0) return 0; /* invalid (negative) level */ ++ lua_lock(L); ++ for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous) ++ level--; ++ if (level == 0 && ci != &L->base_ci) { /* level found? */ ++ status = 1; ++ ar->i_ci = ci; ++ } ++ else status = 0; /* no such level */ ++ lua_unlock(L); ++ return status; ++} ++ ++ ++static const char *upvalname (const Proto *p, int uv) { ++ TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name); ++ if (s == NULL) return "?"; ++ else return getstr(s); ++} ++ ++ ++static const char *findvararg (CallInfo *ci, int n, StkId *pos) { ++ if (clLvalue(s2v(ci->func))->p->is_vararg) { ++ int nextra = ci->u.l.nextraargs; ++ if (n >= -nextra) { /* 'n' is negative */ ++ *pos = ci->func - nextra - (n + 1); ++ return "(vararg)"; /* generic name for any vararg */ ++ } ++ } ++ return NULL; /* no such vararg */ ++} ++ ++ ++const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n, StkId *pos) { ++ StkId base = ci->func + 1; ++ const char *name = NULL; ++ if (isLua(ci)) { ++ if (n < 0) /* access to vararg values? */ ++ return findvararg(ci, n, pos); ++ else ++ name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci)); ++ } ++ if (name == NULL) { /* no 'standard' name? */ ++ StkId limit = (ci == L->ci) ? L->top : ci->next->func; ++ if (limit - base >= n && n > 0) { /* is 'n' inside 'ci' stack? */ ++ /* generic name for any valid slot */ ++ name = isLua(ci) ? "(temporary)" : "(C temporary)"; ++ } ++ else ++ return NULL; /* no name */ ++ } ++ if (pos) ++ *pos = base + (n - 1); ++ return name; ++} ++ ++ ++LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) { ++ const char *name; ++ lua_lock(L); ++ if (ar == NULL) { /* information about non-active function? */ ++ if (!isLfunction(s2v(L->top - 1))) /* not a Lua function? */ ++ name = NULL; ++ else /* consider live variables at function start (parameters) */ ++ name = luaF_getlocalname(clLvalue(s2v(L->top - 1))->p, n, 0); ++ } ++ else { /* active function; get information through 'ar' */ ++ StkId pos = NULL; /* to avoid warnings */ ++ name = luaG_findlocal(L, ar->i_ci, n, &pos); ++ if (name) { ++ setobjs2s(L, L->top, pos); ++ api_incr_top(L); ++ } ++ } ++ lua_unlock(L); ++ return name; ++} ++ ++ ++LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) { ++ StkId pos = NULL; /* to avoid warnings */ ++ const char *name; ++ lua_lock(L); ++ name = luaG_findlocal(L, ar->i_ci, n, &pos); ++ if (name) { ++ setobjs2s(L, pos, L->top - 1); ++ L->top--; /* pop value */ ++ } ++ lua_unlock(L); ++ return name; ++} ++ ++ ++static void funcinfo (lua_Debug *ar, Closure *cl) { ++ if (noLuaClosure(cl)) { ++ ar->source = "=[C]"; ++ ar->srclen = LL("=[C]"); ++ ar->linedefined = -1; ++ ar->lastlinedefined = -1; ++ ar->what = "C"; ++ } ++ else { ++ const Proto *p = cl->l.p; ++ if (p->source) { ++ ar->source = getstr(p->source); ++ ar->srclen = tsslen(p->source); ++ } ++ else { ++ ar->source = "=?"; ++ ar->srclen = LL("=?"); ++ } ++ ar->linedefined = p->linedefined; ++ ar->lastlinedefined = p->lastlinedefined; ++ ar->what = (ar->linedefined == 0) ? "main" : "Lua"; ++ } ++ luaO_chunkid(ar->short_src, ar->source, ar->srclen); ++} ++ ++ ++static int nextline (const Proto *p, int currentline, int pc) { ++ if (p->lineinfo[pc] != ABSLINEINFO) ++ return currentline + p->lineinfo[pc]; ++ else ++ return luaG_getfuncline(p, pc); ++} ++ ++ ++static void collectvalidlines (lua_State *L, Closure *f) { ++ if (noLuaClosure(f)) { ++ setnilvalue(s2v(L->top)); ++ api_incr_top(L); ++ } ++ else { ++ int i; ++ TValue v; ++ const Proto *p = f->l.p; ++ int currentline = p->linedefined; ++ Table *t = luaH_new(L); /* new table to store active lines */ ++ sethvalue2s(L, L->top, t); /* push it on stack */ ++ api_incr_top(L); ++ setbtvalue(&v); /* boolean 'true' to be the value of all indices */ ++ for (i = 0; i < p->sizelineinfo; i++) { /* for all instructions */ ++ currentline = nextline(p, currentline, i); /* get its line */ ++ luaH_setint(L, t, currentline, &v); /* table[line] = true */ ++ } ++ } ++} ++ ++ ++static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { ++ if (ci == NULL) /* no 'ci'? */ ++ return NULL; /* no info */ ++ else if (ci->callstatus & CIST_FIN) { /* is this a finalizer? */ ++ *name = "__gc"; ++ return "metamethod"; /* report it as such */ ++ } ++ /* calling function is a known Lua function? */ ++ else if (!(ci->callstatus & CIST_TAIL) && isLua(ci->previous)) ++ return funcnamefromcode(L, ci->previous, name); ++ else return NULL; /* no way to find a name */ ++} ++ ++ ++static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar, ++ Closure *f, CallInfo *ci) { ++ int status = 1; ++ for (; *what; what++) { ++ switch (*what) { ++ case 'S': { ++ funcinfo(ar, f); ++ break; ++ } ++ case 'l': { ++ ar->currentline = (ci && isLua(ci)) ? getcurrentline(ci) : -1; ++ break; ++ } ++ case 'u': { ++ ar->nups = (f == NULL) ? 0 : f->c.nupvalues; ++ if (noLuaClosure(f)) { ++ ar->isvararg = 1; ++ ar->nparams = 0; ++ } ++ else { ++ ar->isvararg = f->l.p->is_vararg; ++ ar->nparams = f->l.p->numparams; ++ } ++ break; ++ } ++ case 't': { ++ ar->istailcall = (ci) ? ci->callstatus & CIST_TAIL : 0; ++ break; ++ } ++ case 'n': { ++ ar->namewhat = getfuncname(L, ci, &ar->name); ++ if (ar->namewhat == NULL) { ++ ar->namewhat = ""; /* not found */ ++ ar->name = NULL; ++ } ++ break; ++ } ++ case 'r': { ++ if (ci == NULL || !(ci->callstatus & CIST_TRAN)) ++ ar->ftransfer = ar->ntransfer = 0; ++ else { ++ ar->ftransfer = ci->u2.transferinfo.ftransfer; ++ ar->ntransfer = ci->u2.transferinfo.ntransfer; ++ } ++ break; ++ } ++ case 'L': ++ case 'f': /* handled by lua_getinfo */ ++ break; ++ default: status = 0; /* invalid option */ ++ } ++ } ++ return status; ++} ++ ++ ++LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) { ++ int status; ++ Closure *cl; ++ CallInfo *ci; ++ TValue *func; ++ lua_lock(L); ++ if (*what == '>') { ++ ci = NULL; ++ func = s2v(L->top - 1); ++ api_check(L, ttisfunction(func), "function expected"); ++ what++; /* skip the '>' */ ++ L->top--; /* pop function */ ++ } ++ else { ++ ci = ar->i_ci; ++ func = s2v(ci->func); ++ lua_assert(ttisfunction(func)); ++ } ++ cl = ttisclosure(func) ? clvalue(func) : NULL; ++ status = auxgetinfo(L, what, ar, cl, ci); ++ if (strchr(what, 'f')) { ++ setobj2s(L, L->top, func); ++ api_incr_top(L); ++ } ++ if (strchr(what, 'L')) ++ collectvalidlines(L, cl); ++ lua_unlock(L); ++ return status; ++} ++ ++ ++/* ++** {====================================================== ++** Symbolic Execution ++** ======================================================= ++*/ ++ ++static const char *getobjname (const Proto *p, int lastpc, int reg, ++ const char **name); ++ ++ ++/* ++** Find a "name" for the constant 'c'. ++*/ ++static void kname (const Proto *p, int c, const char **name) { ++ TValue *kvalue = &p->k[c]; ++ *name = (ttisstring(kvalue)) ? svalue(kvalue) : "?"; ++} ++ ++ ++/* ++** Find a "name" for the register 'c'. ++*/ ++static void rname (const Proto *p, int pc, int c, const char **name) { ++ const char *what = getobjname(p, pc, c, name); /* search for 'c' */ ++ if (!(what && *what == 'c')) /* did not find a constant name? */ ++ *name = "?"; ++} ++ ++ ++/* ++** Find a "name" for a 'C' value in an RK instruction. ++*/ ++static void rkname (const Proto *p, int pc, Instruction i, const char **name) { ++ int c = GETARG_C(i); /* key index */ ++ if (GETARG_k(i)) /* is 'c' a constant? */ ++ kname(p, c, name); ++ else /* 'c' is a register */ ++ rname(p, pc, c, name); ++} ++ ++ ++static int filterpc (int pc, int jmptarget) { ++ if (pc < jmptarget) /* is code conditional (inside a jump)? */ ++ return -1; /* cannot know who sets that register */ ++ else return pc; /* current position sets that register */ ++} ++ ++ ++/* ++** Try to find last instruction before 'lastpc' that modified register 'reg'. ++*/ ++static int findsetreg (const Proto *p, int lastpc, int reg) { ++ int pc; ++ int setreg = -1; /* keep last instruction that changed 'reg' */ ++ int jmptarget = 0; /* any code before this address is conditional */ ++ if (testMMMode(GET_OPCODE(p->code[lastpc]))) ++ lastpc--; /* previous instruction was not actually executed */ ++ for (pc = 0; pc < lastpc; pc++) { ++ Instruction i = p->code[pc]; ++ OpCode op = GET_OPCODE(i); ++ int a = GETARG_A(i); ++ int change; /* true if current instruction changed 'reg' */ ++ switch (op) { ++ case OP_LOADNIL: { /* set registers from 'a' to 'a+b' */ ++ int b = GETARG_B(i); ++ change = (a <= reg && reg <= a + b); ++ break; ++ } ++ case OP_TFORCALL: { /* affect all regs above its base */ ++ change = (reg >= a + 2); ++ break; ++ } ++ case OP_CALL: ++ case OP_TAILCALL: { /* affect all registers above base */ ++ change = (reg >= a); ++ break; ++ } ++ case OP_JMP: { /* doesn't change registers, but changes 'jmptarget' */ ++ int b = GETARG_sJ(i); ++ int dest = pc + 1 + b; ++ /* jump does not skip 'lastpc' and is larger than current one? */ ++ if (dest <= lastpc && dest > jmptarget) ++ jmptarget = dest; /* update 'jmptarget' */ ++ change = 0; ++ break; ++ } ++ default: /* any instruction that sets A */ ++ change = (testAMode(op) && reg == a); ++ break; ++ } ++ if (change) ++ setreg = filterpc(pc, jmptarget); ++ } ++ return setreg; ++} ++ ++ ++/* ++** Check whether table being indexed by instruction 'i' is the ++** environment '_ENV' ++*/ ++static const char *gxf (const Proto *p, int pc, Instruction i, int isup) { ++ int t = GETARG_B(i); /* table index */ ++ const char *name; /* name of indexed variable */ ++ if (isup) /* is an upvalue? */ ++ name = upvalname(p, t); ++ else ++ getobjname(p, pc, t, &name); ++ return (name && strcmp(name, LUA_ENV) == 0) ? "global" : "field"; ++} ++ ++ ++static const char *getobjname (const Proto *p, int lastpc, int reg, ++ const char **name) { ++ int pc; ++ *name = luaF_getlocalname(p, reg + 1, lastpc); ++ if (*name) /* is a local? */ ++ return "local"; ++ /* else try symbolic execution */ ++ pc = findsetreg(p, lastpc, reg); ++ if (pc != -1) { /* could find instruction? */ ++ Instruction i = p->code[pc]; ++ OpCode op = GET_OPCODE(i); ++ switch (op) { ++ case OP_MOVE: { ++ int b = GETARG_B(i); /* move from 'b' to 'a' */ ++ if (b < GETARG_A(i)) ++ return getobjname(p, pc, b, name); /* get name for 'b' */ ++ break; ++ } ++ case OP_GETTABUP: { ++ int k = GETARG_C(i); /* key index */ ++ kname(p, k, name); ++ return gxf(p, pc, i, 1); ++ } ++ case OP_GETTABLE: { ++ int k = GETARG_C(i); /* key index */ ++ rname(p, pc, k, name); ++ return gxf(p, pc, i, 0); ++ } ++ case OP_GETI: { ++ *name = "integer index"; ++ return "field"; ++ } ++ case OP_GETFIELD: { ++ int k = GETARG_C(i); /* key index */ ++ kname(p, k, name); ++ return gxf(p, pc, i, 0); ++ } ++ case OP_GETUPVAL: { ++ *name = upvalname(p, GETARG_B(i)); ++ return "upvalue"; ++ } ++ case OP_LOADK: ++ case OP_LOADKX: { ++ int b = (op == OP_LOADK) ? GETARG_Bx(i) ++ : GETARG_Ax(p->code[pc + 1]); ++ if (ttisstring(&p->k[b])) { ++ *name = svalue(&p->k[b]); ++ return "constant"; ++ } ++ break; ++ } ++ case OP_SELF: { ++ rkname(p, pc, i, name); ++ return "method"; ++ } ++ default: break; /* go through to return NULL */ ++ } ++ } ++ return NULL; /* could not find reasonable name */ ++} ++ ++ ++/* ++** Try to find a name for a function based on the code that called it. ++** (Only works when function was called by a Lua function.) ++** Returns what the name is (e.g., "for iterator", "method", ++** "metamethod") and sets '*name' to point to the name. ++*/ ++static const char *funcnamefromcode (lua_State *L, CallInfo *ci, ++ const char **name) { ++ TMS tm = (TMS)0; /* (initial value avoids warnings) */ ++ const Proto *p = ci_func(ci)->p; /* calling function */ ++ int pc = currentpc(ci); /* calling instruction index */ ++ Instruction i = p->code[pc]; /* calling instruction */ ++ if (ci->callstatus & CIST_HOOKED) { /* was it called inside a hook? */ ++ *name = "?"; ++ return "hook"; ++ } ++ switch (GET_OPCODE(i)) { ++ case OP_CALL: ++ case OP_TAILCALL: ++ return getobjname(p, pc, GETARG_A(i), name); /* get function name */ ++ case OP_TFORCALL: { /* for iterator */ ++ *name = "for iterator"; ++ return "for iterator"; ++ } ++ /* other instructions can do calls through metamethods */ ++ case OP_SELF: case OP_GETTABUP: case OP_GETTABLE: ++ case OP_GETI: case OP_GETFIELD: ++ tm = TM_INDEX; ++ break; ++ case OP_SETTABUP: case OP_SETTABLE: case OP_SETI: case OP_SETFIELD: ++ tm = TM_NEWINDEX; ++ break; ++ case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: { ++ tm = cast(TMS, GETARG_C(i)); ++ break; ++ } ++ case OP_UNM: tm = TM_UNM; break; ++ case OP_BNOT: tm = TM_BNOT; break; ++ case OP_LEN: tm = TM_LEN; break; ++ case OP_CONCAT: tm = TM_CONCAT; break; ++ case OP_EQ: tm = TM_EQ; break; ++ /* no cases for OP_EQI and OP_EQK, as they don't call metamethods */ ++ case OP_LT: case OP_LTI: case OP_GTI: tm = TM_LT; break; ++ case OP_LE: case OP_LEI: case OP_GEI: tm = TM_LE; break; ++ case OP_CLOSE: case OP_RETURN: tm = TM_CLOSE; break; ++ default: ++ return NULL; /* cannot find a reasonable name */ ++ } ++ *name = getstr(G(L)->tmname[tm]) + 2; ++ return "metamethod"; ++} ++ ++/* }====================================================== */ ++ ++ ++ ++/* ++** Check whether pointer 'o' points to some value in the stack ++** frame of the current function. Because 'o' may not point to a ++** value in this stack, we cannot compare it with the region ++** boundaries (undefined behaviour in ISO C). ++*/ ++static int isinstack (CallInfo *ci, const TValue *o) { ++ StkId pos; ++ for (pos = ci->func + 1; pos < ci->top; pos++) { ++ if (o == s2v(pos)) ++ return 1; ++ } ++ return 0; /* not found */ ++} ++ ++ ++/* ++** Checks whether value 'o' came from an upvalue. (That can only happen ++** with instructions OP_GETTABUP/OP_SETTABUP, which operate directly on ++** upvalues.) ++*/ ++static const char *getupvalname (CallInfo *ci, const TValue *o, ++ const char **name) { ++ LClosure *c = ci_func(ci); ++ int i; ++ for (i = 0; i < c->nupvalues; i++) { ++ if (c->upvals[i]->v == o) { ++ *name = upvalname(c->p, i); ++ return "upvalue"; ++ } ++ } ++ return NULL; ++} ++ ++ ++static const char *varinfo (lua_State *L, const TValue *o) { ++ const char *name = NULL; /* to avoid warnings */ ++ CallInfo *ci = L->ci; ++ const char *kind = NULL; ++ if (isLua(ci)) { ++ kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */ ++ if (!kind && isinstack(ci, o)) /* no? try a register */ ++ kind = getobjname(ci_func(ci)->p, currentpc(ci), ++ cast_int(cast(StkId, o) - (ci->func + 1)), &name); ++ } ++ return (kind) ? luaO_pushfstring(L, " (%s '%s')", kind, name) : ""; ++} ++ ++ ++l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) { ++ const char *t = luaT_objtypename(L, o); ++ luaG_runerror(L, "attempt to %s a %s value%s", op, t, varinfo(L, o)); ++} ++ ++ ++l_noret luaG_callerror (lua_State *L, const TValue *o) { ++ CallInfo *ci = L->ci; ++ const char *name = NULL; /* to avoid warnings */ ++ const char *what = (isLua(ci)) ? funcnamefromcode(L, ci, &name) : NULL; ++ if (what != NULL) { ++ const char *t = luaT_objtypename(L, o); ++ luaG_runerror(L, "%s '%s' is not callable (a %s value)", what, name, t); ++ } ++ else ++ luaG_typeerror(L, o, "call"); ++} ++ ++ ++l_noret luaG_forerror (lua_State *L, const TValue *o, const char *what) { ++ luaG_runerror(L, "bad 'for' %s (number expected, got %s)", ++ what, luaT_objtypename(L, o)); ++} ++ ++ ++l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2) { ++ if (ttisstring(p1) || cvt2str(p1)) p1 = p2; ++ luaG_typeerror(L, p1, "concatenate"); ++} ++ ++ ++l_noret luaG_opinterror (lua_State *L, const TValue *p1, ++ const TValue *p2, const char *msg) { ++ if (!ttisnumber(p1)) /* first operand is wrong? */ ++ p2 = p1; /* now second is wrong */ ++ luaG_typeerror(L, p2, msg); ++} ++ ++ ++/* ++** Error when both values are convertible to numbers, but not to integers ++*/ ++l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) { ++ lua_Integer temp; ++ if (!luaV_tointegerns(p1, &temp, LUA_FLOORN2I)) ++ p2 = p1; ++ luaG_runerror(L, "number%s has no integer representation", varinfo(L, p2)); ++} ++ ++ ++l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) { ++ const char *t1 = luaT_objtypename(L, p1); ++ const char *t2 = luaT_objtypename(L, p2); ++ if (strcmp(t1, t2) == 0) ++ luaG_runerror(L, "attempt to compare two %s values", t1); ++ else ++ luaG_runerror(L, "attempt to compare %s with %s", t1, t2); ++} ++ ++ ++/* add src:line information to 'msg' */ ++const char *luaG_addinfo (lua_State *L, const char *msg, TString *src, ++ int line) { ++ char buff[LUA_IDSIZE]; ++ if (src) ++ luaO_chunkid(buff, getstr(src), tsslen(src)); ++ else { /* no source available; use "?" instead */ ++ buff[0] = '?'; buff[1] = '\0'; ++ } ++ return luaO_pushfstring(L, "%s:%d: %s", buff, line, msg); ++} ++ ++ ++l_noret luaG_errormsg (lua_State *L) { ++ if (L->errfunc != 0) { /* is there an error handling function? */ ++ StkId errfunc = restorestack(L, L->errfunc); ++ lua_assert(ttisfunction(s2v(errfunc))); ++ setobjs2s(L, L->top, L->top - 1); /* move argument */ ++ setobjs2s(L, L->top - 1, errfunc); /* push function */ ++ L->top++; /* assume EXTRA_STACK */ ++ luaD_callnoyield(L, L->top - 2, 1); /* call it */ ++ } ++ luaD_throw(L, LUA_ERRRUN); ++} ++ ++ ++l_noret luaG_runerror (lua_State *L, const char *fmt, ...) { ++ CallInfo *ci = L->ci; ++ const char *msg; ++ va_list argp; ++ luaC_checkGC(L); /* error message uses memory */ ++ va_start(argp, fmt); ++ msg = luaO_pushvfstring(L, fmt, argp); /* format message */ ++ va_end(argp); ++ if (isLua(ci)) /* if Lua function, add source:line information */ ++ luaG_addinfo(L, msg, ci_func(ci)->p->source, getcurrentline(ci)); ++ luaG_errormsg(L); ++} ++ ++ ++/* ++** Check whether new instruction 'newpc' is in a different line from ++** previous instruction 'oldpc'. More often than not, 'newpc' is only ++** one or a few instructions after 'oldpc' (it must be after, see ++** caller), so try to avoid calling 'luaG_getfuncline'. If they are ++** too far apart, there is a good chance of a ABSLINEINFO in the way, ++** so it goes directly to 'luaG_getfuncline'. ++*/ ++static int changedline (const Proto *p, int oldpc, int newpc) { ++ if (p->lineinfo == NULL) /* no debug information? */ ++ return 0; ++ if (newpc - oldpc < MAXIWTHABS / 2) { /* not too far apart? */ ++ int delta = 0; /* line diference */ ++ int pc = oldpc; ++ for (;;) { ++ int lineinfo = p->lineinfo[++pc]; ++ if (lineinfo == ABSLINEINFO) ++ break; /* cannot compute delta; fall through */ ++ delta += lineinfo; ++ if (pc == newpc) ++ return (delta != 0); /* delta computed successfully */ ++ } ++ } ++ /* either instructions are too far apart or there is an absolute line ++ info in the way; compute line difference explicitly */ ++ return (luaG_getfuncline(p, oldpc) != luaG_getfuncline(p, newpc)); ++} ++ ++ ++/* ++** Traces the execution of a Lua function. Called before the execution ++** of each opcode, when debug is on. 'L->oldpc' stores the last ++** instruction traced, to detect line changes. When entering a new ++** function, 'npci' will be zero and will test as a new line whatever ++** the value of 'oldpc'. Some exceptional conditions may return to ++** a function without setting 'oldpc'. In that case, 'oldpc' may be ++** invalid; if so, use zero as a valid value. (A wrong but valid 'oldpc' ++** at most causes an extra call to a line hook.) ++** This function is not "Protected" when called, so it should correct ++** 'L->top' before calling anything that can run the GC. ++*/ ++int luaG_traceexec (lua_State *L, const Instruction *pc) { ++ CallInfo *ci = L->ci; ++ lu_byte mask = L->hookmask; ++ const Proto *p = ci_func(ci)->p; ++ int counthook; ++ if (!(mask & (LUA_MASKLINE | LUA_MASKCOUNT))) { /* no hooks? */ ++ ci->u.l.trap = 0; /* don't need to stop again */ ++ return 0; /* turn off 'trap' */ ++ } ++ pc++; /* reference is always next instruction */ ++ ci->u.l.savedpc = pc; /* save 'pc' */ ++ counthook = (--L->hookcount == 0 && (mask & LUA_MASKCOUNT)); ++ if (counthook) ++ resethookcount(L); /* reset count */ ++ else if (!(mask & LUA_MASKLINE)) ++ return 1; /* no line hook and count != 0; nothing to be done now */ ++ if (ci->callstatus & CIST_HOOKYIELD) { /* called hook last time? */ ++ ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */ ++ return 1; /* do not call hook again (VM yielded, so it did not move) */ ++ } ++ if (!isIT(*(ci->u.l.savedpc - 1))) /* top not being used? */ ++ L->top = ci->top; /* correct top */ ++ if (counthook) ++ luaD_hook(L, LUA_HOOKCOUNT, -1, 0, 0); /* call count hook */ ++ if (mask & LUA_MASKLINE) { ++ /* 'L->oldpc' may be invalid; use zero in this case */ ++ int oldpc = (L->oldpc < p->sizecode) ? L->oldpc : 0; ++ int npci = pcRel(pc, p); ++ if (npci <= oldpc || /* call hook when jump back (loop), */ ++ changedline(p, oldpc, npci)) { /* or when enter new line */ ++ int newline = luaG_getfuncline(p, npci); ++ luaD_hook(L, LUA_HOOKLINE, newline, 0, 0); /* call line hook */ ++ } ++ L->oldpc = npci; /* 'pc' of last call to line hook */ ++ } ++ if (L->status == LUA_YIELD) { /* did hook yield? */ ++ if (counthook) ++ L->hookcount = 1; /* undo decrement to zero */ ++ ci->u.l.savedpc--; /* undo increment (resume will increment it again) */ ++ ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */ ++ luaD_throw(L, LUA_YIELD); ++ } ++ return 1; /* keep 'trap' on */ ++} ++ +diff --git a/src/bin/lua/ldebug.h b/src/bin/lua/ldebug.h +new file mode 100644 +index 0000000000..974960e99d +--- /dev/null ++++ b/src/bin/lua/ldebug.h +@@ -0,0 +1,63 @@ ++/* ++** $Id: ldebug.h $ ++** Auxiliary functions from Debug Interface module ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef ldebug_h ++#define ldebug_h ++ ++ ++#include "lstate.h" ++ ++ ++#define pcRel(pc, p) (cast_int((pc) - (p)->code) - 1) ++ ++ ++/* Active Lua function (given call info) */ ++#define ci_func(ci) (clLvalue(s2v((ci)->func))) ++ ++ ++#define resethookcount(L) (L->hookcount = L->basehookcount) ++ ++/* ++** mark for entries in 'lineinfo' array that has absolute information in ++** 'abslineinfo' array ++*/ ++#define ABSLINEINFO (-0x80) ++ ++ ++/* ++** MAXimum number of successive Instructions WiTHout ABSolute line ++** information. (A power of two allows fast divisions.) ++*/ ++#if !defined(MAXIWTHABS) ++#define MAXIWTHABS 128 ++#endif ++ ++ ++LUAI_FUNC int luaG_getfuncline (const Proto *f, int pc); ++LUAI_FUNC const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n, ++ StkId *pos); ++LUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o, ++ const char *opname); ++LUAI_FUNC l_noret luaG_callerror (lua_State *L, const TValue *o); ++LUAI_FUNC l_noret luaG_forerror (lua_State *L, const TValue *o, ++ const char *what); ++LUAI_FUNC l_noret luaG_concaterror (lua_State *L, const TValue *p1, ++ const TValue *p2); ++LUAI_FUNC l_noret luaG_opinterror (lua_State *L, const TValue *p1, ++ const TValue *p2, ++ const char *msg); ++LUAI_FUNC l_noret luaG_tointerror (lua_State *L, const TValue *p1, ++ const TValue *p2); ++LUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1, ++ const TValue *p2); ++LUAI_FUNC l_noret luaG_runerror (lua_State *L, const char *fmt, ...); ++LUAI_FUNC const char *luaG_addinfo (lua_State *L, const char *msg, ++ TString *src, int line); ++LUAI_FUNC l_noret luaG_errormsg (lua_State *L); ++LUAI_FUNC int luaG_traceexec (lua_State *L, const Instruction *pc); ++ ++ ++#endif +diff --git a/src/bin/lua/ldo.c b/src/bin/lua/ldo.c +new file mode 100644 +index 0000000000..7135079b12 +--- /dev/null ++++ b/src/bin/lua/ldo.c +@@ -0,0 +1,963 @@ ++/* ++** $Id: ldo.c $ ++** Stack and Call structure of Lua ++** See Copyright Notice in lua.h ++*/ ++ ++#define ldo_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++#include ++ ++#include "lua.h" ++ ++#include "lapi.h" ++#include "ldebug.h" ++#include "ldo.h" ++#include "lfunc.h" ++#include "lgc.h" ++#include "lmem.h" ++#include "lobject.h" ++#include "lopcodes.h" ++#include "lparser.h" ++#include "lstate.h" ++#include "lstring.h" ++#include "ltable.h" ++#include "ltm.h" ++#include "lundump.h" ++#include "lvm.h" ++#include "lzio.h" ++ ++ ++ ++#define errorstatus(s) ((s) > LUA_YIELD) ++ ++ ++/* ++** {====================================================== ++** Error-recovery functions ++** ======================================================= ++*/ ++ ++/* ++** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By ++** default, Lua handles errors with exceptions when compiling as ++** C++ code, with _longjmp/_setjmp when asked to use them, and with ++** longjmp/setjmp otherwise. ++*/ ++#if !defined(LUAI_THROW) /* { */ ++ ++#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) /* { */ ++ ++/* C++ exceptions */ ++#define LUAI_THROW(L,c) throw(c) ++#define LUAI_TRY(L,c,a) \ ++ try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; } ++#define luai_jmpbuf int /* dummy variable */ ++ ++#elif defined(LUA_USE_POSIX) /* }{ */ ++ ++/* in POSIX, try _longjmp/_setjmp (more efficient) */ ++#define LUAI_THROW(L,c) _longjmp((c)->b, 1) ++#define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a } ++#define luai_jmpbuf jmp_buf ++ ++#else /* }{ */ ++ ++/* ISO C handling with long jumps */ ++#define LUAI_THROW(L,c) longjmp((c)->b, 1) ++#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a } ++#define luai_jmpbuf jmp_buf ++ ++#endif /* } */ ++ ++#endif /* } */ ++ ++ ++ ++/* chain list of long jump buffers */ ++struct lua_longjmp { ++ struct lua_longjmp *previous; ++ luai_jmpbuf b; ++ volatile int status; /* error code */ ++}; ++ ++ ++void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) { ++ switch (errcode) { ++ case LUA_ERRMEM: { /* memory error? */ ++ setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */ ++ break; ++ } ++ case LUA_ERRERR: { ++ setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling")); ++ break; ++ } ++ case LUA_OK: { /* special case only for closing upvalues */ ++ setnilvalue(s2v(oldtop)); /* no error message */ ++ break; ++ } ++ default: { ++ lua_assert(errorstatus(errcode)); /* real error */ ++ setobjs2s(L, oldtop, L->top - 1); /* error message on current top */ ++ break; ++ } ++ } ++ L->top = oldtop + 1; ++} ++ ++ ++l_noret luaD_throw (lua_State *L, int errcode) { ++ if (L->errorJmp) { /* thread has an error handler? */ ++ L->errorJmp->status = errcode; /* set status */ ++ LUAI_THROW(L, L->errorJmp); /* jump to it */ ++ } ++ else { /* thread has no error handler */ ++ global_State *g = G(L); ++ errcode = luaE_resetthread(L, errcode); /* close all upvalues */ ++ if (g->mainthread->errorJmp) { /* main thread has a handler? */ ++ setobjs2s(L, g->mainthread->top++, L->top - 1); /* copy error obj. */ ++ luaD_throw(g->mainthread, errcode); /* re-throw in main thread */ ++ } ++ else { /* no handler at all; abort */ ++ if (g->panic) { /* panic function? */ ++ lua_unlock(L); ++ g->panic(L); /* call panic function (last chance to jump out) */ ++ } ++ abort(); ++ } ++ } ++} ++ ++ ++int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) { ++ l_uint32 oldnCcalls = L->nCcalls; ++ struct lua_longjmp lj; ++ lj.status = LUA_OK; ++ lj.previous = L->errorJmp; /* chain new error handler */ ++ L->errorJmp = &lj; ++ LUAI_TRY(L, &lj, ++ (*f)(L, ud); ++ ); ++ L->errorJmp = lj.previous; /* restore old error handler */ ++ L->nCcalls = oldnCcalls; ++ return lj.status; ++} ++ ++/* }====================================================== */ ++ ++ ++/* ++** {================================================================== ++** Stack reallocation ++** =================================================================== ++*/ ++static void correctstack (lua_State *L, StkId oldstack, StkId newstack) { ++ CallInfo *ci; ++ UpVal *up; ++ L->top = (L->top - oldstack) + newstack; ++ L->tbclist = (L->tbclist - oldstack) + newstack; ++ for (up = L->openupval; up != NULL; up = up->u.open.next) ++ up->v = s2v((uplevel(up) - oldstack) + newstack); ++ for (ci = L->ci; ci != NULL; ci = ci->previous) { ++ ci->top = (ci->top - oldstack) + newstack; ++ ci->func = (ci->func - oldstack) + newstack; ++ if (isLua(ci)) ++ ci->u.l.trap = 1; /* signal to update 'trap' in 'luaV_execute' */ ++ } ++} ++ ++ ++/* some space for error handling */ ++#define ERRORSTACKSIZE (LUAI_MAXSTACK + 200) ++ ++ ++/* ++** Reallocate the stack to a new size, correcting all pointers into ++** it. (There are pointers to a stack from its upvalues, from its list ++** of call infos, plus a few individual pointers.) The reallocation is ++** done in two steps (allocation + free) because the correction must be ++** done while both addresses (the old stack and the new one) are valid. ++** (In ISO C, any pointer use after the pointer has been deallocated is ++** undefined behavior.) ++** In case of allocation error, raise an error or return false according ++** to 'raiseerror'. ++*/ ++int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) { ++ int oldsize = stacksize(L); ++ int i; ++ StkId newstack = luaM_reallocvector(L, NULL, 0, ++ newsize + EXTRA_STACK, StackValue); ++ lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE); ++ if (l_unlikely(newstack == NULL)) { /* reallocation failed? */ ++ if (raiseerror) ++ luaM_error(L); ++ else return 0; /* do not raise an error */ ++ } ++ /* number of elements to be copied to the new stack */ ++ i = ((oldsize <= newsize) ? oldsize : newsize) + EXTRA_STACK; ++ memcpy(newstack, L->stack, i * sizeof(StackValue)); ++ for (; i < newsize + EXTRA_STACK; i++) ++ setnilvalue(s2v(newstack + i)); /* erase new segment */ ++ correctstack(L, L->stack, newstack); ++ luaM_freearray(L, L->stack, oldsize + EXTRA_STACK); ++ L->stack = newstack; ++ L->stack_last = L->stack + newsize; ++ return 1; ++} ++ ++ ++/* ++** Try to grow the stack by at least 'n' elements. when 'raiseerror' ++** is true, raises any error; otherwise, return 0 in case of errors. ++*/ ++int luaD_growstack (lua_State *L, int n, int raiseerror) { ++ int size = stacksize(L); ++ if (l_unlikely(size > LUAI_MAXSTACK)) { ++ /* if stack is larger than maximum, thread is already using the ++ extra space reserved for errors, that is, thread is handling ++ a stack error; cannot grow further than that. */ ++ lua_assert(stacksize(L) == ERRORSTACKSIZE); ++ if (raiseerror) ++ luaD_throw(L, LUA_ERRERR); /* error inside message handler */ ++ return 0; /* if not 'raiseerror', just signal it */ ++ } ++ else { ++ int newsize = 2 * size; /* tentative new size */ ++ int needed = cast_int(L->top - L->stack) + n; ++ if (newsize > LUAI_MAXSTACK) /* cannot cross the limit */ ++ newsize = LUAI_MAXSTACK; ++ if (newsize < needed) /* but must respect what was asked for */ ++ newsize = needed; ++ if (l_likely(newsize <= LUAI_MAXSTACK)) ++ return luaD_reallocstack(L, newsize, raiseerror); ++ else { /* stack overflow */ ++ /* add extra size to be able to handle the error message */ ++ luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror); ++ if (raiseerror) ++ luaG_runerror(L, "stack overflow"); ++ return 0; ++ } ++ } ++} ++ ++ ++static int stackinuse (lua_State *L) { ++ CallInfo *ci; ++ int res; ++ StkId lim = L->top; ++ for (ci = L->ci; ci != NULL; ci = ci->previous) { ++ if (lim < ci->top) lim = ci->top; ++ } ++ lua_assert(lim <= L->stack_last); ++ res = cast_int(lim - L->stack) + 1; /* part of stack in use */ ++ if (res < LUA_MINSTACK) ++ res = LUA_MINSTACK; /* ensure a minimum size */ ++ return res; ++} ++ ++ ++/* ++** If stack size is more than 3 times the current use, reduce that size ++** to twice the current use. (So, the final stack size is at most 2/3 the ++** previous size, and half of its entries are empty.) ++** As a particular case, if stack was handling a stack overflow and now ++** it is not, 'max' (limited by LUAI_MAXSTACK) will be smaller than ++** stacksize (equal to ERRORSTACKSIZE in this case), and so the stack ++** will be reduced to a "regular" size. ++*/ ++void luaD_shrinkstack (lua_State *L) { ++ int inuse = stackinuse(L); ++ int nsize = inuse * 2; /* proposed new size */ ++ int max = inuse * 3; /* maximum "reasonable" size */ ++ if (max > LUAI_MAXSTACK) { ++ max = LUAI_MAXSTACK; /* respect stack limit */ ++ if (nsize > LUAI_MAXSTACK) ++ nsize = LUAI_MAXSTACK; ++ } ++ /* if thread is currently not handling a stack overflow and its ++ size is larger than maximum "reasonable" size, shrink it */ ++ if (inuse <= LUAI_MAXSTACK && stacksize(L) > max) ++ luaD_reallocstack(L, nsize, 0); /* ok if that fails */ ++ else /* don't change stack */ ++ condmovestack(L,{},{}); /* (change only for debugging) */ ++ luaE_shrinkCI(L); /* shrink CI list */ ++} ++ ++ ++void luaD_inctop (lua_State *L) { ++ luaD_checkstack(L, 1); ++ L->top++; ++} ++ ++/* }================================================================== */ ++ ++ ++/* ++** Call a hook for the given event. Make sure there is a hook to be ++** called. (Both 'L->hook' and 'L->hookmask', which trigger this ++** function, can be changed asynchronously by signals.) ++*/ ++void luaD_hook (lua_State *L, int event, int line, ++ int ftransfer, int ntransfer) { ++ lua_Hook hook = L->hook; ++ if (hook && L->allowhook) { /* make sure there is a hook */ ++ int mask = CIST_HOOKED; ++ CallInfo *ci = L->ci; ++ ptrdiff_t top = savestack(L, L->top); /* preserve original 'top' */ ++ ptrdiff_t ci_top = savestack(L, ci->top); /* idem for 'ci->top' */ ++ lua_Debug ar; ++ ar.event = event; ++ ar.currentline = line; ++ ar.i_ci = ci; ++ if (ntransfer != 0) { ++ mask |= CIST_TRAN; /* 'ci' has transfer information */ ++ ci->u2.transferinfo.ftransfer = ftransfer; ++ ci->u2.transferinfo.ntransfer = ntransfer; ++ } ++ if (isLua(ci) && L->top < ci->top) ++ L->top = ci->top; /* protect entire activation register */ ++ luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ ++ if (ci->top < L->top + LUA_MINSTACK) ++ ci->top = L->top + LUA_MINSTACK; ++ L->allowhook = 0; /* cannot call hooks inside a hook */ ++ ci->callstatus |= mask; ++ lua_unlock(L); ++ (*hook)(L, &ar); ++ lua_lock(L); ++ lua_assert(!L->allowhook); ++ L->allowhook = 1; ++ ci->top = restorestack(L, ci_top); ++ L->top = restorestack(L, top); ++ ci->callstatus &= ~mask; ++ } ++} ++ ++ ++/* ++** Executes a call hook for Lua functions. This function is called ++** whenever 'hookmask' is not zero, so it checks whether call hooks are ++** active. ++*/ ++void luaD_hookcall (lua_State *L, CallInfo *ci) { ++ L->oldpc = 0; /* set 'oldpc' for new function */ ++ if (L->hookmask & LUA_MASKCALL) { /* is call hook on? */ ++ int event = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL ++ : LUA_HOOKCALL; ++ Proto *p = ci_func(ci)->p; ++ ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */ ++ luaD_hook(L, event, -1, 1, p->numparams); ++ ci->u.l.savedpc--; /* correct 'pc' */ ++ } ++} ++ ++ ++/* ++** Executes a return hook for Lua and C functions and sets/corrects ++** 'oldpc'. (Note that this correction is needed by the line hook, so it ++** is done even when return hooks are off.) ++*/ ++static void rethook (lua_State *L, CallInfo *ci, int nres) { ++ if (L->hookmask & LUA_MASKRET) { /* is return hook on? */ ++ StkId firstres = L->top - nres; /* index of first result */ ++ int delta = 0; /* correction for vararg functions */ ++ int ftransfer; ++ if (isLua(ci)) { ++ Proto *p = ci_func(ci)->p; ++ if (p->is_vararg) ++ delta = ci->u.l.nextraargs + p->numparams + 1; ++ } ++ ci->func += delta; /* if vararg, back to virtual 'func' */ ++ ftransfer = cast(unsigned short, firstres - ci->func); ++ luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres); /* call it */ ++ ci->func -= delta; ++ } ++ if (isLua(ci = ci->previous)) ++ L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p); /* set 'oldpc' */ ++} ++ ++ ++/* ++** Check whether 'func' has a '__call' metafield. If so, put it in the ++** stack, below original 'func', so that 'luaD_precall' can call it. Raise ++** an error if there is no '__call' metafield. ++*/ ++void luaD_tryfuncTM (lua_State *L, StkId func) { ++ const TValue *tm = luaT_gettmbyobj(L, s2v(func), TM_CALL); ++ StkId p; ++ if (l_unlikely(ttisnil(tm))) ++ luaG_callerror(L, s2v(func)); /* nothing to call */ ++ for (p = L->top; p > func; p--) /* open space for metamethod */ ++ setobjs2s(L, p, p-1); ++ L->top++; /* stack space pre-allocated by the caller */ ++ setobj2s(L, func, tm); /* metamethod is the new function to be called */ ++} ++ ++ ++/* ++** Given 'nres' results at 'firstResult', move 'wanted' of them to 'res'. ++** Handle most typical cases (zero results for commands, one result for ++** expressions, multiple results for tail calls/single parameters) ++** separated. ++*/ ++static void moveresults (lua_State *L, StkId res, int nres, int wanted) { ++ StkId firstresult; ++ int i; ++ switch (wanted) { /* handle typical cases separately */ ++ case 0: /* no values needed */ ++ L->top = res; ++ return; ++ case 1: /* one value needed */ ++ if (nres == 0) /* no results? */ ++ setnilvalue(s2v(res)); /* adjust with nil */ ++ else /* at least one result */ ++ setobjs2s(L, res, L->top - nres); /* move it to proper place */ ++ L->top = res + 1; ++ return; ++ case LUA_MULTRET: ++ wanted = nres; /* we want all results */ ++ break; ++ default: /* two/more results and/or to-be-closed variables */ ++ if (hastocloseCfunc(wanted)) { /* to-be-closed variables? */ ++ ptrdiff_t savedres = savestack(L, res); ++ L->ci->callstatus |= CIST_CLSRET; /* in case of yields */ ++ L->ci->u2.nres = nres; ++ luaF_close(L, res, CLOSEKTOP, 1); ++ L->ci->callstatus &= ~CIST_CLSRET; ++ if (L->hookmask) /* if needed, call hook after '__close's */ ++ rethook(L, L->ci, nres); ++ res = restorestack(L, savedres); /* close and hook can move stack */ ++ wanted = decodeNresults(wanted); ++ if (wanted == LUA_MULTRET) ++ wanted = nres; /* we want all results */ ++ } ++ break; ++ } ++ /* generic case */ ++ firstresult = L->top - nres; /* index of first result */ ++ if (nres > wanted) /* extra results? */ ++ nres = wanted; /* don't need them */ ++ for (i = 0; i < nres; i++) /* move all results to correct place */ ++ setobjs2s(L, res + i, firstresult + i); ++ for (; i < wanted; i++) /* complete wanted number of results */ ++ setnilvalue(s2v(res + i)); ++ L->top = res + wanted; /* top points after the last result */ ++} ++ ++ ++/* ++** Finishes a function call: calls hook if necessary, moves current ++** number of results to proper place, and returns to previous call ++** info. If function has to close variables, hook must be called after ++** that. ++*/ ++void luaD_poscall (lua_State *L, CallInfo *ci, int nres) { ++ int wanted = ci->nresults; ++ if (l_unlikely(L->hookmask && !hastocloseCfunc(wanted))) ++ rethook(L, ci, nres); ++ /* move results to proper place */ ++ moveresults(L, ci->func, nres, wanted); ++ /* function cannot be in any of these cases when returning */ ++ lua_assert(!(ci->callstatus & ++ (CIST_HOOKED | CIST_YPCALL | CIST_FIN | CIST_TRAN | CIST_CLSRET))); ++ L->ci = ci->previous; /* back to caller (after closing variables) */ ++} ++ ++ ++ ++#define next_ci(L) (L->ci->next ? L->ci->next : luaE_extendCI(L)) ++ ++ ++/* ++** Prepare a function for a tail call, building its call info on top ++** of the current call info. 'narg1' is the number of arguments plus 1 ++** (so that it includes the function itself). ++*/ ++void luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func, int narg1) { ++ Proto *p = clLvalue(s2v(func))->p; ++ int fsize = p->maxstacksize; /* frame size */ ++ int nfixparams = p->numparams; ++ int i; ++ for (i = 0; i < narg1; i++) /* move down function and arguments */ ++ setobjs2s(L, ci->func + i, func + i); ++ checkstackGC(L, fsize); ++ func = ci->func; /* moved-down function */ ++ for (; narg1 <= nfixparams; narg1++) ++ setnilvalue(s2v(func + narg1)); /* complete missing arguments */ ++ ci->top = func + 1 + fsize; /* top for new function */ ++ lua_assert(ci->top <= L->stack_last); ++ ci->u.l.savedpc = p->code; /* starting point */ ++ ci->callstatus |= CIST_TAIL; ++ L->top = func + narg1; /* set top */ ++} ++ ++ ++/* ++** Prepares the call to a function (C or Lua). For C functions, also do ++** the call. The function to be called is at '*func'. The arguments ++** are on the stack, right after the function. Returns the CallInfo ++** to be executed, if it was a Lua function. Otherwise (a C function) ++** returns NULL, with all the results on the stack, starting at the ++** original function position. ++*/ ++CallInfo *luaD_precall (lua_State *L, StkId func, int nresults) { ++ lua_CFunction f; ++ retry: ++ switch (ttypetag(s2v(func))) { ++ case LUA_VCCL: /* C closure */ ++ f = clCvalue(s2v(func))->f; ++ goto Cfunc; ++ case LUA_VLCF: /* light C function */ ++ f = fvalue(s2v(func)); ++ Cfunc: { ++ int n; /* number of returns */ ++ CallInfo *ci; ++ checkstackGCp(L, LUA_MINSTACK, func); /* ensure minimum stack size */ ++ L->ci = ci = next_ci(L); ++ ci->nresults = nresults; ++ ci->callstatus = CIST_C; ++ ci->top = L->top + LUA_MINSTACK; ++ ci->func = func; ++ lua_assert(ci->top <= L->stack_last); ++ if (l_unlikely(L->hookmask & LUA_MASKCALL)) { ++ int narg = cast_int(L->top - func) - 1; ++ luaD_hook(L, LUA_HOOKCALL, -1, 1, narg); ++ } ++ lua_unlock(L); ++ n = (*f)(L); /* do the actual call */ ++ lua_lock(L); ++ api_checknelems(L, n); ++ luaD_poscall(L, ci, n); ++ return NULL; ++ } ++ case LUA_VLCL: { /* Lua function */ ++ CallInfo *ci; ++ Proto *p = clLvalue(s2v(func))->p; ++ int narg = cast_int(L->top - func) - 1; /* number of real arguments */ ++ int nfixparams = p->numparams; ++ int fsize = p->maxstacksize; /* frame size */ ++ checkstackGCp(L, fsize, func); ++ L->ci = ci = next_ci(L); ++ ci->nresults = nresults; ++ ci->u.l.savedpc = p->code; /* starting point */ ++ ci->top = func + 1 + fsize; ++ ci->func = func; ++ L->ci = ci; ++ for (; narg < nfixparams; narg++) ++ setnilvalue(s2v(L->top++)); /* complete missing arguments */ ++ lua_assert(ci->top <= L->stack_last); ++ return ci; ++ } ++ default: { /* not a function */ ++ checkstackGCp(L, 1, func); /* space for metamethod */ ++ luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */ ++ goto retry; /* try again with metamethod */ ++ } ++ } ++} ++ ++ ++/* ++** Call a function (C or Lua) through C. 'inc' can be 1 (increment ++** number of recursive invocations in the C stack) or nyci (the same ++** plus increment number of non-yieldable calls). ++*/ ++static void ccall (lua_State *L, StkId func, int nResults, int inc) { ++ CallInfo *ci; ++ L->nCcalls += inc; ++ if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS)) ++ luaE_checkcstack(L); ++ if ((ci = luaD_precall(L, func, nResults)) != NULL) { /* Lua function? */ ++ ci->callstatus = CIST_FRESH; /* mark that it is a "fresh" execute */ ++ luaV_execute(L, ci); /* call it */ ++ } ++ L->nCcalls -= inc; ++} ++ ++ ++/* ++** External interface for 'ccall' ++*/ ++void luaD_call (lua_State *L, StkId func, int nResults) { ++ ccall(L, func, nResults, 1); ++} ++ ++ ++/* ++** Similar to 'luaD_call', but does not allow yields during the call. ++*/ ++void luaD_callnoyield (lua_State *L, StkId func, int nResults) { ++ ccall(L, func, nResults, nyci); ++} ++ ++ ++/* ++** Finish the job of 'lua_pcallk' after it was interrupted by an yield. ++** (The caller, 'finishCcall', does the final call to 'adjustresults'.) ++** The main job is to complete the 'luaD_pcall' called by 'lua_pcallk'. ++** If a '__close' method yields here, eventually control will be back ++** to 'finishCcall' (when that '__close' method finally returns) and ++** 'finishpcallk' will run again and close any still pending '__close' ++** methods. Similarly, if a '__close' method errs, 'precover' calls ++** 'unroll' which calls ''finishCcall' and we are back here again, to ++** close any pending '__close' methods. ++** Note that, up to the call to 'luaF_close', the corresponding ++** 'CallInfo' is not modified, so that this repeated run works like the ++** first one (except that it has at least one less '__close' to do). In ++** particular, field CIST_RECST preserves the error status across these ++** multiple runs, changing only if there is a new error. ++*/ ++static int finishpcallk (lua_State *L, CallInfo *ci) { ++ int status = getcistrecst(ci); /* get original status */ ++ if (l_likely(status == LUA_OK)) /* no error? */ ++ status = LUA_YIELD; /* was interrupted by an yield */ ++ else { /* error */ ++ StkId func = restorestack(L, ci->u2.funcidx); ++ L->allowhook = getoah(ci->callstatus); /* restore 'allowhook' */ ++ luaF_close(L, func, status, 1); /* can yield or raise an error */ ++ func = restorestack(L, ci->u2.funcidx); /* stack may be moved */ ++ luaD_seterrorobj(L, status, func); ++ luaD_shrinkstack(L); /* restore stack size in case of overflow */ ++ setcistrecst(ci, LUA_OK); /* clear original status */ ++ } ++ ci->callstatus &= ~CIST_YPCALL; ++ L->errfunc = ci->u.c.old_errfunc; ++ /* if it is here, there were errors or yields; unlike 'lua_pcallk', ++ do not change status */ ++ return status; ++} ++ ++ ++/* ++** Completes the execution of a C function interrupted by an yield. ++** The interruption must have happened while the function was either ++** closing its tbc variables in 'moveresults' or executing ++** 'lua_callk'/'lua_pcallk'. In the first case, it just redoes ++** 'luaD_poscall'. In the second case, the call to 'finishpcallk' ++** finishes the interrupted execution of 'lua_pcallk'. After that, it ++** calls the continuation of the interrupted function and finally it ++** completes the job of the 'luaD_call' that called the function. In ++** the call to 'adjustresults', we do not know the number of results ++** of the function called by 'lua_callk'/'lua_pcallk', so we are ++** conservative and use LUA_MULTRET (always adjust). ++*/ ++static void finishCcall (lua_State *L, CallInfo *ci) { ++ int n; /* actual number of results from C function */ ++ if (ci->callstatus & CIST_CLSRET) { /* was returning? */ ++ lua_assert(hastocloseCfunc(ci->nresults)); ++ n = ci->u2.nres; /* just redo 'luaD_poscall' */ ++ /* don't need to reset CIST_CLSRET, as it will be set again anyway */ ++ } ++ else { ++ int status = LUA_YIELD; /* default if there were no errors */ ++ /* must have a continuation and must be able to call it */ ++ lua_assert(ci->u.c.k != NULL && yieldable(L)); ++ if (ci->callstatus & CIST_YPCALL) /* was inside a 'lua_pcallk'? */ ++ status = finishpcallk(L, ci); /* finish it */ ++ adjustresults(L, LUA_MULTRET); /* finish 'lua_callk' */ ++ lua_unlock(L); ++ n = (*ci->u.c.k)(L, status, ci->u.c.ctx); /* call continuation */ ++ lua_lock(L); ++ api_checknelems(L, n); ++ } ++ luaD_poscall(L, ci, n); /* finish 'luaD_call' */ ++} ++ ++ ++/* ++** Executes "full continuation" (everything in the stack) of a ++** previously interrupted coroutine until the stack is empty (or another ++** interruption long-jumps out of the loop). ++*/ ++static void unroll (lua_State *L, void *ud) { ++ CallInfo *ci; ++ UNUSED(ud); ++ while ((ci = L->ci) != &L->base_ci) { /* something in the stack */ ++ if (!isLua(ci)) /* C function? */ ++ finishCcall(L, ci); /* complete its execution */ ++ else { /* Lua function */ ++ luaV_finishOp(L); /* finish interrupted instruction */ ++ luaV_execute(L, ci); /* execute down to higher C 'boundary' */ ++ } ++ } ++} ++ ++ ++/* ++** Try to find a suspended protected call (a "recover point") for the ++** given thread. ++*/ ++static CallInfo *findpcall (lua_State *L) { ++ CallInfo *ci; ++ for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */ ++ if (ci->callstatus & CIST_YPCALL) ++ return ci; ++ } ++ return NULL; /* no pending pcall */ ++} ++ ++ ++/* ++** Signal an error in the call to 'lua_resume', not in the execution ++** of the coroutine itself. (Such errors should not be handled by any ++** coroutine error handler and should not kill the coroutine.) ++*/ ++static int resume_error (lua_State *L, const char *msg, int narg) { ++ L->top -= narg; /* remove args from the stack */ ++ setsvalue2s(L, L->top, luaS_new(L, msg)); /* push error message */ ++ api_incr_top(L); ++ lua_unlock(L); ++ return LUA_ERRRUN; ++} ++ ++ ++/* ++** Do the work for 'lua_resume' in protected mode. Most of the work ++** depends on the status of the coroutine: initial state, suspended ++** inside a hook, or regularly suspended (optionally with a continuation ++** function), plus erroneous cases: non-suspended coroutine or dead ++** coroutine. ++*/ ++static void resume (lua_State *L, void *ud) { ++ int n = *(cast(int*, ud)); /* number of arguments */ ++ StkId firstArg = L->top - n; /* first argument */ ++ CallInfo *ci = L->ci; ++ if (L->status == LUA_OK) /* starting a coroutine? */ ++ ccall(L, firstArg - 1, LUA_MULTRET, 1); /* just call its body */ ++ else { /* resuming from previous yield */ ++ lua_assert(L->status == LUA_YIELD); ++ L->status = LUA_OK; /* mark that it is running (again) */ ++ luaE_incCstack(L); /* control the C stack */ ++ if (isLua(ci)) { /* yielded inside a hook? */ ++ L->top = firstArg; /* discard arguments */ ++ luaV_execute(L, ci); /* just continue running Lua code */ ++ } ++ else { /* 'common' yield */ ++ if (ci->u.c.k != NULL) { /* does it have a continuation function? */ ++ lua_unlock(L); ++ n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */ ++ lua_lock(L); ++ api_checknelems(L, n); ++ } ++ luaD_poscall(L, ci, n); /* finish 'luaD_call' */ ++ } ++ unroll(L, NULL); /* run continuation */ ++ } ++} ++ ++ ++/* ++** Unrolls a coroutine in protected mode while there are recoverable ++** errors, that is, errors inside a protected call. (Any error ++** interrupts 'unroll', and this loop protects it again so it can ++** continue.) Stops with a normal end (status == LUA_OK), an yield ++** (status == LUA_YIELD), or an unprotected error ('findpcall' doesn't ++** find a recover point). ++*/ ++static int precover (lua_State *L, int status) { ++ CallInfo *ci; ++ while (errorstatus(status) && (ci = findpcall(L)) != NULL) { ++ L->ci = ci; /* go down to recovery functions */ ++ setcistrecst(ci, status); /* status to finish 'pcall' */ ++ status = luaD_rawrunprotected(L, unroll, NULL); ++ } ++ return status; ++} ++ ++ ++LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs, ++ int *nresults) { ++ int status; ++ lua_lock(L); ++ if (L->status == LUA_OK) { /* may be starting a coroutine */ ++ if (L->ci != &L->base_ci) /* not in base level? */ ++ return resume_error(L, "cannot resume non-suspended coroutine", nargs); ++ else if (L->top - (L->ci->func + 1) == nargs) /* no function? */ ++ return resume_error(L, "cannot resume dead coroutine", nargs); ++ } ++ else if (L->status != LUA_YIELD) /* ended with errors? */ ++ return resume_error(L, "cannot resume dead coroutine", nargs); ++ L->nCcalls = (from) ? getCcalls(from) : 0; ++ luai_userstateresume(L, nargs); ++ api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs); ++ status = luaD_rawrunprotected(L, resume, &nargs); ++ /* continue running after recoverable errors */ ++ status = precover(L, status); ++ if (l_likely(!errorstatus(status))) ++ lua_assert(status == L->status); /* normal end or yield */ ++ else { /* unrecoverable error */ ++ L->status = cast_byte(status); /* mark thread as 'dead' */ ++ luaD_seterrorobj(L, status, L->top); /* push error message */ ++ L->ci->top = L->top; ++ } ++ *nresults = (status == LUA_YIELD) ? L->ci->u2.nyield ++ : cast_int(L->top - (L->ci->func + 1)); ++ lua_unlock(L); ++ return status; ++} ++ ++ ++LUA_API int lua_isyieldable (lua_State *L) { ++ return yieldable(L); ++} ++ ++ ++LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx, ++ lua_KFunction k) { ++ CallInfo *ci; ++ luai_userstateyield(L, nresults); ++ lua_lock(L); ++ ci = L->ci; ++ api_checknelems(L, nresults); ++ if (l_unlikely(!yieldable(L))) { ++ if (L != G(L)->mainthread) ++ luaG_runerror(L, "attempt to yield across a C-call boundary"); ++ else ++ luaG_runerror(L, "attempt to yield from outside a coroutine"); ++ } ++ L->status = LUA_YIELD; ++ ci->u2.nyield = nresults; /* save number of results */ ++ if (isLua(ci)) { /* inside a hook? */ ++ lua_assert(!isLuacode(ci)); ++ api_check(L, nresults == 0, "hooks cannot yield values"); ++ api_check(L, k == NULL, "hooks cannot continue after yielding"); ++ } ++ else { ++ if ((ci->u.c.k = k) != NULL) /* is there a continuation? */ ++ ci->u.c.ctx = ctx; /* save context */ ++ luaD_throw(L, LUA_YIELD); ++ } ++ lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */ ++ lua_unlock(L); ++ return 0; /* return to 'luaD_hook' */ ++} ++ ++ ++/* ++** Auxiliary structure to call 'luaF_close' in protected mode. ++*/ ++struct CloseP { ++ StkId level; ++ int status; ++}; ++ ++ ++/* ++** Auxiliary function to call 'luaF_close' in protected mode. ++*/ ++static void closepaux (lua_State *L, void *ud) { ++ struct CloseP *pcl = cast(struct CloseP *, ud); ++ luaF_close(L, pcl->level, pcl->status, 0); ++} ++ ++ ++/* ++** Calls 'luaF_close' in protected mode. Return the original status ++** or, in case of errors, the new status. ++*/ ++int luaD_closeprotected (lua_State *L, ptrdiff_t level, int status) { ++ CallInfo *old_ci = L->ci; ++ lu_byte old_allowhooks = L->allowhook; ++ for (;;) { /* keep closing upvalues until no more errors */ ++ struct CloseP pcl; ++ pcl.level = restorestack(L, level); pcl.status = status; ++ status = luaD_rawrunprotected(L, &closepaux, &pcl); ++ if (l_likely(status == LUA_OK)) /* no more errors? */ ++ return pcl.status; ++ else { /* an error occurred; restore saved state and repeat */ ++ L->ci = old_ci; ++ L->allowhook = old_allowhooks; ++ } ++ } ++} ++ ++ ++/* ++** Call the C function 'func' in protected mode, restoring basic ++** thread information ('allowhook', etc.) and in particular ++** its stack level in case of errors. ++*/ ++int luaD_pcall (lua_State *L, Pfunc func, void *u, ++ ptrdiff_t old_top, ptrdiff_t ef) { ++ int status; ++ CallInfo *old_ci = L->ci; ++ lu_byte old_allowhooks = L->allowhook; ++ ptrdiff_t old_errfunc = L->errfunc; ++ L->errfunc = ef; ++ status = luaD_rawrunprotected(L, func, u); ++ if (l_unlikely(status != LUA_OK)) { /* an error occurred? */ ++ L->ci = old_ci; ++ L->allowhook = old_allowhooks; ++ status = luaD_closeprotected(L, old_top, status); ++ luaD_seterrorobj(L, status, restorestack(L, old_top)); ++ luaD_shrinkstack(L); /* restore stack size in case of overflow */ ++ } ++ L->errfunc = old_errfunc; ++ return status; ++} ++ ++ ++ ++/* ++** Execute a protected parser. ++*/ ++struct SParser { /* data to 'f_parser' */ ++ ZIO *z; ++ Mbuffer buff; /* dynamic structure used by the scanner */ ++ Dyndata dyd; /* dynamic structures used by the parser */ ++ const char *mode; ++ const char *name; ++}; ++ ++ ++static void checkmode (lua_State *L, const char *mode, const char *x) { ++ if (mode && strchr(mode, x[0]) == NULL) { ++ luaO_pushfstring(L, ++ "attempt to load a %s chunk (mode is '%s')", x, mode); ++ luaD_throw(L, LUA_ERRSYNTAX); ++ } ++} ++ ++ ++static void f_parser (lua_State *L, void *ud) { ++ LClosure *cl; ++ struct SParser *p = cast(struct SParser *, ud); ++ int c = zgetc(p->z); /* read first character */ ++ if (c == LUA_SIGNATURE[0]) { ++ checkmode(L, p->mode, "binary"); ++ cl = luaU_undump(L, p->z, p->name); ++ } ++ else { ++ checkmode(L, p->mode, "text"); ++ cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c); ++ } ++ lua_assert(cl->nupvalues == cl->p->sizeupvalues); ++ luaF_initupvals(L, cl); ++} ++ ++ ++int luaD_protectedparser (lua_State *L, ZIO *z, const char *name, ++ const char *mode) { ++ struct SParser p; ++ int status; ++ incnny(L); /* cannot yield during parsing */ ++ p.z = z; p.name = name; p.mode = mode; ++ p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0; ++ p.dyd.gt.arr = NULL; p.dyd.gt.size = 0; ++ p.dyd.label.arr = NULL; p.dyd.label.size = 0; ++ luaZ_initbuffer(L, &p.buff); ++ status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc); ++ luaZ_freebuffer(L, &p.buff); ++ luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size); ++ luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size); ++ luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size); ++ decnny(L); ++ return status; ++} ++ ++ +diff --git a/src/bin/lua/ldo.h b/src/bin/lua/ldo.h +new file mode 100644 +index 0000000000..6bf0ed86f7 +--- /dev/null ++++ b/src/bin/lua/ldo.h +@@ -0,0 +1,79 @@ ++/* ++** $Id: ldo.h $ ++** Stack and Call structure of Lua ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef ldo_h ++#define ldo_h ++ ++ ++#include "lobject.h" ++#include "lstate.h" ++#include "lzio.h" ++ ++ ++/* ++** Macro to check stack size and grow stack if needed. Parameters ++** 'pre'/'pos' allow the macro to preserve a pointer into the ++** stack across reallocations, doing the work only when needed. ++** It also allows the running of one GC step when the stack is ++** reallocated. ++** 'condmovestack' is used in heavy tests to force a stack reallocation ++** at every check. ++*/ ++#define luaD_checkstackaux(L,n,pre,pos) \ ++ if (l_unlikely(L->stack_last - L->top <= (n))) \ ++ { pre; luaD_growstack(L, n, 1); pos; } \ ++ else { condmovestack(L,pre,pos); } ++ ++/* In general, 'pre'/'pos' are empty (nothing to save) */ ++#define luaD_checkstack(L,n) luaD_checkstackaux(L,n,(void)0,(void)0) ++ ++ ++ ++#define savestack(L,p) ((char *)(p) - (char *)L->stack) ++#define restorestack(L,n) ((StkId)((char *)L->stack + (n))) ++ ++ ++/* macro to check stack size, preserving 'p' */ ++#define checkstackGCp(L,n,p) \ ++ luaD_checkstackaux(L, n, \ ++ ptrdiff_t t__ = savestack(L, p); /* save 'p' */ \ ++ luaC_checkGC(L), /* stack grow uses memory */ \ ++ p = restorestack(L, t__)) /* 'pos' part: restore 'p' */ ++ ++ ++/* macro to check stack size and GC */ ++#define checkstackGC(L,fsize) \ ++ luaD_checkstackaux(L, (fsize), luaC_checkGC(L), (void)0) ++ ++ ++/* type of protected functions, to be ran by 'runprotected' */ ++typedef void (*Pfunc) (lua_State *L, void *ud); ++ ++LUAI_FUNC void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop); ++LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name, ++ const char *mode); ++LUAI_FUNC void luaD_hook (lua_State *L, int event, int line, ++ int fTransfer, int nTransfer); ++LUAI_FUNC void luaD_hookcall (lua_State *L, CallInfo *ci); ++LUAI_FUNC void luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func, int n); ++LUAI_FUNC CallInfo *luaD_precall (lua_State *L, StkId func, int nResults); ++LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults); ++LUAI_FUNC void luaD_callnoyield (lua_State *L, StkId func, int nResults); ++LUAI_FUNC void luaD_tryfuncTM (lua_State *L, StkId func); ++LUAI_FUNC int luaD_closeprotected (lua_State *L, ptrdiff_t level, int status); ++LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u, ++ ptrdiff_t oldtop, ptrdiff_t ef); ++LUAI_FUNC void luaD_poscall (lua_State *L, CallInfo *ci, int nres); ++LUAI_FUNC int luaD_reallocstack (lua_State *L, int newsize, int raiseerror); ++LUAI_FUNC int luaD_growstack (lua_State *L, int n, int raiseerror); ++LUAI_FUNC void luaD_shrinkstack (lua_State *L); ++LUAI_FUNC void luaD_inctop (lua_State *L); ++ ++LUAI_FUNC l_noret luaD_throw (lua_State *L, int errcode); ++LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud); ++ ++#endif ++ +diff --git a/src/bin/lua/ldump.c b/src/bin/lua/ldump.c +new file mode 100644 +index 0000000000..f848b669cb +--- /dev/null ++++ b/src/bin/lua/ldump.c +@@ -0,0 +1,226 @@ ++/* ++** $Id: ldump.c $ ++** save precompiled Lua chunks ++** See Copyright Notice in lua.h ++*/ ++ ++#define ldump_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++#include ++ ++#include "lua.h" ++ ++#include "lobject.h" ++#include "lstate.h" ++#include "lundump.h" ++ ++ ++typedef struct { ++ lua_State *L; ++ lua_Writer writer; ++ void *data; ++ int strip; ++ int status; ++} DumpState; ++ ++ ++/* ++** All high-level dumps go through dumpVector; you can change it to ++** change the endianness of the result ++*/ ++#define dumpVector(D,v,n) dumpBlock(D,v,(n)*sizeof((v)[0])) ++ ++#define dumpLiteral(D, s) dumpBlock(D,s,sizeof(s) - sizeof(char)) ++ ++ ++static void dumpBlock (DumpState *D, const void *b, size_t size) { ++ if (D->status == 0 && size > 0) { ++ lua_unlock(D->L); ++ D->status = (*D->writer)(D->L, b, size, D->data); ++ lua_lock(D->L); ++ } ++} ++ ++ ++#define dumpVar(D,x) dumpVector(D,&x,1) ++ ++ ++static void dumpByte (DumpState *D, int y) { ++ lu_byte x = (lu_byte)y; ++ dumpVar(D, x); ++} ++ ++ ++/* dumpInt Buff Size */ ++#define DIBS ((sizeof(size_t) * 8 / 7) + 1) ++ ++static void dumpSize (DumpState *D, size_t x) { ++ lu_byte buff[DIBS]; ++ int n = 0; ++ do { ++ buff[DIBS - (++n)] = x & 0x7f; /* fill buffer in reverse order */ ++ x >>= 7; ++ } while (x != 0); ++ buff[DIBS - 1] |= 0x80; /* mark last byte */ ++ dumpVector(D, buff + DIBS - n, n); ++} ++ ++ ++static void dumpInt (DumpState *D, int x) { ++ dumpSize(D, x); ++} ++ ++ ++static void dumpNumber (DumpState *D, lua_Number x) { ++ dumpVar(D, x); ++} ++ ++ ++static void dumpInteger (DumpState *D, lua_Integer x) { ++ dumpVar(D, x); ++} ++ ++ ++static void dumpString (DumpState *D, const TString *s) { ++ if (s == NULL) ++ dumpSize(D, 0); ++ else { ++ size_t size = tsslen(s); ++ const char *str = getstr(s); ++ dumpSize(D, size + 1); ++ dumpVector(D, str, size); ++ } ++} ++ ++ ++static void dumpCode (DumpState *D, const Proto *f) { ++ dumpInt(D, f->sizecode); ++ dumpVector(D, f->code, f->sizecode); ++} ++ ++ ++static void dumpFunction(DumpState *D, const Proto *f, TString *psource); ++ ++static void dumpConstants (DumpState *D, const Proto *f) { ++ int i; ++ int n = f->sizek; ++ dumpInt(D, n); ++ for (i = 0; i < n; i++) { ++ const TValue *o = &f->k[i]; ++ int tt = ttypetag(o); ++ dumpByte(D, tt); ++ switch (tt) { ++ case LUA_VNUMFLT: ++ dumpNumber(D, fltvalue(o)); ++ break; ++ case LUA_VNUMINT: ++ dumpInteger(D, ivalue(o)); ++ break; ++ case LUA_VSHRSTR: ++ case LUA_VLNGSTR: ++ dumpString(D, tsvalue(o)); ++ break; ++ default: ++ lua_assert(tt == LUA_VNIL || tt == LUA_VFALSE || tt == LUA_VTRUE); ++ } ++ } ++} ++ ++ ++static void dumpProtos (DumpState *D, const Proto *f) { ++ int i; ++ int n = f->sizep; ++ dumpInt(D, n); ++ for (i = 0; i < n; i++) ++ dumpFunction(D, f->p[i], f->source); ++} ++ ++ ++static void dumpUpvalues (DumpState *D, const Proto *f) { ++ int i, n = f->sizeupvalues; ++ dumpInt(D, n); ++ for (i = 0; i < n; i++) { ++ dumpByte(D, f->upvalues[i].instack); ++ dumpByte(D, f->upvalues[i].idx); ++ dumpByte(D, f->upvalues[i].kind); ++ } ++} ++ ++ ++static void dumpDebug (DumpState *D, const Proto *f) { ++ int i, n; ++ n = (D->strip) ? 0 : f->sizelineinfo; ++ dumpInt(D, n); ++ dumpVector(D, f->lineinfo, n); ++ n = (D->strip) ? 0 : f->sizeabslineinfo; ++ dumpInt(D, n); ++ for (i = 0; i < n; i++) { ++ dumpInt(D, f->abslineinfo[i].pc); ++ dumpInt(D, f->abslineinfo[i].line); ++ } ++ n = (D->strip) ? 0 : f->sizelocvars; ++ dumpInt(D, n); ++ for (i = 0; i < n; i++) { ++ dumpString(D, f->locvars[i].varname); ++ dumpInt(D, f->locvars[i].startpc); ++ dumpInt(D, f->locvars[i].endpc); ++ } ++ n = (D->strip) ? 0 : f->sizeupvalues; ++ dumpInt(D, n); ++ for (i = 0; i < n; i++) ++ dumpString(D, f->upvalues[i].name); ++} ++ ++ ++static void dumpFunction (DumpState *D, const Proto *f, TString *psource) { ++ if (D->strip || f->source == psource) ++ dumpString(D, NULL); /* no debug info or same source as its parent */ ++ else ++ dumpString(D, f->source); ++ dumpInt(D, f->linedefined); ++ dumpInt(D, f->lastlinedefined); ++ dumpByte(D, f->numparams); ++ dumpByte(D, f->is_vararg); ++ dumpByte(D, f->maxstacksize); ++ dumpCode(D, f); ++ dumpConstants(D, f); ++ dumpUpvalues(D, f); ++ dumpProtos(D, f); ++ dumpDebug(D, f); ++} ++ ++ ++static void dumpHeader (DumpState *D) { ++ dumpLiteral(D, LUA_SIGNATURE); ++ dumpByte(D, LUAC_VERSION); ++ dumpByte(D, LUAC_FORMAT); ++ dumpLiteral(D, LUAC_DATA); ++ dumpByte(D, sizeof(Instruction)); ++ dumpByte(D, sizeof(lua_Integer)); ++ dumpByte(D, sizeof(lua_Number)); ++ dumpInteger(D, LUAC_INT); ++ dumpNumber(D, LUAC_NUM); ++} ++ ++ ++/* ++** dump Lua function as precompiled chunk ++*/ ++int luaU_dump(lua_State *L, const Proto *f, lua_Writer w, void *data, ++ int strip) { ++ DumpState D; ++ D.L = L; ++ D.writer = w; ++ D.data = data; ++ D.strip = strip; ++ D.status = 0; ++ dumpHeader(&D); ++ dumpByte(&D, f->sizeupvalues); ++ dumpFunction(&D, f, NULL); ++ return D.status; ++} ++ +diff --git a/src/bin/lua/lfunc.c b/src/bin/lua/lfunc.c +new file mode 100644 +index 0000000000..f5889a21d1 +--- /dev/null ++++ b/src/bin/lua/lfunc.c +@@ -0,0 +1,294 @@ ++/* ++** $Id: lfunc.c $ ++** Auxiliary functions to manipulate prototypes and closures ++** See Copyright Notice in lua.h ++*/ ++ ++#define lfunc_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++#include ++ ++#include "lua.h" ++ ++#include "ldebug.h" ++#include "ldo.h" ++#include "lfunc.h" ++#include "lgc.h" ++#include "lmem.h" ++#include "lobject.h" ++#include "lstate.h" ++ ++ ++ ++CClosure *luaF_newCclosure (lua_State *L, int nupvals) { ++ GCObject *o = luaC_newobj(L, LUA_VCCL, sizeCclosure(nupvals)); ++ CClosure *c = gco2ccl(o); ++ c->nupvalues = cast_byte(nupvals); ++ return c; ++} ++ ++ ++LClosure *luaF_newLclosure (lua_State *L, int nupvals) { ++ GCObject *o = luaC_newobj(L, LUA_VLCL, sizeLclosure(nupvals)); ++ LClosure *c = gco2lcl(o); ++ c->p = NULL; ++ c->nupvalues = cast_byte(nupvals); ++ while (nupvals--) c->upvals[nupvals] = NULL; ++ return c; ++} ++ ++ ++/* ++** fill a closure with new closed upvalues ++*/ ++void luaF_initupvals (lua_State *L, LClosure *cl) { ++ int i; ++ for (i = 0; i < cl->nupvalues; i++) { ++ GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal)); ++ UpVal *uv = gco2upv(o); ++ uv->v = &uv->u.value; /* make it closed */ ++ setnilvalue(uv->v); ++ cl->upvals[i] = uv; ++ luaC_objbarrier(L, cl, uv); ++ } ++} ++ ++ ++/* ++** Create a new upvalue at the given level, and link it to the list of ++** open upvalues of 'L' after entry 'prev'. ++**/ ++static UpVal *newupval (lua_State *L, int tbc, StkId level, UpVal **prev) { ++ GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal)); ++ UpVal *uv = gco2upv(o); ++ UpVal *next = *prev; ++ uv->v = s2v(level); /* current value lives in the stack */ ++ uv->tbc = tbc; ++ uv->u.open.next = next; /* link it to list of open upvalues */ ++ uv->u.open.previous = prev; ++ if (next) ++ next->u.open.previous = &uv->u.open.next; ++ *prev = uv; ++ if (!isintwups(L)) { /* thread not in list of threads with upvalues? */ ++ L->twups = G(L)->twups; /* link it to the list */ ++ G(L)->twups = L; ++ } ++ return uv; ++} ++ ++ ++/* ++** Find and reuse, or create if it does not exist, an upvalue ++** at the given level. ++*/ ++UpVal *luaF_findupval (lua_State *L, StkId level) { ++ UpVal **pp = &L->openupval; ++ UpVal *p; ++ lua_assert(isintwups(L) || L->openupval == NULL); ++ while ((p = *pp) != NULL && uplevel(p) >= level) { /* search for it */ ++ lua_assert(!isdead(G(L), p)); ++ if (uplevel(p) == level) /* corresponding upvalue? */ ++ return p; /* return it */ ++ pp = &p->u.open.next; ++ } ++ /* not found: create a new upvalue after 'pp' */ ++ return newupval(L, 0, level, pp); ++} ++ ++ ++/* ++** Call closing method for object 'obj' with error message 'err'. The ++** boolean 'yy' controls whether the call is yieldable. ++** (This function assumes EXTRA_STACK.) ++*/ ++static void callclosemethod (lua_State *L, TValue *obj, TValue *err, int yy) { ++ StkId top = L->top; ++ const TValue *tm = luaT_gettmbyobj(L, obj, TM_CLOSE); ++ setobj2s(L, top, tm); /* will call metamethod... */ ++ setobj2s(L, top + 1, obj); /* with 'self' as the 1st argument */ ++ setobj2s(L, top + 2, err); /* and error msg. as 2nd argument */ ++ L->top = top + 3; /* add function and arguments */ ++ if (yy) ++ luaD_call(L, top, 0); ++ else ++ luaD_callnoyield(L, top, 0); ++} ++ ++ ++/* ++** Check whether object at given level has a close metamethod and raise ++** an error if not. ++*/ ++static void checkclosemth (lua_State *L, StkId level) { ++ const TValue *tm = luaT_gettmbyobj(L, s2v(level), TM_CLOSE); ++ if (ttisnil(tm)) { /* no metamethod? */ ++ int idx = cast_int(level - L->ci->func); /* variable index */ ++ const char *vname = luaG_findlocal(L, L->ci, idx, NULL); ++ if (vname == NULL) vname = "?"; ++ luaG_runerror(L, "variable '%s' got a non-closable value", vname); ++ } ++} ++ ++ ++/* ++** Prepare and call a closing method. ++** If status is CLOSEKTOP, the call to the closing method will be pushed ++** at the top of the stack. Otherwise, values can be pushed right after ++** the 'level' of the upvalue being closed, as everything after that ++** won't be used again. ++*/ ++static void prepcallclosemth (lua_State *L, StkId level, int status, int yy) { ++ TValue *uv = s2v(level); /* value being closed */ ++ TValue *errobj; ++ if (status == CLOSEKTOP) ++ errobj = &G(L)->nilvalue; /* error object is nil */ ++ else { /* 'luaD_seterrorobj' will set top to level + 2 */ ++ errobj = s2v(level + 1); /* error object goes after 'uv' */ ++ luaD_seterrorobj(L, status, level + 1); /* set error object */ ++ } ++ callclosemethod(L, uv, errobj, yy); ++} ++ ++ ++/* ++** Maximum value for deltas in 'tbclist', dependent on the type ++** of delta. (This macro assumes that an 'L' is in scope where it ++** is used.) ++*/ ++#define MAXDELTA \ ++ ((256ul << ((sizeof(L->stack->tbclist.delta) - 1) * 8)) - 1) ++ ++ ++/* ++** Insert a variable in the list of to-be-closed variables. ++*/ ++void luaF_newtbcupval (lua_State *L, StkId level) { ++ lua_assert(level > L->tbclist); ++ if (l_isfalse(s2v(level))) ++ return; /* false doesn't need to be closed */ ++ checkclosemth(L, level); /* value must have a close method */ ++ while (cast_uint(level - L->tbclist) > MAXDELTA) { ++ L->tbclist += MAXDELTA; /* create a dummy node at maximum delta */ ++ L->tbclist->tbclist.delta = 0; ++ } ++ level->tbclist.delta = cast(unsigned short, level - L->tbclist); ++ L->tbclist = level; ++} ++ ++ ++void luaF_unlinkupval (UpVal *uv) { ++ lua_assert(upisopen(uv)); ++ *uv->u.open.previous = uv->u.open.next; ++ if (uv->u.open.next) ++ uv->u.open.next->u.open.previous = uv->u.open.previous; ++} ++ ++ ++/* ++** Close all upvalues up to the given stack level. ++*/ ++void luaF_closeupval (lua_State *L, StkId level) { ++ UpVal *uv; ++ StkId upl; /* stack index pointed by 'uv' */ ++ while ((uv = L->openupval) != NULL && (upl = uplevel(uv)) >= level) { ++ TValue *slot = &uv->u.value; /* new position for value */ ++ lua_assert(uplevel(uv) < L->top); ++ luaF_unlinkupval(uv); /* remove upvalue from 'openupval' list */ ++ setobj(L, slot, uv->v); /* move value to upvalue slot */ ++ uv->v = slot; /* now current value lives here */ ++ if (!iswhite(uv)) { /* neither white nor dead? */ ++ nw2black(uv); /* closed upvalues cannot be gray */ ++ luaC_barrier(L, uv, slot); ++ } ++ } ++} ++ ++ ++/* ++** Remove firt element from the tbclist plus its dummy nodes. ++*/ ++static void poptbclist (lua_State *L) { ++ StkId tbc = L->tbclist; ++ lua_assert(tbc->tbclist.delta > 0); /* first element cannot be dummy */ ++ tbc -= tbc->tbclist.delta; ++ while (tbc > L->stack && tbc->tbclist.delta == 0) ++ tbc -= MAXDELTA; /* remove dummy nodes */ ++ L->tbclist = tbc; ++} ++ ++ ++/* ++** Close all upvalues and to-be-closed variables up to the given stack ++** level. ++*/ ++void luaF_close (lua_State *L, StkId level, int status, int yy) { ++ ptrdiff_t levelrel = savestack(L, level); ++ luaF_closeupval(L, level); /* first, close the upvalues */ ++ while (L->tbclist >= level) { /* traverse tbc's down to that level */ ++ StkId tbc = L->tbclist; /* get variable index */ ++ poptbclist(L); /* remove it from list */ ++ prepcallclosemth(L, tbc, status, yy); /* close variable */ ++ level = restorestack(L, levelrel); ++ } ++} ++ ++ ++Proto *luaF_newproto (lua_State *L) { ++ GCObject *o = luaC_newobj(L, LUA_VPROTO, sizeof(Proto)); ++ Proto *f = gco2p(o); ++ f->k = NULL; ++ f->sizek = 0; ++ f->p = NULL; ++ f->sizep = 0; ++ f->code = NULL; ++ f->sizecode = 0; ++ f->lineinfo = NULL; ++ f->sizelineinfo = 0; ++ f->abslineinfo = NULL; ++ f->sizeabslineinfo = 0; ++ f->upvalues = NULL; ++ f->sizeupvalues = 0; ++ f->numparams = 0; ++ f->is_vararg = 0; ++ f->maxstacksize = 0; ++ f->locvars = NULL; ++ f->sizelocvars = 0; ++ f->linedefined = 0; ++ f->lastlinedefined = 0; ++ f->source = NULL; ++ return f; ++} ++ ++ ++void luaF_freeproto (lua_State *L, Proto *f) { ++ luaM_freearray(L, f->code, f->sizecode); ++ luaM_freearray(L, f->p, f->sizep); ++ luaM_freearray(L, f->k, f->sizek); ++ luaM_freearray(L, f->lineinfo, f->sizelineinfo); ++ luaM_freearray(L, f->abslineinfo, f->sizeabslineinfo); ++ luaM_freearray(L, f->locvars, f->sizelocvars); ++ luaM_freearray(L, f->upvalues, f->sizeupvalues); ++ luaM_free(L, f); ++} ++ ++ ++/* ++** Look for n-th local variable at line 'line' in function 'func'. ++** Returns NULL if not found. ++*/ ++const char *luaF_getlocalname (const Proto *f, int local_number, int pc) { ++ int i; ++ for (i = 0; isizelocvars && f->locvars[i].startpc <= pc; i++) { ++ if (pc < f->locvars[i].endpc) { /* is variable active? */ ++ local_number--; ++ if (local_number == 0) ++ return getstr(f->locvars[i].varname); ++ } ++ } ++ return NULL; /* not found */ ++} ++ +diff --git a/src/bin/lua/lfunc.h b/src/bin/lua/lfunc.h +new file mode 100644 +index 0000000000..dc1cebccd1 +--- /dev/null ++++ b/src/bin/lua/lfunc.h +@@ -0,0 +1,64 @@ ++/* ++** $Id: lfunc.h $ ++** Auxiliary functions to manipulate prototypes and closures ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef lfunc_h ++#define lfunc_h ++ ++ ++#include "lobject.h" ++ ++ ++#define sizeCclosure(n) (cast_int(offsetof(CClosure, upvalue)) + \ ++ cast_int(sizeof(TValue)) * (n)) ++ ++#define sizeLclosure(n) (cast_int(offsetof(LClosure, upvals)) + \ ++ cast_int(sizeof(TValue *)) * (n)) ++ ++ ++/* test whether thread is in 'twups' list */ ++#define isintwups(L) (L->twups != L) ++ ++ ++/* ++** maximum number of upvalues in a closure (both C and Lua). (Value ++** must fit in a VM register.) ++*/ ++#define MAXUPVAL 255 ++ ++ ++#define upisopen(up) ((up)->v != &(up)->u.value) ++ ++ ++#define uplevel(up) check_exp(upisopen(up), cast(StkId, (up)->v)) ++ ++ ++/* ++** maximum number of misses before giving up the cache of closures ++** in prototypes ++*/ ++#define MAXMISS 10 ++ ++ ++ ++/* special status to close upvalues preserving the top of the stack */ ++#define CLOSEKTOP (-1) ++ ++ ++LUAI_FUNC Proto *luaF_newproto (lua_State *L); ++LUAI_FUNC CClosure *luaF_newCclosure (lua_State *L, int nupvals); ++LUAI_FUNC LClosure *luaF_newLclosure (lua_State *L, int nupvals); ++LUAI_FUNC void luaF_initupvals (lua_State *L, LClosure *cl); ++LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level); ++LUAI_FUNC void luaF_newtbcupval (lua_State *L, StkId level); ++LUAI_FUNC void luaF_closeupval (lua_State *L, StkId level); ++LUAI_FUNC void luaF_close (lua_State *L, StkId level, int status, int yy); ++LUAI_FUNC void luaF_unlinkupval (UpVal *uv); ++LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f); ++LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number, ++ int pc); ++ ++ ++#endif +diff --git a/src/bin/lua/lgc.c b/src/bin/lua/lgc.c +new file mode 100644 +index 0000000000..b360eed008 +--- /dev/null ++++ b/src/bin/lua/lgc.c +@@ -0,0 +1,1728 @@ ++/* ++** $Id: lgc.c $ ++** Garbage Collector ++** See Copyright Notice in lua.h ++*/ ++ ++#define lgc_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++#include ++#include ++ ++ ++#include "lua.h" ++ ++#include "ldebug.h" ++#include "ldo.h" ++#include "lfunc.h" ++#include "lgc.h" ++#include "lmem.h" ++#include "lobject.h" ++#include "lstate.h" ++#include "lstring.h" ++#include "ltable.h" ++#include "ltm.h" ++ ++ ++/* ++** Maximum number of elements to sweep in each single step. ++** (Large enough to dissipate fixed overheads but small enough ++** to allow small steps for the collector.) ++*/ ++#define GCSWEEPMAX 100 ++ ++/* ++** Maximum number of finalizers to call in each single step. ++*/ ++#define GCFINMAX 10 ++ ++ ++/* ++** Cost of calling one finalizer. ++*/ ++#define GCFINALIZECOST 50 ++ ++ ++/* ++** The equivalent, in bytes, of one unit of "work" (visiting a slot, ++** sweeping an object, etc.) ++*/ ++#define WORK2MEM sizeof(TValue) ++ ++ ++/* ++** macro to adjust 'pause': 'pause' is actually used like ++** 'pause / PAUSEADJ' (value chosen by tests) ++*/ ++#define PAUSEADJ 100 ++ ++ ++/* mask with all color bits */ ++#define maskcolors (bitmask(BLACKBIT) | WHITEBITS) ++ ++/* mask with all GC bits */ ++#define maskgcbits (maskcolors | AGEBITS) ++ ++ ++/* macro to erase all color bits then set only the current white bit */ ++#define makewhite(g,x) \ ++ (x->marked = cast_byte((x->marked & ~maskcolors) | luaC_white(g))) ++ ++/* make an object gray (neither white nor black) */ ++#define set2gray(x) resetbits(x->marked, maskcolors) ++ ++ ++/* make an object black (coming from any color) */ ++#define set2black(x) \ ++ (x->marked = cast_byte((x->marked & ~WHITEBITS) | bitmask(BLACKBIT))) ++ ++ ++#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x))) ++ ++#define keyiswhite(n) (keyiscollectable(n) && iswhite(gckey(n))) ++ ++ ++/* ++** Protected access to objects in values ++*/ ++#define gcvalueN(o) (iscollectable(o) ? gcvalue(o) : NULL) ++ ++ ++#define markvalue(g,o) { checkliveness(g->mainthread,o); \ ++ if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); } ++ ++#define markkey(g, n) { if keyiswhite(n) reallymarkobject(g,gckey(n)); } ++ ++#define markobject(g,t) { if (iswhite(t)) reallymarkobject(g, obj2gco(t)); } ++ ++/* ++** mark an object that can be NULL (either because it is really optional, ++** or it was stripped as debug info, or inside an uncompleted structure) ++*/ ++#define markobjectN(g,t) { if (t) markobject(g,t); } ++ ++static void reallymarkobject (global_State *g, GCObject *o); ++static lu_mem atomic (lua_State *L); ++static void entersweep (lua_State *L); ++ ++ ++/* ++** {====================================================== ++** Generic functions ++** ======================================================= ++*/ ++ ++ ++/* ++** one after last element in a hash array ++*/ ++#define gnodelast(h) gnode(h, cast_sizet(sizenode(h))) ++ ++ ++static GCObject **getgclist (GCObject *o) { ++ switch (o->tt) { ++ case LUA_VTABLE: return &gco2t(o)->gclist; ++ case LUA_VLCL: return &gco2lcl(o)->gclist; ++ case LUA_VCCL: return &gco2ccl(o)->gclist; ++ case LUA_VTHREAD: return &gco2th(o)->gclist; ++ case LUA_VPROTO: return &gco2p(o)->gclist; ++ case LUA_VUSERDATA: { ++ Udata *u = gco2u(o); ++ lua_assert(u->nuvalue > 0); ++ return &u->gclist; ++ } ++ default: lua_assert(0); return 0; ++ } ++} ++ ++ ++/* ++** Link a collectable object 'o' with a known type into the list 'p'. ++** (Must be a macro to access the 'gclist' field in different types.) ++*/ ++#define linkgclist(o,p) linkgclist_(obj2gco(o), &(o)->gclist, &(p)) ++ ++static void linkgclist_ (GCObject *o, GCObject **pnext, GCObject **list) { ++ lua_assert(!isgray(o)); /* cannot be in a gray list */ ++ *pnext = *list; ++ *list = o; ++ set2gray(o); /* now it is */ ++} ++ ++ ++/* ++** Link a generic collectable object 'o' into the list 'p'. ++*/ ++#define linkobjgclist(o,p) linkgclist_(obj2gco(o), getgclist(o), &(p)) ++ ++ ++ ++/* ++** Clear keys for empty entries in tables. If entry is empty, mark its ++** entry as dead. This allows the collection of the key, but keeps its ++** entry in the table: its removal could break a chain and could break ++** a table traversal. Other places never manipulate dead keys, because ++** its associated empty value is enough to signal that the entry is ++** logically empty. ++*/ ++static void clearkey (Node *n) { ++ lua_assert(isempty(gval(n))); ++ if (keyiscollectable(n)) ++ setdeadkey(n); /* unused key; remove it */ ++} ++ ++ ++/* ++** tells whether a key or value can be cleared from a weak ++** table. Non-collectable objects are never removed from weak ++** tables. Strings behave as 'values', so are never removed too. for ++** other objects: if really collected, cannot keep them; for objects ++** being finalized, keep them in keys, but not in values ++*/ ++static int iscleared (global_State *g, const GCObject *o) { ++ if (o == NULL) return 0; /* non-collectable value */ ++ else if (novariant(o->tt) == LUA_TSTRING) { ++ markobject(g, o); /* strings are 'values', so are never weak */ ++ return 0; ++ } ++ else return iswhite(o); ++} ++ ++ ++/* ++** Barrier that moves collector forward, that is, marks the white object ++** 'v' being pointed by the black object 'o'. In the generational ++** mode, 'v' must also become old, if 'o' is old; however, it cannot ++** be changed directly to OLD, because it may still point to non-old ++** objects. So, it is marked as OLD0. In the next cycle it will become ++** OLD1, and in the next it will finally become OLD (regular old). By ++** then, any object it points to will also be old. If called in the ++** incremental sweep phase, it clears the black object to white (sweep ++** it) to avoid other barrier calls for this same object. (That cannot ++** be done is generational mode, as its sweep does not distinguish ++** whites from deads.) ++*/ ++void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) { ++ global_State *g = G(L); ++ lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o)); ++ if (keepinvariant(g)) { /* must keep invariant? */ ++ reallymarkobject(g, v); /* restore invariant */ ++ if (isold(o)) { ++ lua_assert(!isold(v)); /* white object could not be old */ ++ setage(v, G_OLD0); /* restore generational invariant */ ++ } ++ } ++ else { /* sweep phase */ ++ lua_assert(issweepphase(g)); ++ if (g->gckind == KGC_INC) /* incremental mode? */ ++ makewhite(g, o); /* mark 'o' as white to avoid other barriers */ ++ } ++} ++ ++ ++/* ++** barrier that moves collector backward, that is, mark the black object ++** pointing to a white object as gray again. ++*/ ++void luaC_barrierback_ (lua_State *L, GCObject *o) { ++ global_State *g = G(L); ++ lua_assert(isblack(o) && !isdead(g, o)); ++ lua_assert((g->gckind == KGC_GEN) == (isold(o) && getage(o) != G_TOUCHED1)); ++ if (getage(o) == G_TOUCHED2) /* already in gray list? */ ++ set2gray(o); /* make it gray to become touched1 */ ++ else /* link it in 'grayagain' and paint it gray */ ++ linkobjgclist(o, g->grayagain); ++ if (isold(o)) /* generational mode? */ ++ setage(o, G_TOUCHED1); /* touched in current cycle */ ++} ++ ++ ++void luaC_fix (lua_State *L, GCObject *o) { ++ global_State *g = G(L); ++ lua_assert(g->allgc == o); /* object must be 1st in 'allgc' list! */ ++ set2gray(o); /* they will be gray forever */ ++ setage(o, G_OLD); /* and old forever */ ++ g->allgc = o->next; /* remove object from 'allgc' list */ ++ o->next = g->fixedgc; /* link it to 'fixedgc' list */ ++ g->fixedgc = o; ++} ++ ++ ++/* ++** create a new collectable object (with given type and size) and link ++** it to 'allgc' list. ++*/ ++GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) { ++ global_State *g = G(L); ++ GCObject *o = cast(GCObject *, luaM_newobject(L, novariant(tt), sz)); ++ o->marked = luaC_white(g); ++ o->tt = tt; ++ o->next = g->allgc; ++ g->allgc = o; ++ return o; ++} ++ ++/* }====================================================== */ ++ ++ ++ ++/* ++** {====================================================== ++** Mark functions ++** ======================================================= ++*/ ++ ++ ++/* ++** Mark an object. Userdata with no user values, strings, and closed ++** upvalues are visited and turned black here. Open upvalues are ++** already indirectly linked through their respective threads in the ++** 'twups' list, so they don't go to the gray list; nevertheless, they ++** are kept gray to avoid barriers, as their values will be revisited ++** by the thread or by 'remarkupvals'. Other objects are added to the ++** gray list to be visited (and turned black) later. Both userdata and ++** upvalues can call this function recursively, but this recursion goes ++** for at most two levels: An upvalue cannot refer to another upvalue ++** (only closures can), and a userdata's metatable must be a table. ++*/ ++static void reallymarkobject (global_State *g, GCObject *o) { ++ switch (o->tt) { ++ case LUA_VSHRSTR: ++ case LUA_VLNGSTR: { ++ set2black(o); /* nothing to visit */ ++ break; ++ } ++ case LUA_VUPVAL: { ++ UpVal *uv = gco2upv(o); ++ if (upisopen(uv)) ++ set2gray(uv); /* open upvalues are kept gray */ ++ else ++ set2black(uv); /* closed upvalues are visited here */ ++ markvalue(g, uv->v); /* mark its content */ ++ break; ++ } ++ case LUA_VUSERDATA: { ++ Udata *u = gco2u(o); ++ if (u->nuvalue == 0) { /* no user values? */ ++ markobjectN(g, u->metatable); /* mark its metatable */ ++ set2black(u); /* nothing else to mark */ ++ break; ++ } ++ /* else... */ ++ } /* FALLTHROUGH */ ++ case LUA_VLCL: case LUA_VCCL: case LUA_VTABLE: ++ case LUA_VTHREAD: case LUA_VPROTO: { ++ linkobjgclist(o, g->gray); /* to be visited later */ ++ break; ++ } ++ default: lua_assert(0); break; ++ } ++} ++ ++ ++/* ++** mark metamethods for basic types ++*/ ++static void markmt (global_State *g) { ++ int i; ++ for (i=0; i < LUA_NUMTAGS; i++) ++ markobjectN(g, g->mt[i]); ++} ++ ++ ++/* ++** mark all objects in list of being-finalized ++*/ ++static lu_mem markbeingfnz (global_State *g) { ++ GCObject *o; ++ lu_mem count = 0; ++ for (o = g->tobefnz; o != NULL; o = o->next) { ++ count++; ++ markobject(g, o); ++ } ++ return count; ++} ++ ++ ++/* ++** For each non-marked thread, simulates a barrier between each open ++** upvalue and its value. (If the thread is collected, the value will be ++** assigned to the upvalue, but then it can be too late for the barrier ++** to act. The "barrier" does not need to check colors: A non-marked ++** thread must be young; upvalues cannot be older than their threads; so ++** any visited upvalue must be young too.) Also removes the thread from ++** the list, as it was already visited. Removes also threads with no ++** upvalues, as they have nothing to be checked. (If the thread gets an ++** upvalue later, it will be linked in the list again.) ++*/ ++static int remarkupvals (global_State *g) { ++ lua_State *thread; ++ lua_State **p = &g->twups; ++ int work = 0; /* estimate of how much work was done here */ ++ while ((thread = *p) != NULL) { ++ work++; ++ if (!iswhite(thread) && thread->openupval != NULL) ++ p = &thread->twups; /* keep marked thread with upvalues in the list */ ++ else { /* thread is not marked or without upvalues */ ++ UpVal *uv; ++ lua_assert(!isold(thread) || thread->openupval == NULL); ++ *p = thread->twups; /* remove thread from the list */ ++ thread->twups = thread; /* mark that it is out of list */ ++ for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) { ++ lua_assert(getage(uv) <= getage(thread)); ++ work++; ++ if (!iswhite(uv)) { /* upvalue already visited? */ ++ lua_assert(upisopen(uv) && isgray(uv)); ++ markvalue(g, uv->v); /* mark its value */ ++ } ++ } ++ } ++ } ++ return work; ++} ++ ++ ++static void cleargraylists (global_State *g) { ++ g->gray = g->grayagain = NULL; ++ g->weak = g->allweak = g->ephemeron = NULL; ++} ++ ++ ++/* ++** mark root set and reset all gray lists, to start a new collection ++*/ ++static void restartcollection (global_State *g) { ++ cleargraylists(g); ++ markobject(g, g->mainthread); ++ markvalue(g, &g->l_registry); ++ markmt(g); ++ markbeingfnz(g); /* mark any finalizing object left from previous cycle */ ++} ++ ++/* }====================================================== */ ++ ++ ++/* ++** {====================================================== ++** Traverse functions ++** ======================================================= ++*/ ++ ++ ++/* ++** Check whether object 'o' should be kept in the 'grayagain' list for ++** post-processing by 'correctgraylist'. (It could put all old objects ++** in the list and leave all the work to 'correctgraylist', but it is ++** more efficient to avoid adding elements that will be removed.) Only ++** TOUCHED1 objects need to be in the list. TOUCHED2 doesn't need to go ++** back to a gray list, but then it must become OLD. (That is what ++** 'correctgraylist' does when it finds a TOUCHED2 object.) ++*/ ++static void genlink (global_State *g, GCObject *o) { ++ lua_assert(isblack(o)); ++ if (getage(o) == G_TOUCHED1) { /* touched in this cycle? */ ++ linkobjgclist(o, g->grayagain); /* link it back in 'grayagain' */ ++ } /* everything else do not need to be linked back */ ++ else if (getage(o) == G_TOUCHED2) ++ changeage(o, G_TOUCHED2, G_OLD); /* advance age */ ++} ++ ++ ++/* ++** Traverse a table with weak values and link it to proper list. During ++** propagate phase, keep it in 'grayagain' list, to be revisited in the ++** atomic phase. In the atomic phase, if table has any white value, ++** put it in 'weak' list, to be cleared. ++*/ ++static void traverseweakvalue (global_State *g, Table *h) { ++ Node *n, *limit = gnodelast(h); ++ /* if there is array part, assume it may have white values (it is not ++ worth traversing it now just to check) */ ++ int hasclears = (h->alimit > 0); ++ for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */ ++ if (isempty(gval(n))) /* entry is empty? */ ++ clearkey(n); /* clear its key */ ++ else { ++ lua_assert(!keyisnil(n)); ++ markkey(g, n); ++ if (!hasclears && iscleared(g, gcvalueN(gval(n)))) /* a white value? */ ++ hasclears = 1; /* table will have to be cleared */ ++ } ++ } ++ if (g->gcstate == GCSatomic && hasclears) ++ linkgclist(h, g->weak); /* has to be cleared later */ ++ else ++ linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */ ++} ++ ++ ++/* ++** Traverse an ephemeron table and link it to proper list. Returns true ++** iff any object was marked during this traversal (which implies that ++** convergence has to continue). During propagation phase, keep table ++** in 'grayagain' list, to be visited again in the atomic phase. In ++** the atomic phase, if table has any white->white entry, it has to ++** be revisited during ephemeron convergence (as that key may turn ++** black). Otherwise, if it has any white key, table has to be cleared ++** (in the atomic phase). In generational mode, some tables ++** must be kept in some gray list for post-processing; this is done ++** by 'genlink'. ++*/ ++static int traverseephemeron (global_State *g, Table *h, int inv) { ++ int marked = 0; /* true if an object is marked in this traversal */ ++ int hasclears = 0; /* true if table has white keys */ ++ int hasww = 0; /* true if table has entry "white-key -> white-value" */ ++ unsigned int i; ++ unsigned int asize = luaH_realasize(h); ++ unsigned int nsize = sizenode(h); ++ /* traverse array part */ ++ for (i = 0; i < asize; i++) { ++ if (valiswhite(&h->array[i])) { ++ marked = 1; ++ reallymarkobject(g, gcvalue(&h->array[i])); ++ } ++ } ++ /* traverse hash part; if 'inv', traverse descending ++ (see 'convergeephemerons') */ ++ for (i = 0; i < nsize; i++) { ++ Node *n = inv ? gnode(h, nsize - 1 - i) : gnode(h, i); ++ if (isempty(gval(n))) /* entry is empty? */ ++ clearkey(n); /* clear its key */ ++ else if (iscleared(g, gckeyN(n))) { /* key is not marked (yet)? */ ++ hasclears = 1; /* table must be cleared */ ++ if (valiswhite(gval(n))) /* value not marked yet? */ ++ hasww = 1; /* white-white entry */ ++ } ++ else if (valiswhite(gval(n))) { /* value not marked yet? */ ++ marked = 1; ++ reallymarkobject(g, gcvalue(gval(n))); /* mark it now */ ++ } ++ } ++ /* link table into proper list */ ++ if (g->gcstate == GCSpropagate) ++ linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */ ++ else if (hasww) /* table has white->white entries? */ ++ linkgclist(h, g->ephemeron); /* have to propagate again */ ++ else if (hasclears) /* table has white keys? */ ++ linkgclist(h, g->allweak); /* may have to clean white keys */ ++ else ++ genlink(g, obj2gco(h)); /* check whether collector still needs to see it */ ++ return marked; ++} ++ ++ ++static void traversestrongtable (global_State *g, Table *h) { ++ Node *n, *limit = gnodelast(h); ++ unsigned int i; ++ unsigned int asize = luaH_realasize(h); ++ for (i = 0; i < asize; i++) /* traverse array part */ ++ markvalue(g, &h->array[i]); ++ for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */ ++ if (isempty(gval(n))) /* entry is empty? */ ++ clearkey(n); /* clear its key */ ++ else { ++ lua_assert(!keyisnil(n)); ++ markkey(g, n); ++ markvalue(g, gval(n)); ++ } ++ } ++ genlink(g, obj2gco(h)); ++} ++ ++ ++static lu_mem traversetable (global_State *g, Table *h) { ++ const char *weakkey, *weakvalue; ++ const TValue *mode = gfasttm(g, h->metatable, TM_MODE); ++ markobjectN(g, h->metatable); ++ if (mode && ttisstring(mode) && /* is there a weak mode? */ ++ (cast_void(weakkey = strchr(svalue(mode), 'k')), ++ cast_void(weakvalue = strchr(svalue(mode), 'v')), ++ (weakkey || weakvalue))) { /* is really weak? */ ++ if (!weakkey) /* strong keys? */ ++ traverseweakvalue(g, h); ++ else if (!weakvalue) /* strong values? */ ++ traverseephemeron(g, h, 0); ++ else /* all weak */ ++ linkgclist(h, g->allweak); /* nothing to traverse now */ ++ } ++ else /* not weak */ ++ traversestrongtable(g, h); ++ return 1 + h->alimit + 2 * allocsizenode(h); ++} ++ ++ ++static int traverseudata (global_State *g, Udata *u) { ++ int i; ++ markobjectN(g, u->metatable); /* mark its metatable */ ++ for (i = 0; i < u->nuvalue; i++) ++ markvalue(g, &u->uv[i].uv); ++ genlink(g, obj2gco(u)); ++ return 1 + u->nuvalue; ++} ++ ++ ++/* ++** Traverse a prototype. (While a prototype is being build, its ++** arrays can be larger than needed; the extra slots are filled with ++** NULL, so the use of 'markobjectN') ++*/ ++static int traverseproto (global_State *g, Proto *f) { ++ int i; ++ markobjectN(g, f->source); ++ for (i = 0; i < f->sizek; i++) /* mark literals */ ++ markvalue(g, &f->k[i]); ++ for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */ ++ markobjectN(g, f->upvalues[i].name); ++ for (i = 0; i < f->sizep; i++) /* mark nested protos */ ++ markobjectN(g, f->p[i]); ++ for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */ ++ markobjectN(g, f->locvars[i].varname); ++ return 1 + f->sizek + f->sizeupvalues + f->sizep + f->sizelocvars; ++} ++ ++ ++static int traverseCclosure (global_State *g, CClosure *cl) { ++ int i; ++ for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */ ++ markvalue(g, &cl->upvalue[i]); ++ return 1 + cl->nupvalues; ++} ++ ++/* ++** Traverse a Lua closure, marking its prototype and its upvalues. ++** (Both can be NULL while closure is being created.) ++*/ ++static int traverseLclosure (global_State *g, LClosure *cl) { ++ int i; ++ markobjectN(g, cl->p); /* mark its prototype */ ++ for (i = 0; i < cl->nupvalues; i++) { /* visit its upvalues */ ++ UpVal *uv = cl->upvals[i]; ++ markobjectN(g, uv); /* mark upvalue */ ++ } ++ return 1 + cl->nupvalues; ++} ++ ++ ++/* ++** Traverse a thread, marking the elements in the stack up to its top ++** and cleaning the rest of the stack in the final traversal. That ++** ensures that the entire stack have valid (non-dead) objects. ++** Threads have no barriers. In gen. mode, old threads must be visited ++** at every cycle, because they might point to young objects. In inc. ++** mode, the thread can still be modified before the end of the cycle, ++** and therefore it must be visited again in the atomic phase. To ensure ++** these visits, threads must return to a gray list if they are not new ++** (which can only happen in generational mode) or if the traverse is in ++** the propagate phase (which can only happen in incremental mode). ++*/ ++static int traversethread (global_State *g, lua_State *th) { ++ UpVal *uv; ++ StkId o = th->stack; ++ if (isold(th) || g->gcstate == GCSpropagate) ++ linkgclist(th, g->grayagain); /* insert into 'grayagain' list */ ++ if (o == NULL) ++ return 1; /* stack not completely built yet */ ++ lua_assert(g->gcstate == GCSatomic || ++ th->openupval == NULL || isintwups(th)); ++ for (; o < th->top; o++) /* mark live elements in the stack */ ++ markvalue(g, s2v(o)); ++ for (uv = th->openupval; uv != NULL; uv = uv->u.open.next) ++ markobject(g, uv); /* open upvalues cannot be collected */ ++ if (g->gcstate == GCSatomic) { /* final traversal? */ ++ for (; o < th->stack_last + EXTRA_STACK; o++) ++ setnilvalue(s2v(o)); /* clear dead stack slice */ ++ /* 'remarkupvals' may have removed thread from 'twups' list */ ++ if (!isintwups(th) && th->openupval != NULL) { ++ th->twups = g->twups; /* link it back to the list */ ++ g->twups = th; ++ } ++ } ++ else if (!g->gcemergency) ++ luaD_shrinkstack(th); /* do not change stack in emergency cycle */ ++ return 1 + stacksize(th); ++} ++ ++ ++/* ++** traverse one gray object, turning it to black. ++*/ ++static lu_mem propagatemark (global_State *g) { ++ GCObject *o = g->gray; ++ nw2black(o); ++ g->gray = *getgclist(o); /* remove from 'gray' list */ ++ switch (o->tt) { ++ case LUA_VTABLE: return traversetable(g, gco2t(o)); ++ case LUA_VUSERDATA: return traverseudata(g, gco2u(o)); ++ case LUA_VLCL: return traverseLclosure(g, gco2lcl(o)); ++ case LUA_VCCL: return traverseCclosure(g, gco2ccl(o)); ++ case LUA_VPROTO: return traverseproto(g, gco2p(o)); ++ case LUA_VTHREAD: return traversethread(g, gco2th(o)); ++ default: lua_assert(0); return 0; ++ } ++} ++ ++ ++static lu_mem propagateall (global_State *g) { ++ lu_mem tot = 0; ++ while (g->gray) ++ tot += propagatemark(g); ++ return tot; ++} ++ ++ ++/* ++** Traverse all ephemeron tables propagating marks from keys to values. ++** Repeat until it converges, that is, nothing new is marked. 'dir' ++** inverts the direction of the traversals, trying to speed up ++** convergence on chains in the same table. ++** ++*/ ++static void convergeephemerons (global_State *g) { ++ int changed; ++ int dir = 0; ++ do { ++ GCObject *w; ++ GCObject *next = g->ephemeron; /* get ephemeron list */ ++ g->ephemeron = NULL; /* tables may return to this list when traversed */ ++ changed = 0; ++ while ((w = next) != NULL) { /* for each ephemeron table */ ++ Table *h = gco2t(w); ++ next = h->gclist; /* list is rebuilt during loop */ ++ nw2black(h); /* out of the list (for now) */ ++ if (traverseephemeron(g, h, dir)) { /* marked some value? */ ++ propagateall(g); /* propagate changes */ ++ changed = 1; /* will have to revisit all ephemeron tables */ ++ } ++ } ++ dir = !dir; /* invert direction next time */ ++ } while (changed); /* repeat until no more changes */ ++} ++ ++/* }====================================================== */ ++ ++ ++/* ++** {====================================================== ++** Sweep Functions ++** ======================================================= ++*/ ++ ++ ++/* ++** clear entries with unmarked keys from all weaktables in list 'l' ++*/ ++static void clearbykeys (global_State *g, GCObject *l) { ++ for (; l; l = gco2t(l)->gclist) { ++ Table *h = gco2t(l); ++ Node *limit = gnodelast(h); ++ Node *n; ++ for (n = gnode(h, 0); n < limit; n++) { ++ if (iscleared(g, gckeyN(n))) /* unmarked key? */ ++ setempty(gval(n)); /* remove entry */ ++ if (isempty(gval(n))) /* is entry empty? */ ++ clearkey(n); /* clear its key */ ++ } ++ } ++} ++ ++ ++/* ++** clear entries with unmarked values from all weaktables in list 'l' up ++** to element 'f' ++*/ ++static void clearbyvalues (global_State *g, GCObject *l, GCObject *f) { ++ for (; l != f; l = gco2t(l)->gclist) { ++ Table *h = gco2t(l); ++ Node *n, *limit = gnodelast(h); ++ unsigned int i; ++ unsigned int asize = luaH_realasize(h); ++ for (i = 0; i < asize; i++) { ++ TValue *o = &h->array[i]; ++ if (iscleared(g, gcvalueN(o))) /* value was collected? */ ++ setempty(o); /* remove entry */ ++ } ++ for (n = gnode(h, 0); n < limit; n++) { ++ if (iscleared(g, gcvalueN(gval(n)))) /* unmarked value? */ ++ setempty(gval(n)); /* remove entry */ ++ if (isempty(gval(n))) /* is entry empty? */ ++ clearkey(n); /* clear its key */ ++ } ++ } ++} ++ ++ ++static void freeupval (lua_State *L, UpVal *uv) { ++ if (upisopen(uv)) ++ luaF_unlinkupval(uv); ++ luaM_free(L, uv); ++} ++ ++ ++static void freeobj (lua_State *L, GCObject *o) { ++ switch (o->tt) { ++ case LUA_VPROTO: ++ luaF_freeproto(L, gco2p(o)); ++ break; ++ case LUA_VUPVAL: ++ freeupval(L, gco2upv(o)); ++ break; ++ case LUA_VLCL: { ++ LClosure *cl = gco2lcl(o); ++ luaM_freemem(L, cl, sizeLclosure(cl->nupvalues)); ++ break; ++ } ++ case LUA_VCCL: { ++ CClosure *cl = gco2ccl(o); ++ luaM_freemem(L, cl, sizeCclosure(cl->nupvalues)); ++ break; ++ } ++ case LUA_VTABLE: ++ luaH_free(L, gco2t(o)); ++ break; ++ case LUA_VTHREAD: ++ luaE_freethread(L, gco2th(o)); ++ break; ++ case LUA_VUSERDATA: { ++ Udata *u = gco2u(o); ++ luaM_freemem(L, o, sizeudata(u->nuvalue, u->len)); ++ break; ++ } ++ case LUA_VSHRSTR: { ++ TString *ts = gco2ts(o); ++ luaS_remove(L, ts); /* remove it from hash table */ ++ luaM_freemem(L, ts, sizelstring(ts->shrlen)); ++ break; ++ } ++ case LUA_VLNGSTR: { ++ TString *ts = gco2ts(o); ++ luaM_freemem(L, ts, sizelstring(ts->u.lnglen)); ++ break; ++ } ++ default: lua_assert(0); ++ } ++} ++ ++ ++/* ++** sweep at most 'countin' elements from a list of GCObjects erasing dead ++** objects, where a dead object is one marked with the old (non current) ++** white; change all non-dead objects back to white, preparing for next ++** collection cycle. Return where to continue the traversal or NULL if ++** list is finished. ('*countout' gets the number of elements traversed.) ++*/ ++static GCObject **sweeplist (lua_State *L, GCObject **p, int countin, ++ int *countout) { ++ global_State *g = G(L); ++ int ow = otherwhite(g); ++ int i; ++ int white = luaC_white(g); /* current white */ ++ for (i = 0; *p != NULL && i < countin; i++) { ++ GCObject *curr = *p; ++ int marked = curr->marked; ++ if (isdeadm(ow, marked)) { /* is 'curr' dead? */ ++ *p = curr->next; /* remove 'curr' from list */ ++ freeobj(L, curr); /* erase 'curr' */ ++ } ++ else { /* change mark to 'white' */ ++ curr->marked = cast_byte((marked & ~maskgcbits) | white); ++ p = &curr->next; /* go to next element */ ++ } ++ } ++ if (countout) ++ *countout = i; /* number of elements traversed */ ++ return (*p == NULL) ? NULL : p; ++} ++ ++ ++/* ++** sweep a list until a live object (or end of list) ++*/ ++static GCObject **sweeptolive (lua_State *L, GCObject **p) { ++ GCObject **old = p; ++ do { ++ p = sweeplist(L, p, 1, NULL); ++ } while (p == old); ++ return p; ++} ++ ++/* }====================================================== */ ++ ++ ++/* ++** {====================================================== ++** Finalization ++** ======================================================= ++*/ ++ ++/* ++** If possible, shrink string table. ++*/ ++static void checkSizes (lua_State *L, global_State *g) { ++ if (!g->gcemergency) { ++ if (g->strt.nuse < g->strt.size / 4) { /* string table too big? */ ++ l_mem olddebt = g->GCdebt; ++ luaS_resize(L, g->strt.size / 2); ++ g->GCestimate += g->GCdebt - olddebt; /* correct estimate */ ++ } ++ } ++} ++ ++ ++/* ++** Get the next udata to be finalized from the 'tobefnz' list, and ++** link it back into the 'allgc' list. ++*/ ++static GCObject *udata2finalize (global_State *g) { ++ GCObject *o = g->tobefnz; /* get first element */ ++ lua_assert(tofinalize(o)); ++ g->tobefnz = o->next; /* remove it from 'tobefnz' list */ ++ o->next = g->allgc; /* return it to 'allgc' list */ ++ g->allgc = o; ++ resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */ ++ if (issweepphase(g)) ++ makewhite(g, o); /* "sweep" object */ ++ else if (getage(o) == G_OLD1) ++ g->firstold1 = o; /* it is the first OLD1 object in the list */ ++ return o; ++} ++ ++ ++static void dothecall (lua_State *L, void *ud) { ++ UNUSED(ud); ++ luaD_callnoyield(L, L->top - 2, 0); ++} ++ ++ ++static void GCTM (lua_State *L) { ++ global_State *g = G(L); ++ const TValue *tm; ++ TValue v; ++ lua_assert(!g->gcemergency); ++ setgcovalue(L, &v, udata2finalize(g)); ++ tm = luaT_gettmbyobj(L, &v, TM_GC); ++ if (!notm(tm)) { /* is there a finalizer? */ ++ int status; ++ lu_byte oldah = L->allowhook; ++ int running = g->gcrunning; ++ L->allowhook = 0; /* stop debug hooks during GC metamethod */ ++ g->gcrunning = 0; /* avoid GC steps */ ++ setobj2s(L, L->top++, tm); /* push finalizer... */ ++ setobj2s(L, L->top++, &v); /* ... and its argument */ ++ L->ci->callstatus |= CIST_FIN; /* will run a finalizer */ ++ status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0); ++ L->ci->callstatus &= ~CIST_FIN; /* not running a finalizer anymore */ ++ L->allowhook = oldah; /* restore hooks */ ++ g->gcrunning = running; /* restore state */ ++ if (l_unlikely(status != LUA_OK)) { /* error while running __gc? */ ++ luaE_warnerror(L, "__gc metamethod"); ++ L->top--; /* pops error object */ ++ } ++ } ++} ++ ++ ++/* ++** Call a few finalizers ++*/ ++static int runafewfinalizers (lua_State *L, int n) { ++ global_State *g = G(L); ++ int i; ++ for (i = 0; i < n && g->tobefnz; i++) ++ GCTM(L); /* call one finalizer */ ++ return i; ++} ++ ++ ++/* ++** call all pending finalizers ++*/ ++static void callallpendingfinalizers (lua_State *L) { ++ global_State *g = G(L); ++ while (g->tobefnz) ++ GCTM(L); ++} ++ ++ ++/* ++** find last 'next' field in list 'p' list (to add elements in its end) ++*/ ++static GCObject **findlast (GCObject **p) { ++ while (*p != NULL) ++ p = &(*p)->next; ++ return p; ++} ++ ++ ++/* ++** Move all unreachable objects (or 'all' objects) that need ++** finalization from list 'finobj' to list 'tobefnz' (to be finalized). ++** (Note that objects after 'finobjold1' cannot be white, so they ++** don't need to be traversed. In incremental mode, 'finobjold1' is NULL, ++** so the whole list is traversed.) ++*/ ++static void separatetobefnz (global_State *g, int all) { ++ GCObject *curr; ++ GCObject **p = &g->finobj; ++ GCObject **lastnext = findlast(&g->tobefnz); ++ while ((curr = *p) != g->finobjold1) { /* traverse all finalizable objects */ ++ lua_assert(tofinalize(curr)); ++ if (!(iswhite(curr) || all)) /* not being collected? */ ++ p = &curr->next; /* don't bother with it */ ++ else { ++ if (curr == g->finobjsur) /* removing 'finobjsur'? */ ++ g->finobjsur = curr->next; /* correct it */ ++ *p = curr->next; /* remove 'curr' from 'finobj' list */ ++ curr->next = *lastnext; /* link at the end of 'tobefnz' list */ ++ *lastnext = curr; ++ lastnext = &curr->next; ++ } ++ } ++} ++ ++ ++/* ++** If pointer 'p' points to 'o', move it to the next element. ++*/ ++static void checkpointer (GCObject **p, GCObject *o) { ++ if (o == *p) ++ *p = o->next; ++} ++ ++ ++/* ++** Correct pointers to objects inside 'allgc' list when ++** object 'o' is being removed from the list. ++*/ ++static void correctpointers (global_State *g, GCObject *o) { ++ checkpointer(&g->survival, o); ++ checkpointer(&g->old1, o); ++ checkpointer(&g->reallyold, o); ++ checkpointer(&g->firstold1, o); ++} ++ ++ ++/* ++** if object 'o' has a finalizer, remove it from 'allgc' list (must ++** search the list to find it) and link it in 'finobj' list. ++*/ ++void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) { ++ global_State *g = G(L); ++ if (tofinalize(o) || /* obj. is already marked... */ ++ gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */ ++ return; /* nothing to be done */ ++ else { /* move 'o' to 'finobj' list */ ++ GCObject **p; ++ if (issweepphase(g)) { ++ makewhite(g, o); /* "sweep" object 'o' */ ++ if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */ ++ g->sweepgc = sweeptolive(L, g->sweepgc); /* change 'sweepgc' */ ++ } ++ else ++ correctpointers(g, o); ++ /* search for pointer pointing to 'o' */ ++ for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ } ++ *p = o->next; /* remove 'o' from 'allgc' list */ ++ o->next = g->finobj; /* link it in 'finobj' list */ ++ g->finobj = o; ++ l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */ ++ } ++} ++ ++/* }====================================================== */ ++ ++ ++/* ++** {====================================================== ++** Generational Collector ++** ======================================================= ++*/ ++ ++static void setpause (global_State *g); ++ ++ ++/* ++** Sweep a list of objects to enter generational mode. Deletes dead ++** objects and turns the non dead to old. All non-dead threads---which ++** are now old---must be in a gray list. Everything else is not in a ++** gray list. Open upvalues are also kept gray. ++*/ ++static void sweep2old (lua_State *L, GCObject **p) { ++ GCObject *curr; ++ global_State *g = G(L); ++ while ((curr = *p) != NULL) { ++ if (iswhite(curr)) { /* is 'curr' dead? */ ++ lua_assert(isdead(g, curr)); ++ *p = curr->next; /* remove 'curr' from list */ ++ freeobj(L, curr); /* erase 'curr' */ ++ } ++ else { /* all surviving objects become old */ ++ setage(curr, G_OLD); ++ if (curr->tt == LUA_VTHREAD) { /* threads must be watched */ ++ lua_State *th = gco2th(curr); ++ linkgclist(th, g->grayagain); /* insert into 'grayagain' list */ ++ } ++ else if (curr->tt == LUA_VUPVAL && upisopen(gco2upv(curr))) ++ set2gray(curr); /* open upvalues are always gray */ ++ else /* everything else is black */ ++ nw2black(curr); ++ p = &curr->next; /* go to next element */ ++ } ++ } ++} ++ ++ ++/* ++** Sweep for generational mode. Delete dead objects. (Because the ++** collection is not incremental, there are no "new white" objects ++** during the sweep. So, any white object must be dead.) For ++** non-dead objects, advance their ages and clear the color of ++** new objects. (Old objects keep their colors.) ++** The ages of G_TOUCHED1 and G_TOUCHED2 objects cannot be advanced ++** here, because these old-generation objects are usually not swept ++** here. They will all be advanced in 'correctgraylist'. That function ++** will also remove objects turned white here from any gray list. ++*/ ++static GCObject **sweepgen (lua_State *L, global_State *g, GCObject **p, ++ GCObject *limit, GCObject **pfirstold1) { ++ static const lu_byte nextage[] = { ++ G_SURVIVAL, /* from G_NEW */ ++ G_OLD1, /* from G_SURVIVAL */ ++ G_OLD1, /* from G_OLD0 */ ++ G_OLD, /* from G_OLD1 */ ++ G_OLD, /* from G_OLD (do not change) */ ++ G_TOUCHED1, /* from G_TOUCHED1 (do not change) */ ++ G_TOUCHED2 /* from G_TOUCHED2 (do not change) */ ++ }; ++ int white = luaC_white(g); ++ GCObject *curr; ++ while ((curr = *p) != limit) { ++ if (iswhite(curr)) { /* is 'curr' dead? */ ++ lua_assert(!isold(curr) && isdead(g, curr)); ++ *p = curr->next; /* remove 'curr' from list */ ++ freeobj(L, curr); /* erase 'curr' */ ++ } ++ else { /* correct mark and age */ ++ if (getage(curr) == G_NEW) { /* new objects go back to white */ ++ int marked = curr->marked & ~maskgcbits; /* erase GC bits */ ++ curr->marked = cast_byte(marked | G_SURVIVAL | white); ++ } ++ else { /* all other objects will be old, and so keep their color */ ++ setage(curr, nextage[getage(curr)]); ++ if (getage(curr) == G_OLD1 && *pfirstold1 == NULL) ++ *pfirstold1 = curr; /* first OLD1 object in the list */ ++ } ++ p = &curr->next; /* go to next element */ ++ } ++ } ++ return p; ++} ++ ++ ++/* ++** Traverse a list making all its elements white and clearing their ++** age. In incremental mode, all objects are 'new' all the time, ++** except for fixed strings (which are always old). ++*/ ++static void whitelist (global_State *g, GCObject *p) { ++ int white = luaC_white(g); ++ for (; p != NULL; p = p->next) ++ p->marked = cast_byte((p->marked & ~maskgcbits) | white); ++} ++ ++ ++/* ++** Correct a list of gray objects. Return pointer to where rest of the ++** list should be linked. ++** Because this correction is done after sweeping, young objects might ++** be turned white and still be in the list. They are only removed. ++** 'TOUCHED1' objects are advanced to 'TOUCHED2' and remain on the list; ++** Non-white threads also remain on the list; 'TOUCHED2' objects become ++** regular old; they and anything else are removed from the list. ++*/ ++static GCObject **correctgraylist (GCObject **p) { ++ GCObject *curr; ++ while ((curr = *p) != NULL) { ++ GCObject **next = getgclist(curr); ++ if (iswhite(curr)) ++ goto remove; /* remove all white objects */ ++ else if (getage(curr) == G_TOUCHED1) { /* touched in this cycle? */ ++ lua_assert(isgray(curr)); ++ nw2black(curr); /* make it black, for next barrier */ ++ changeage(curr, G_TOUCHED1, G_TOUCHED2); ++ goto remain; /* keep it in the list and go to next element */ ++ } ++ else if (curr->tt == LUA_VTHREAD) { ++ lua_assert(isgray(curr)); ++ goto remain; /* keep non-white threads on the list */ ++ } ++ else { /* everything else is removed */ ++ lua_assert(isold(curr)); /* young objects should be white here */ ++ if (getage(curr) == G_TOUCHED2) /* advance from TOUCHED2... */ ++ changeage(curr, G_TOUCHED2, G_OLD); /* ... to OLD */ ++ nw2black(curr); /* make object black (to be removed) */ ++ goto remove; ++ } ++ remove: *p = *next; continue; ++ remain: p = next; continue; ++ } ++ return p; ++} ++ ++ ++/* ++** Correct all gray lists, coalescing them into 'grayagain'. ++*/ ++static void correctgraylists (global_State *g) { ++ GCObject **list = correctgraylist(&g->grayagain); ++ *list = g->weak; g->weak = NULL; ++ list = correctgraylist(list); ++ *list = g->allweak; g->allweak = NULL; ++ list = correctgraylist(list); ++ *list = g->ephemeron; g->ephemeron = NULL; ++ correctgraylist(list); ++} ++ ++ ++/* ++** Mark black 'OLD1' objects when starting a new young collection. ++** Gray objects are already in some gray list, and so will be visited ++** in the atomic step. ++*/ ++static void markold (global_State *g, GCObject *from, GCObject *to) { ++ GCObject *p; ++ for (p = from; p != to; p = p->next) { ++ if (getage(p) == G_OLD1) { ++ lua_assert(!iswhite(p)); ++ changeage(p, G_OLD1, G_OLD); /* now they are old */ ++ if (isblack(p)) ++ reallymarkobject(g, p); ++ } ++ } ++} ++ ++ ++/* ++** Finish a young-generation collection. ++*/ ++static void finishgencycle (lua_State *L, global_State *g) { ++ correctgraylists(g); ++ checkSizes(L, g); ++ g->gcstate = GCSpropagate; /* skip restart */ ++ if (!g->gcemergency) ++ callallpendingfinalizers(L); ++} ++ ++ ++/* ++** Does a young collection. First, mark 'OLD1' objects. Then does the ++** atomic step. Then, sweep all lists and advance pointers. Finally, ++** finish the collection. ++*/ ++static void youngcollection (lua_State *L, global_State *g) { ++ GCObject **psurvival; /* to point to first non-dead survival object */ ++ GCObject *dummy; /* dummy out parameter to 'sweepgen' */ ++ lua_assert(g->gcstate == GCSpropagate); ++ if (g->firstold1) { /* are there regular OLD1 objects? */ ++ markold(g, g->firstold1, g->reallyold); /* mark them */ ++ g->firstold1 = NULL; /* no more OLD1 objects (for now) */ ++ } ++ markold(g, g->finobj, g->finobjrold); ++ markold(g, g->tobefnz, NULL); ++ atomic(L); ++ ++ /* sweep nursery and get a pointer to its last live element */ ++ g->gcstate = GCSswpallgc; ++ psurvival = sweepgen(L, g, &g->allgc, g->survival, &g->firstold1); ++ /* sweep 'survival' */ ++ sweepgen(L, g, psurvival, g->old1, &g->firstold1); ++ g->reallyold = g->old1; ++ g->old1 = *psurvival; /* 'survival' survivals are old now */ ++ g->survival = g->allgc; /* all news are survivals */ ++ ++ /* repeat for 'finobj' lists */ ++ dummy = NULL; /* no 'firstold1' optimization for 'finobj' lists */ ++ psurvival = sweepgen(L, g, &g->finobj, g->finobjsur, &dummy); ++ /* sweep 'survival' */ ++ sweepgen(L, g, psurvival, g->finobjold1, &dummy); ++ g->finobjrold = g->finobjold1; ++ g->finobjold1 = *psurvival; /* 'survival' survivals are old now */ ++ g->finobjsur = g->finobj; /* all news are survivals */ ++ ++ sweepgen(L, g, &g->tobefnz, NULL, &dummy); ++ finishgencycle(L, g); ++} ++ ++ ++/* ++** Clears all gray lists, sweeps objects, and prepare sublists to enter ++** generational mode. The sweeps remove dead objects and turn all ++** surviving objects to old. Threads go back to 'grayagain'; everything ++** else is turned black (not in any gray list). ++*/ ++static void atomic2gen (lua_State *L, global_State *g) { ++ cleargraylists(g); ++ /* sweep all elements making them old */ ++ g->gcstate = GCSswpallgc; ++ sweep2old(L, &g->allgc); ++ /* everything alive now is old */ ++ g->reallyold = g->old1 = g->survival = g->allgc; ++ g->firstold1 = NULL; /* there are no OLD1 objects anywhere */ ++ ++ /* repeat for 'finobj' lists */ ++ sweep2old(L, &g->finobj); ++ g->finobjrold = g->finobjold1 = g->finobjsur = g->finobj; ++ ++ sweep2old(L, &g->tobefnz); ++ ++ g->gckind = KGC_GEN; ++ g->lastatomic = 0; ++ g->GCestimate = gettotalbytes(g); /* base for memory control */ ++ finishgencycle(L, g); ++} ++ ++ ++/* ++** Enter generational mode. Must go until the end of an atomic cycle ++** to ensure that all objects are correctly marked and weak tables ++** are cleared. Then, turn all objects into old and finishes the ++** collection. ++*/ ++static lu_mem entergen (lua_State *L, global_State *g) { ++ lu_mem numobjs; ++ luaC_runtilstate(L, bitmask(GCSpause)); /* prepare to start a new cycle */ ++ luaC_runtilstate(L, bitmask(GCSpropagate)); /* start new cycle */ ++ numobjs = atomic(L); /* propagates all and then do the atomic stuff */ ++ atomic2gen(L, g); ++ return numobjs; ++} ++ ++ ++/* ++** Enter incremental mode. Turn all objects white, make all ++** intermediate lists point to NULL (to avoid invalid pointers), ++** and go to the pause state. ++*/ ++static void enterinc (global_State *g) { ++ whitelist(g, g->allgc); ++ g->reallyold = g->old1 = g->survival = NULL; ++ whitelist(g, g->finobj); ++ whitelist(g, g->tobefnz); ++ g->finobjrold = g->finobjold1 = g->finobjsur = NULL; ++ g->gcstate = GCSpause; ++ g->gckind = KGC_INC; ++ g->lastatomic = 0; ++} ++ ++ ++/* ++** Change collector mode to 'newmode'. ++*/ ++void luaC_changemode (lua_State *L, int newmode) { ++ global_State *g = G(L); ++ if (newmode != g->gckind) { ++ if (newmode == KGC_GEN) /* entering generational mode? */ ++ entergen(L, g); ++ else ++ enterinc(g); /* entering incremental mode */ ++ } ++ g->lastatomic = 0; ++} ++ ++ ++/* ++** Does a full collection in generational mode. ++*/ ++static lu_mem fullgen (lua_State *L, global_State *g) { ++ enterinc(g); ++ return entergen(L, g); ++} ++ ++ ++/* ++** Set debt for the next minor collection, which will happen when ++** memory grows 'genminormul'%. ++*/ ++static void setminordebt (global_State *g) { ++ luaE_setdebt(g, -(cast(l_mem, (gettotalbytes(g) / 100)) * g->genminormul)); ++} ++ ++ ++/* ++** Does a major collection after last collection was a "bad collection". ++** ++** When the program is building a big structure, it allocates lots of ++** memory but generates very little garbage. In those scenarios, ++** the generational mode just wastes time doing small collections, and ++** major collections are frequently what we call a "bad collection", a ++** collection that frees too few objects. To avoid the cost of switching ++** between generational mode and the incremental mode needed for full ++** (major) collections, the collector tries to stay in incremental mode ++** after a bad collection, and to switch back to generational mode only ++** after a "good" collection (one that traverses less than 9/8 objects ++** of the previous one). ++** The collector must choose whether to stay in incremental mode or to ++** switch back to generational mode before sweeping. At this point, it ++** does not know the real memory in use, so it cannot use memory to ++** decide whether to return to generational mode. Instead, it uses the ++** number of objects traversed (returned by 'atomic') as a proxy. The ++** field 'g->lastatomic' keeps this count from the last collection. ++** ('g->lastatomic != 0' also means that the last collection was bad.) ++*/ ++static void stepgenfull (lua_State *L, global_State *g) { ++ lu_mem newatomic; /* count of traversed objects */ ++ lu_mem lastatomic = g->lastatomic; /* count from last collection */ ++ if (g->gckind == KGC_GEN) /* still in generational mode? */ ++ enterinc(g); /* enter incremental mode */ ++ luaC_runtilstate(L, bitmask(GCSpropagate)); /* start new cycle */ ++ newatomic = atomic(L); /* mark everybody */ ++ if (newatomic < lastatomic + (lastatomic >> 3)) { /* good collection? */ ++ atomic2gen(L, g); /* return to generational mode */ ++ setminordebt(g); ++ } ++ else { /* another bad collection; stay in incremental mode */ ++ g->GCestimate = gettotalbytes(g); /* first estimate */; ++ entersweep(L); ++ luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */ ++ setpause(g); ++ g->lastatomic = newatomic; ++ } ++} ++ ++ ++/* ++** Does a generational "step". ++** Usually, this means doing a minor collection and setting the debt to ++** make another collection when memory grows 'genminormul'% larger. ++** ++** However, there are exceptions. If memory grows 'genmajormul'% ++** larger than it was at the end of the last major collection (kept ++** in 'g->GCestimate'), the function does a major collection. At the ++** end, it checks whether the major collection was able to free a ++** decent amount of memory (at least half the growth in memory since ++** previous major collection). If so, the collector keeps its state, ++** and the next collection will probably be minor again. Otherwise, ++** we have what we call a "bad collection". In that case, set the field ++** 'g->lastatomic' to signal that fact, so that the next collection will ++** go to 'stepgenfull'. ++** ++** 'GCdebt <= 0' means an explicit call to GC step with "size" zero; ++** in that case, do a minor collection. ++*/ ++static void genstep (lua_State *L, global_State *g) { ++ if (g->lastatomic != 0) /* last collection was a bad one? */ ++ stepgenfull(L, g); /* do a full step */ ++ else { ++ lu_mem majorbase = g->GCestimate; /* memory after last major collection */ ++ lu_mem majorinc = (majorbase / 100) * getgcparam(g->genmajormul); ++ if (g->GCdebt > 0 && gettotalbytes(g) > majorbase + majorinc) { ++ lu_mem numobjs = fullgen(L, g); /* do a major collection */ ++ if (gettotalbytes(g) < majorbase + (majorinc / 2)) { ++ /* collected at least half of memory growth since last major ++ collection; keep doing minor collections */ ++ setminordebt(g); ++ } ++ else { /* bad collection */ ++ g->lastatomic = numobjs; /* signal that last collection was bad */ ++ setpause(g); /* do a long wait for next (major) collection */ ++ } ++ } ++ else { /* regular case; do a minor collection */ ++ youngcollection(L, g); ++ setminordebt(g); ++ g->GCestimate = majorbase; /* preserve base value */ ++ } ++ } ++ lua_assert(isdecGCmodegen(g)); ++} ++ ++/* }====================================================== */ ++ ++ ++/* ++** {====================================================== ++** GC control ++** ======================================================= ++*/ ++ ++ ++/* ++** Set the "time" to wait before starting a new GC cycle; cycle will ++** start when memory use hits the threshold of ('estimate' * pause / ++** PAUSEADJ). (Division by 'estimate' should be OK: it cannot be zero, ++** because Lua cannot even start with less than PAUSEADJ bytes). ++*/ ++static void setpause (global_State *g) { ++ l_mem threshold, debt; ++ int pause = getgcparam(g->gcpause); ++ l_mem estimate = g->GCestimate / PAUSEADJ; /* adjust 'estimate' */ ++ lua_assert(estimate > 0); ++ threshold = (pause < MAX_LMEM / estimate) /* overflow? */ ++ ? estimate * pause /* no overflow */ ++ : MAX_LMEM; /* overflow; truncate to maximum */ ++ debt = gettotalbytes(g) - threshold; ++ if (debt > 0) debt = 0; ++ luaE_setdebt(g, debt); ++} ++ ++ ++/* ++** Enter first sweep phase. ++** The call to 'sweeptolive' makes the pointer point to an object ++** inside the list (instead of to the header), so that the real sweep do ++** not need to skip objects created between "now" and the start of the ++** real sweep. ++*/ ++static void entersweep (lua_State *L) { ++ global_State *g = G(L); ++ g->gcstate = GCSswpallgc; ++ lua_assert(g->sweepgc == NULL); ++ g->sweepgc = sweeptolive(L, &g->allgc); ++} ++ ++ ++/* ++** Delete all objects in list 'p' until (but not including) object ++** 'limit'. ++*/ ++static void deletelist (lua_State *L, GCObject *p, GCObject *limit) { ++ while (p != limit) { ++ GCObject *next = p->next; ++ freeobj(L, p); ++ p = next; ++ } ++} ++ ++ ++/* ++** Call all finalizers of the objects in the given Lua state, and ++** then free all objects, except for the main thread. ++*/ ++void luaC_freeallobjects (lua_State *L) { ++ global_State *g = G(L); ++ luaC_changemode(L, KGC_INC); ++ separatetobefnz(g, 1); /* separate all objects with finalizers */ ++ lua_assert(g->finobj == NULL); ++ callallpendingfinalizers(L); ++ deletelist(L, g->allgc, obj2gco(g->mainthread)); ++ deletelist(L, g->finobj, NULL); ++ deletelist(L, g->fixedgc, NULL); /* collect fixed objects */ ++ lua_assert(g->strt.nuse == 0); ++} ++ ++ ++static lu_mem atomic (lua_State *L) { ++ global_State *g = G(L); ++ lu_mem work = 0; ++ GCObject *origweak, *origall; ++ GCObject *grayagain = g->grayagain; /* save original list */ ++ g->grayagain = NULL; ++ lua_assert(g->ephemeron == NULL && g->weak == NULL); ++ lua_assert(!iswhite(g->mainthread)); ++ g->gcstate = GCSatomic; ++ markobject(g, L); /* mark running thread */ ++ /* registry and global metatables may be changed by API */ ++ markvalue(g, &g->l_registry); ++ markmt(g); /* mark global metatables */ ++ work += propagateall(g); /* empties 'gray' list */ ++ /* remark occasional upvalues of (maybe) dead threads */ ++ work += remarkupvals(g); ++ work += propagateall(g); /* propagate changes */ ++ g->gray = grayagain; ++ work += propagateall(g); /* traverse 'grayagain' list */ ++ convergeephemerons(g); ++ /* at this point, all strongly accessible objects are marked. */ ++ /* Clear values from weak tables, before checking finalizers */ ++ clearbyvalues(g, g->weak, NULL); ++ clearbyvalues(g, g->allweak, NULL); ++ origweak = g->weak; origall = g->allweak; ++ separatetobefnz(g, 0); /* separate objects to be finalized */ ++ work += markbeingfnz(g); /* mark objects that will be finalized */ ++ work += propagateall(g); /* remark, to propagate 'resurrection' */ ++ convergeephemerons(g); ++ /* at this point, all resurrected objects are marked. */ ++ /* remove dead objects from weak tables */ ++ clearbykeys(g, g->ephemeron); /* clear keys from all ephemeron tables */ ++ clearbykeys(g, g->allweak); /* clear keys from all 'allweak' tables */ ++ /* clear values from resurrected weak tables */ ++ clearbyvalues(g, g->weak, origweak); ++ clearbyvalues(g, g->allweak, origall); ++ luaS_clearcache(g); ++ g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */ ++ lua_assert(g->gray == NULL); ++ return work; /* estimate of slots marked by 'atomic' */ ++} ++ ++ ++static int sweepstep (lua_State *L, global_State *g, ++ int nextstate, GCObject **nextlist) { ++ if (g->sweepgc) { ++ l_mem olddebt = g->GCdebt; ++ int count; ++ g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX, &count); ++ g->GCestimate += g->GCdebt - olddebt; /* update estimate */ ++ return count; ++ } ++ else { /* enter next state */ ++ g->gcstate = nextstate; ++ g->sweepgc = nextlist; ++ return 0; /* no work done */ ++ } ++} ++ ++ ++static lu_mem singlestep (lua_State *L) { ++ global_State *g = G(L); ++ lu_mem work; ++ lua_assert(!g->gcstopem); /* collector is not reentrant */ ++ g->gcstopem = 1; /* no emergency collections while collecting */ ++ switch (g->gcstate) { ++ case GCSpause: { ++ restartcollection(g); ++ g->gcstate = GCSpropagate; ++ work = 1; ++ break; ++ } ++ case GCSpropagate: { ++ if (g->gray == NULL) { /* no more gray objects? */ ++ g->gcstate = GCSenteratomic; /* finish propagate phase */ ++ work = 0; ++ } ++ else ++ work = propagatemark(g); /* traverse one gray object */ ++ break; ++ } ++ case GCSenteratomic: { ++ work = atomic(L); /* work is what was traversed by 'atomic' */ ++ entersweep(L); ++ g->GCestimate = gettotalbytes(g); /* first estimate */; ++ break; ++ } ++ case GCSswpallgc: { /* sweep "regular" objects */ ++ work = sweepstep(L, g, GCSswpfinobj, &g->finobj); ++ break; ++ } ++ case GCSswpfinobj: { /* sweep objects with finalizers */ ++ work = sweepstep(L, g, GCSswptobefnz, &g->tobefnz); ++ break; ++ } ++ case GCSswptobefnz: { /* sweep objects to be finalized */ ++ work = sweepstep(L, g, GCSswpend, NULL); ++ break; ++ } ++ case GCSswpend: { /* finish sweeps */ ++ checkSizes(L, g); ++ g->gcstate = GCScallfin; ++ work = 0; ++ break; ++ } ++ case GCScallfin: { /* call remaining finalizers */ ++ if (g->tobefnz && !g->gcemergency) { ++ g->gcstopem = 0; /* ok collections during finalizers */ ++ work = runafewfinalizers(L, GCFINMAX) * GCFINALIZECOST; ++ } ++ else { /* emergency mode or no more finalizers */ ++ g->gcstate = GCSpause; /* finish collection */ ++ work = 0; ++ } ++ break; ++ } ++ default: lua_assert(0); return 0; ++ } ++ g->gcstopem = 0; ++ return work; ++} ++ ++ ++/* ++** advances the garbage collector until it reaches a state allowed ++** by 'statemask' ++*/ ++void luaC_runtilstate (lua_State *L, int statesmask) { ++ global_State *g = G(L); ++ while (!testbit(statesmask, g->gcstate)) ++ singlestep(L); ++} ++ ++ ++/* ++** Performs a basic incremental step. The debt and step size are ++** converted from bytes to "units of work"; then the function loops ++** running single steps until adding that many units of work or ++** finishing a cycle (pause state). Finally, it sets the debt that ++** controls when next step will be performed. ++*/ ++static void incstep (lua_State *L, global_State *g) { ++ int stepmul = (getgcparam(g->gcstepmul) | 1); /* avoid division by 0 */ ++ l_mem debt = (g->GCdebt / WORK2MEM) * stepmul; ++ l_mem stepsize = (g->gcstepsize <= log2maxs(l_mem)) ++ ? ((cast(l_mem, 1) << g->gcstepsize) / WORK2MEM) * stepmul ++ : MAX_LMEM; /* overflow; keep maximum value */ ++ do { /* repeat until pause or enough "credit" (negative debt) */ ++ lu_mem work = singlestep(L); /* perform one single step */ ++ debt -= work; ++ } while (debt > -stepsize && g->gcstate != GCSpause); ++ if (g->gcstate == GCSpause) ++ setpause(g); /* pause until next cycle */ ++ else { ++ debt = (debt / stepmul) * WORK2MEM; /* convert 'work units' to bytes */ ++ luaE_setdebt(g, debt); ++ } ++} ++ ++/* ++** performs a basic GC step if collector is running ++*/ ++void luaC_step (lua_State *L) { ++ global_State *g = G(L); ++ lua_assert(!g->gcemergency); ++ if (g->gcrunning) { /* running? */ ++ if(isdecGCmodegen(g)) ++ genstep(L, g); ++ else ++ incstep(L, g); ++ } ++} ++ ++ ++/* ++** Perform a full collection in incremental mode. ++** Before running the collection, check 'keepinvariant'; if it is true, ++** there may be some objects marked as black, so the collector has ++** to sweep all objects to turn them back to white (as white has not ++** changed, nothing will be collected). ++*/ ++static void fullinc (lua_State *L, global_State *g) { ++ if (keepinvariant(g)) /* black objects? */ ++ entersweep(L); /* sweep everything to turn them back to white */ ++ /* finish any pending sweep phase to start a new cycle */ ++ luaC_runtilstate(L, bitmask(GCSpause)); ++ luaC_runtilstate(L, bitmask(GCScallfin)); /* run up to finalizers */ ++ /* estimate must be correct after a full GC cycle */ ++ lua_assert(g->GCestimate == gettotalbytes(g)); ++ luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */ ++ setpause(g); ++} ++ ++ ++/* ++** Performs a full GC cycle; if 'isemergency', set a flag to avoid ++** some operations which could change the interpreter state in some ++** unexpected ways (running finalizers and shrinking some structures). ++*/ ++void luaC_fullgc (lua_State *L, int isemergency) { ++ global_State *g = G(L); ++ lua_assert(!g->gcemergency); ++ g->gcemergency = isemergency; /* set flag */ ++ if (g->gckind == KGC_INC) ++ fullinc(L, g); ++ else ++ fullgen(L, g); ++ g->gcemergency = 0; ++} ++ ++/* }====================================================== */ ++ ++ +diff --git a/src/bin/lua/lgc.h b/src/bin/lua/lgc.h +new file mode 100644 +index 0000000000..073e2a4029 +--- /dev/null ++++ b/src/bin/lua/lgc.h +@@ -0,0 +1,189 @@ ++/* ++** $Id: lgc.h $ ++** Garbage Collector ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef lgc_h ++#define lgc_h ++ ++ ++#include "lobject.h" ++#include "lstate.h" ++ ++/* ++** Collectable objects may have one of three colors: white, which means ++** the object is not marked; gray, which means the object is marked, but ++** its references may be not marked; and black, which means that the ++** object and all its references are marked. The main invariant of the ++** garbage collector, while marking objects, is that a black object can ++** never point to a white one. Moreover, any gray object must be in a ++** "gray list" (gray, grayagain, weak, allweak, ephemeron) so that it ++** can be visited again before finishing the collection cycle. (Open ++** upvalues are an exception to this rule.) These lists have no meaning ++** when the invariant is not being enforced (e.g., sweep phase). ++*/ ++ ++ ++/* ++** Possible states of the Garbage Collector ++*/ ++#define GCSpropagate 0 ++#define GCSenteratomic 1 ++#define GCSatomic 2 ++#define GCSswpallgc 3 ++#define GCSswpfinobj 4 ++#define GCSswptobefnz 5 ++#define GCSswpend 6 ++#define GCScallfin 7 ++#define GCSpause 8 ++ ++ ++#define issweepphase(g) \ ++ (GCSswpallgc <= (g)->gcstate && (g)->gcstate <= GCSswpend) ++ ++ ++/* ++** macro to tell when main invariant (white objects cannot point to black ++** ones) must be kept. During a collection, the sweep ++** phase may break the invariant, as objects turned white may point to ++** still-black objects. The invariant is restored when sweep ends and ++** all objects are white again. ++*/ ++ ++#define keepinvariant(g) ((g)->gcstate <= GCSatomic) ++ ++ ++/* ++** some useful bit tricks ++*/ ++#define resetbits(x,m) ((x) &= cast_byte(~(m))) ++#define setbits(x,m) ((x) |= (m)) ++#define testbits(x,m) ((x) & (m)) ++#define bitmask(b) (1<<(b)) ++#define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2)) ++#define l_setbit(x,b) setbits(x, bitmask(b)) ++#define resetbit(x,b) resetbits(x, bitmask(b)) ++#define testbit(x,b) testbits(x, bitmask(b)) ++ ++ ++/* ++** Layout for bit use in 'marked' field. First three bits are ++** used for object "age" in generational mode. Last bit is used ++** by tests. ++*/ ++#define WHITE0BIT 3 /* object is white (type 0) */ ++#define WHITE1BIT 4 /* object is white (type 1) */ ++#define BLACKBIT 5 /* object is black */ ++#define FINALIZEDBIT 6 /* object has been marked for finalization */ ++ ++#define TESTBIT 7 ++ ++ ++ ++#define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT) ++ ++ ++#define iswhite(x) testbits((x)->marked, WHITEBITS) ++#define isblack(x) testbit((x)->marked, BLACKBIT) ++#define isgray(x) /* neither white nor black */ \ ++ (!testbits((x)->marked, WHITEBITS | bitmask(BLACKBIT))) ++ ++#define tofinalize(x) testbit((x)->marked, FINALIZEDBIT) ++ ++#define otherwhite(g) ((g)->currentwhite ^ WHITEBITS) ++#define isdeadm(ow,m) ((m) & (ow)) ++#define isdead(g,v) isdeadm(otherwhite(g), (v)->marked) ++ ++#define changewhite(x) ((x)->marked ^= WHITEBITS) ++#define nw2black(x) \ ++ check_exp(!iswhite(x), l_setbit((x)->marked, BLACKBIT)) ++ ++#define luaC_white(g) cast_byte((g)->currentwhite & WHITEBITS) ++ ++ ++/* object age in generational mode */ ++#define G_NEW 0 /* created in current cycle */ ++#define G_SURVIVAL 1 /* created in previous cycle */ ++#define G_OLD0 2 /* marked old by frw. barrier in this cycle */ ++#define G_OLD1 3 /* first full cycle as old */ ++#define G_OLD 4 /* really old object (not to be visited) */ ++#define G_TOUCHED1 5 /* old object touched this cycle */ ++#define G_TOUCHED2 6 /* old object touched in previous cycle */ ++ ++#define AGEBITS 7 /* all age bits (111) */ ++ ++#define getage(o) ((o)->marked & AGEBITS) ++#define setage(o,a) ((o)->marked = cast_byte(((o)->marked & (~AGEBITS)) | a)) ++#define isold(o) (getage(o) > G_SURVIVAL) ++ ++#define changeage(o,f,t) \ ++ check_exp(getage(o) == (f), (o)->marked ^= ((f)^(t))) ++ ++ ++/* Default Values for GC parameters */ ++#define LUAI_GENMAJORMUL 100 ++#define LUAI_GENMINORMUL 20 ++ ++/* wait memory to double before starting new cycle */ ++#define LUAI_GCPAUSE 200 ++ ++/* ++** some gc parameters are stored divided by 4 to allow a maximum value ++** up to 1023 in a 'lu_byte'. ++*/ ++#define getgcparam(p) ((p) * 4) ++#define setgcparam(p,v) ((p) = (v) / 4) ++ ++#define LUAI_GCMUL 100 ++ ++/* how much to allocate before next GC step (log2) */ ++#define LUAI_GCSTEPSIZE 13 /* 8 KB */ ++ ++ ++/* ++** Check whether the declared GC mode is generational. While in ++** generational mode, the collector can go temporarily to incremental ++** mode to improve performance. This is signaled by 'g->lastatomic != 0'. ++*/ ++#define isdecGCmodegen(g) (g->gckind == KGC_GEN || g->lastatomic != 0) ++ ++/* ++** Does one step of collection when debt becomes positive. 'pre'/'pos' ++** allows some adjustments to be done only when needed. macro ++** 'condchangemem' is used only for heavy tests (forcing a full ++** GC cycle on every opportunity) ++*/ ++#define luaC_condGC(L,pre,pos) \ ++ { if (G(L)->GCdebt > 0) { pre; luaC_step(L); pos;}; \ ++ condchangemem(L,pre,pos); } ++ ++/* more often than not, 'pre'/'pos' are empty */ ++#define luaC_checkGC(L) luaC_condGC(L,(void)0,(void)0) ++ ++ ++#define luaC_barrier(L,p,v) ( \ ++ (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) ? \ ++ luaC_barrier_(L,obj2gco(p),gcvalue(v)) : cast_void(0)) ++ ++#define luaC_barrierback(L,p,v) ( \ ++ (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) ? \ ++ luaC_barrierback_(L,p) : cast_void(0)) ++ ++#define luaC_objbarrier(L,p,o) ( \ ++ (isblack(p) && iswhite(o)) ? \ ++ luaC_barrier_(L,obj2gco(p),obj2gco(o)) : cast_void(0)) ++ ++LUAI_FUNC void luaC_fix (lua_State *L, GCObject *o); ++LUAI_FUNC void luaC_freeallobjects (lua_State *L); ++LUAI_FUNC void luaC_step (lua_State *L); ++LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask); ++LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency); ++LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz); ++LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v); ++LUAI_FUNC void luaC_barrierback_ (lua_State *L, GCObject *o); ++LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt); ++LUAI_FUNC void luaC_changemode (lua_State *L, int newmode); ++ ++ ++#endif +diff --git a/src/bin/lua/linit.c b/src/bin/lua/linit.c +new file mode 100644 +index 0000000000..69808f84f4 +--- /dev/null ++++ b/src/bin/lua/linit.c +@@ -0,0 +1,65 @@ ++/* ++** $Id: linit.c $ ++** Initialization of libraries for lua.c and other clients ++** See Copyright Notice in lua.h ++*/ ++ ++ ++#define linit_c ++#define LUA_LIB ++ ++/* ++** If you embed Lua in your program and need to open the standard ++** libraries, call luaL_openlibs in your program. If you need a ++** different set of libraries, copy this file to your project and edit ++** it to suit your needs. ++** ++** You can also *preload* libraries, so that a later 'require' can ++** open the library, which is already linked to the application. ++** For that, do the following code: ++** ++** luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); ++** lua_pushcfunction(L, luaopen_modname); ++** lua_setfield(L, -2, modname); ++** lua_pop(L, 1); // remove PRELOAD table ++*/ ++ ++#include "lprefix.h" ++ ++ ++#include ++ ++#include "lua.h" ++ ++#include "lualib.h" ++#include "lauxlib.h" ++ ++ ++/* ++** these libs are loaded by lua.c and are readily available to any Lua ++** program ++*/ ++static const luaL_Reg loadedlibs[] = { ++ {LUA_GNAME, luaopen_base}, ++ {LUA_LOADLIBNAME, luaopen_package}, ++ {LUA_COLIBNAME, luaopen_coroutine}, ++ {LUA_TABLIBNAME, luaopen_table}, ++ {LUA_IOLIBNAME, luaopen_io}, ++ {LUA_OSLIBNAME, luaopen_os}, ++ {LUA_STRLIBNAME, luaopen_string}, ++ {LUA_MATHLIBNAME, luaopen_math}, ++ {LUA_UTF8LIBNAME, luaopen_utf8}, ++ {LUA_DBLIBNAME, luaopen_debug}, ++ {NULL, NULL} ++}; ++ ++ ++LUALIB_API void luaL_openlibs (lua_State *L) { ++ const luaL_Reg *lib; ++ /* "require" functions from 'loadedlibs' and set results to global table */ ++ for (lib = loadedlibs; lib->func; lib++) { ++ luaL_requiref(L, lib->name, lib->func, 1); ++ lua_pop(L, 1); /* remove lib */ ++ } ++} ++ +diff --git a/src/bin/lua/liolib.c b/src/bin/lua/liolib.c +new file mode 100644 +index 0000000000..b08397da45 +--- /dev/null ++++ b/src/bin/lua/liolib.c +@@ -0,0 +1,828 @@ ++/* ++** $Id: liolib.c $ ++** Standard I/O (and system) library ++** See Copyright Notice in lua.h ++*/ ++ ++#define liolib_c ++#define LUA_LIB ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "lua.h" ++ ++#include "lauxlib.h" ++#include "lualib.h" ++ ++ ++ ++ ++/* ++** Change this macro to accept other modes for 'fopen' besides ++** the standard ones. ++*/ ++#if !defined(l_checkmode) ++ ++/* accepted extensions to 'mode' in 'fopen' */ ++#if !defined(L_MODEEXT) ++#define L_MODEEXT "b" ++#endif ++ ++/* Check whether 'mode' matches '[rwa]%+?[L_MODEEXT]*' */ ++static int l_checkmode (const char *mode) { ++ return (*mode != '\0' && strchr("rwa", *(mode++)) != NULL && ++ (*mode != '+' || ((void)(++mode), 1)) && /* skip if char is '+' */ ++ (strspn(mode, L_MODEEXT) == strlen(mode))); /* check extensions */ ++} ++ ++#endif ++ ++/* ++** {====================================================== ++** l_popen spawns a new process connected to the current ++** one through the file streams. ++** ======================================================= ++*/ ++ ++#if !defined(l_popen) /* { */ ++ ++#if defined(LUA_USE_POSIX) /* { */ ++ ++#define l_popen(L,c,m) (fflush(NULL), popen(c,m)) ++#define l_pclose(L,file) (pclose(file)) ++ ++#elif defined(LUA_USE_WINDOWS) /* }{ */ ++ ++#define l_popen(L,c,m) (_popen(c,m)) ++#define l_pclose(L,file) (_pclose(file)) ++ ++#if !defined(l_checkmodep) ++/* Windows accepts "[rw][bt]?" as valid modes */ ++#define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && \ ++ (m[1] == '\0' || ((m[1] == 'b' || m[1] == 't') && m[2] == '\0'))) ++#endif ++ ++#else /* }{ */ ++ ++/* ISO C definitions */ ++#define l_popen(L,c,m) \ ++ ((void)c, (void)m, \ ++ luaL_error(L, "'popen' not supported"), \ ++ (FILE*)0) ++#define l_pclose(L,file) ((void)L, (void)file, -1) ++ ++#endif /* } */ ++ ++#endif /* } */ ++ ++ ++#if !defined(l_checkmodep) ++/* By default, Lua accepts only "r" or "w" as valid modes */ ++#define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && m[1] == '\0') ++#endif ++ ++/* }====================================================== */ ++ ++ ++#if !defined(l_getc) /* { */ ++ ++#if defined(LUA_USE_POSIX) ++#define l_getc(f) getc_unlocked(f) ++#define l_lockfile(f) flockfile(f) ++#define l_unlockfile(f) funlockfile(f) ++#else ++#define l_getc(f) getc(f) ++#define l_lockfile(f) ((void)0) ++#define l_unlockfile(f) ((void)0) ++#endif ++ ++#endif /* } */ ++ ++ ++/* ++** {====================================================== ++** l_fseek: configuration for longer offsets ++** ======================================================= ++*/ ++ ++#if !defined(l_fseek) /* { */ ++ ++#if defined(LUA_USE_POSIX) /* { */ ++ ++#include ++ ++#define l_fseek(f,o,w) fseeko(f,o,w) ++#define l_ftell(f) ftello(f) ++#define l_seeknum off_t ++ ++#elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \ ++ && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */ ++ ++/* Windows (but not DDK) and Visual C++ 2005 or higher */ ++#define l_fseek(f,o,w) _fseeki64(f,o,w) ++#define l_ftell(f) _ftelli64(f) ++#define l_seeknum __int64 ++ ++#else /* }{ */ ++ ++/* ISO C definitions */ ++#define l_fseek(f,o,w) fseek(f,o,w) ++#define l_ftell(f) ftell(f) ++#define l_seeknum long ++ ++#endif /* } */ ++ ++#endif /* } */ ++ ++/* }====================================================== */ ++ ++ ++ ++#define IO_PREFIX "_IO_" ++#define IOPREF_LEN (sizeof(IO_PREFIX)/sizeof(char) - 1) ++#define IO_INPUT (IO_PREFIX "input") ++#define IO_OUTPUT (IO_PREFIX "output") ++ ++ ++typedef luaL_Stream LStream; ++ ++ ++#define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE)) ++ ++#define isclosed(p) ((p)->closef == NULL) ++ ++ ++static int io_type (lua_State *L) { ++ LStream *p; ++ luaL_checkany(L, 1); ++ p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE); ++ if (p == NULL) ++ luaL_pushfail(L); /* not a file */ ++ else if (isclosed(p)) ++ lua_pushliteral(L, "closed file"); ++ else ++ lua_pushliteral(L, "file"); ++ return 1; ++} ++ ++ ++static int f_tostring (lua_State *L) { ++ LStream *p = tolstream(L); ++ if (isclosed(p)) ++ lua_pushliteral(L, "file (closed)"); ++ else ++ lua_pushfstring(L, "file (%p)", p->f); ++ return 1; ++} ++ ++ ++static FILE *tofile (lua_State *L) { ++ LStream *p = tolstream(L); ++ if (l_unlikely(isclosed(p))) ++ luaL_error(L, "attempt to use a closed file"); ++ lua_assert(p->f); ++ return p->f; ++} ++ ++ ++/* ++** When creating file handles, always creates a 'closed' file handle ++** before opening the actual file; so, if there is a memory error, the ++** handle is in a consistent state. ++*/ ++static LStream *newprefile (lua_State *L) { ++ LStream *p = (LStream *)lua_newuserdatauv(L, sizeof(LStream), 0); ++ p->closef = NULL; /* mark file handle as 'closed' */ ++ luaL_setmetatable(L, LUA_FILEHANDLE); ++ return p; ++} ++ ++ ++/* ++** Calls the 'close' function from a file handle. The 'volatile' avoids ++** a bug in some versions of the Clang compiler (e.g., clang 3.0 for ++** 32 bits). ++*/ ++static int aux_close (lua_State *L) { ++ LStream *p = tolstream(L); ++ volatile lua_CFunction cf = p->closef; ++ p->closef = NULL; /* mark stream as closed */ ++ return (*cf)(L); /* close it */ ++} ++ ++ ++static int f_close (lua_State *L) { ++ tofile(L); /* make sure argument is an open stream */ ++ return aux_close(L); ++} ++ ++ ++static int io_close (lua_State *L) { ++ if (lua_isnone(L, 1)) /* no argument? */ ++ lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use default output */ ++ return f_close(L); ++} ++ ++ ++static int f_gc (lua_State *L) { ++ LStream *p = tolstream(L); ++ if (!isclosed(p) && p->f != NULL) ++ aux_close(L); /* ignore closed and incompletely open files */ ++ return 0; ++} ++ ++ ++/* ++** function to close regular files ++*/ ++static int io_fclose (lua_State *L) { ++ LStream *p = tolstream(L); ++ int res = fclose(p->f); ++ return luaL_fileresult(L, (res == 0), NULL); ++} ++ ++ ++static LStream *newfile (lua_State *L) { ++ LStream *p = newprefile(L); ++ p->f = NULL; ++ p->closef = &io_fclose; ++ return p; ++} ++ ++ ++static void opencheck (lua_State *L, const char *fname, const char *mode) { ++ LStream *p = newfile(L); ++ p->f = fopen(fname, mode); ++ if (l_unlikely(p->f == NULL)) ++ luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno)); ++} ++ ++ ++static int io_open (lua_State *L) { ++ const char *filename = luaL_checkstring(L, 1); ++ const char *mode = luaL_optstring(L, 2, "r"); ++ LStream *p = newfile(L); ++ const char *md = mode; /* to traverse/check mode */ ++ luaL_argcheck(L, l_checkmode(md), 2, "invalid mode"); ++ p->f = fopen(filename, mode); ++ return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1; ++} ++ ++ ++/* ++** function to close 'popen' files ++*/ ++static int io_pclose (lua_State *L) { ++ LStream *p = tolstream(L); ++ errno = 0; ++ return luaL_execresult(L, l_pclose(L, p->f)); ++} ++ ++ ++static int io_popen (lua_State *L) { ++ const char *filename = luaL_checkstring(L, 1); ++ const char *mode = luaL_optstring(L, 2, "r"); ++ LStream *p = newprefile(L); ++ luaL_argcheck(L, l_checkmodep(mode), 2, "invalid mode"); ++ p->f = l_popen(L, filename, mode); ++ p->closef = &io_pclose; ++ return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1; ++} ++ ++ ++static int io_tmpfile (lua_State *L) { ++ LStream *p = newfile(L); ++ p->f = tmpfile(); ++ return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1; ++} ++ ++ ++static FILE *getiofile (lua_State *L, const char *findex) { ++ LStream *p; ++ lua_getfield(L, LUA_REGISTRYINDEX, findex); ++ p = (LStream *)lua_touserdata(L, -1); ++ if (l_unlikely(isclosed(p))) ++ luaL_error(L, "default %s file is closed", findex + IOPREF_LEN); ++ return p->f; ++} ++ ++ ++static int g_iofile (lua_State *L, const char *f, const char *mode) { ++ if (!lua_isnoneornil(L, 1)) { ++ const char *filename = lua_tostring(L, 1); ++ if (filename) ++ opencheck(L, filename, mode); ++ else { ++ tofile(L); /* check that it's a valid file handle */ ++ lua_pushvalue(L, 1); ++ } ++ lua_setfield(L, LUA_REGISTRYINDEX, f); ++ } ++ /* return current value */ ++ lua_getfield(L, LUA_REGISTRYINDEX, f); ++ return 1; ++} ++ ++ ++static int io_input (lua_State *L) { ++ return g_iofile(L, IO_INPUT, "r"); ++} ++ ++ ++static int io_output (lua_State *L) { ++ return g_iofile(L, IO_OUTPUT, "w"); ++} ++ ++ ++static int io_readline (lua_State *L); ++ ++ ++/* ++** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit ++** in the limit for upvalues of a closure) ++*/ ++#define MAXARGLINE 250 ++ ++/* ++** Auxiliary function to create the iteration function for 'lines'. ++** The iteration function is a closure over 'io_readline', with ++** the following upvalues: ++** 1) The file being read (first value in the stack) ++** 2) the number of arguments to read ++** 3) a boolean, true iff file has to be closed when finished ('toclose') ++** *) a variable number of format arguments (rest of the stack) ++*/ ++static void aux_lines (lua_State *L, int toclose) { ++ int n = lua_gettop(L) - 1; /* number of arguments to read */ ++ luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, "too many arguments"); ++ lua_pushvalue(L, 1); /* file */ ++ lua_pushinteger(L, n); /* number of arguments to read */ ++ lua_pushboolean(L, toclose); /* close/not close file when finished */ ++ lua_rotate(L, 2, 3); /* move the three values to their positions */ ++ lua_pushcclosure(L, io_readline, 3 + n); ++} ++ ++ ++static int f_lines (lua_State *L) { ++ tofile(L); /* check that it's a valid file handle */ ++ aux_lines(L, 0); ++ return 1; ++} ++ ++ ++/* ++** Return an iteration function for 'io.lines'. If file has to be ++** closed, also returns the file itself as a second result (to be ++** closed as the state at the exit of a generic for). ++*/ ++static int io_lines (lua_State *L) { ++ int toclose; ++ if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */ ++ if (lua_isnil(L, 1)) { /* no file name? */ ++ lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */ ++ lua_replace(L, 1); /* put it at index 1 */ ++ tofile(L); /* check that it's a valid file handle */ ++ toclose = 0; /* do not close it after iteration */ ++ } ++ else { /* open a new file */ ++ const char *filename = luaL_checkstring(L, 1); ++ opencheck(L, filename, "r"); ++ lua_replace(L, 1); /* put file at index 1 */ ++ toclose = 1; /* close it after iteration */ ++ } ++ aux_lines(L, toclose); /* push iteration function */ ++ if (toclose) { ++ lua_pushnil(L); /* state */ ++ lua_pushnil(L); /* control */ ++ lua_pushvalue(L, 1); /* file is the to-be-closed variable (4th result) */ ++ return 4; ++ } ++ else ++ return 1; ++} ++ ++ ++/* ++** {====================================================== ++** READ ++** ======================================================= ++*/ ++ ++ ++/* maximum length of a numeral */ ++#if !defined (L_MAXLENNUM) ++#define L_MAXLENNUM 200 ++#endif ++ ++ ++/* auxiliary structure used by 'read_number' */ ++typedef struct { ++ FILE *f; /* file being read */ ++ int c; /* current character (look ahead) */ ++ int n; /* number of elements in buffer 'buff' */ ++ char buff[L_MAXLENNUM + 1]; /* +1 for ending '\0' */ ++} RN; ++ ++ ++/* ++** Add current char to buffer (if not out of space) and read next one ++*/ ++static int nextc (RN *rn) { ++ if (l_unlikely(rn->n >= L_MAXLENNUM)) { /* buffer overflow? */ ++ rn->buff[0] = '\0'; /* invalidate result */ ++ return 0; /* fail */ ++ } ++ else { ++ rn->buff[rn->n++] = rn->c; /* save current char */ ++ rn->c = l_getc(rn->f); /* read next one */ ++ return 1; ++ } ++} ++ ++ ++/* ++** Accept current char if it is in 'set' (of size 2) ++*/ ++static int test2 (RN *rn, const char *set) { ++ if (rn->c == set[0] || rn->c == set[1]) ++ return nextc(rn); ++ else return 0; ++} ++ ++ ++/* ++** Read a sequence of (hex)digits ++*/ ++static int readdigits (RN *rn, int hex) { ++ int count = 0; ++ while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn)) ++ count++; ++ return count; ++} ++ ++ ++/* ++** Read a number: first reads a valid prefix of a numeral into a buffer. ++** Then it calls 'lua_stringtonumber' to check whether the format is ++** correct and to convert it to a Lua number. ++*/ ++static int read_number (lua_State *L, FILE *f) { ++ RN rn; ++ int count = 0; ++ int hex = 0; ++ char decp[2]; ++ rn.f = f; rn.n = 0; ++ decp[0] = lua_getlocaledecpoint(); /* get decimal point from locale */ ++ decp[1] = '.'; /* always accept a dot */ ++ l_lockfile(rn.f); ++ do { rn.c = l_getc(rn.f); } while (isspace(rn.c)); /* skip spaces */ ++ test2(&rn, "-+"); /* optional sign */ ++ if (test2(&rn, "00")) { ++ if (test2(&rn, "xX")) hex = 1; /* numeral is hexadecimal */ ++ else count = 1; /* count initial '0' as a valid digit */ ++ } ++ count += readdigits(&rn, hex); /* integral part */ ++ if (test2(&rn, decp)) /* decimal point? */ ++ count += readdigits(&rn, hex); /* fractional part */ ++ if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) { /* exponent mark? */ ++ test2(&rn, "-+"); /* exponent sign */ ++ readdigits(&rn, 0); /* exponent digits */ ++ } ++ ungetc(rn.c, rn.f); /* unread look-ahead char */ ++ l_unlockfile(rn.f); ++ rn.buff[rn.n] = '\0'; /* finish string */ ++ if (l_likely(lua_stringtonumber(L, rn.buff))) ++ return 1; /* ok, it is a valid number */ ++ else { /* invalid format */ ++ lua_pushnil(L); /* "result" to be removed */ ++ return 0; /* read fails */ ++ } ++} ++ ++ ++static int test_eof (lua_State *L, FILE *f) { ++ int c = getc(f); ++ ungetc(c, f); /* no-op when c == EOF */ ++ lua_pushliteral(L, ""); ++ return (c != EOF); ++} ++ ++ ++static int read_line (lua_State *L, FILE *f, int chop) { ++ luaL_Buffer b; ++ int c; ++ luaL_buffinit(L, &b); ++ do { /* may need to read several chunks to get whole line */ ++ char *buff = luaL_prepbuffer(&b); /* preallocate buffer space */ ++ int i = 0; ++ l_lockfile(f); /* no memory errors can happen inside the lock */ ++ while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n') ++ buff[i++] = c; /* read up to end of line or buffer limit */ ++ l_unlockfile(f); ++ luaL_addsize(&b, i); ++ } while (c != EOF && c != '\n'); /* repeat until end of line */ ++ if (!chop && c == '\n') /* want a newline and have one? */ ++ luaL_addchar(&b, c); /* add ending newline to result */ ++ luaL_pushresult(&b); /* close buffer */ ++ /* return ok if read something (either a newline or something else) */ ++ return (c == '\n' || lua_rawlen(L, -1) > 0); ++} ++ ++ ++static void read_all (lua_State *L, FILE *f) { ++ size_t nr; ++ luaL_Buffer b; ++ luaL_buffinit(L, &b); ++ do { /* read file in chunks of LUAL_BUFFERSIZE bytes */ ++ char *p = luaL_prepbuffer(&b); ++ nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f); ++ luaL_addsize(&b, nr); ++ } while (nr == LUAL_BUFFERSIZE); ++ luaL_pushresult(&b); /* close buffer */ ++} ++ ++ ++static int read_chars (lua_State *L, FILE *f, size_t n) { ++ size_t nr; /* number of chars actually read */ ++ char *p; ++ luaL_Buffer b; ++ luaL_buffinit(L, &b); ++ p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */ ++ nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */ ++ luaL_addsize(&b, nr); ++ luaL_pushresult(&b); /* close buffer */ ++ return (nr > 0); /* true iff read something */ ++} ++ ++ ++static int g_read (lua_State *L, FILE *f, int first) { ++ int nargs = lua_gettop(L) - 1; ++ int n, success; ++ clearerr(f); ++ if (nargs == 0) { /* no arguments? */ ++ success = read_line(L, f, 1); ++ n = first + 1; /* to return 1 result */ ++ } ++ else { ++ /* ensure stack space for all results and for auxlib's buffer */ ++ luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments"); ++ success = 1; ++ for (n = first; nargs-- && success; n++) { ++ if (lua_type(L, n) == LUA_TNUMBER) { ++ size_t l = (size_t)luaL_checkinteger(L, n); ++ success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l); ++ } ++ else { ++ const char *p = luaL_checkstring(L, n); ++ if (*p == '*') p++; /* skip optional '*' (for compatibility) */ ++ switch (*p) { ++ case 'n': /* number */ ++ success = read_number(L, f); ++ break; ++ case 'l': /* line */ ++ success = read_line(L, f, 1); ++ break; ++ case 'L': /* line with end-of-line */ ++ success = read_line(L, f, 0); ++ break; ++ case 'a': /* file */ ++ read_all(L, f); /* read entire file */ ++ success = 1; /* always success */ ++ break; ++ default: ++ return luaL_argerror(L, n, "invalid format"); ++ } ++ } ++ } ++ } ++ if (ferror(f)) ++ return luaL_fileresult(L, 0, NULL); ++ if (!success) { ++ lua_pop(L, 1); /* remove last result */ ++ luaL_pushfail(L); /* push nil instead */ ++ } ++ return n - first; ++} ++ ++ ++static int io_read (lua_State *L) { ++ return g_read(L, getiofile(L, IO_INPUT), 1); ++} ++ ++ ++static int f_read (lua_State *L) { ++ return g_read(L, tofile(L), 2); ++} ++ ++ ++/* ++** Iteration function for 'lines'. ++*/ ++static int io_readline (lua_State *L) { ++ LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1)); ++ int i; ++ int n = (int)lua_tointeger(L, lua_upvalueindex(2)); ++ if (isclosed(p)) /* file is already closed? */ ++ return luaL_error(L, "file is already closed"); ++ lua_settop(L , 1); ++ luaL_checkstack(L, n, "too many arguments"); ++ for (i = 1; i <= n; i++) /* push arguments to 'g_read' */ ++ lua_pushvalue(L, lua_upvalueindex(3 + i)); ++ n = g_read(L, p->f, 2); /* 'n' is number of results */ ++ lua_assert(n > 0); /* should return at least a nil */ ++ if (lua_toboolean(L, -n)) /* read at least one value? */ ++ return n; /* return them */ ++ else { /* first result is false: EOF or error */ ++ if (n > 1) { /* is there error information? */ ++ /* 2nd result is error message */ ++ return luaL_error(L, "%s", lua_tostring(L, -n + 1)); ++ } ++ if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */ ++ lua_settop(L, 0); /* clear stack */ ++ lua_pushvalue(L, lua_upvalueindex(1)); /* push file at index 1 */ ++ aux_close(L); /* close it */ ++ } ++ return 0; ++ } ++} ++ ++/* }====================================================== */ ++ ++ ++static int g_write (lua_State *L, FILE *f, int arg) { ++ int nargs = lua_gettop(L) - arg; ++ int status = 1; ++ for (; nargs--; arg++) { ++ if (lua_type(L, arg) == LUA_TNUMBER) { ++ /* optimization: could be done exactly as for strings */ ++ int len = lua_isinteger(L, arg) ++ ? fprintf(f, LUA_INTEGER_FMT, ++ (LUAI_UACINT)lua_tointeger(L, arg)) ++ : fprintf(f, LUA_NUMBER_FMT, ++ (LUAI_UACNUMBER)lua_tonumber(L, arg)); ++ status = status && (len > 0); ++ } ++ else { ++ size_t l; ++ const char *s = luaL_checklstring(L, arg, &l); ++ status = status && (fwrite(s, sizeof(char), l, f) == l); ++ } ++ } ++ if (l_likely(status)) ++ return 1; /* file handle already on stack top */ ++ else return luaL_fileresult(L, status, NULL); ++} ++ ++ ++static int io_write (lua_State *L) { ++ return g_write(L, getiofile(L, IO_OUTPUT), 1); ++} ++ ++ ++static int f_write (lua_State *L) { ++ FILE *f = tofile(L); ++ lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */ ++ return g_write(L, f, 2); ++} ++ ++ ++static int f_seek (lua_State *L) { ++ static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END}; ++ static const char *const modenames[] = {"set", "cur", "end", NULL}; ++ FILE *f = tofile(L); ++ int op = luaL_checkoption(L, 2, "cur", modenames); ++ lua_Integer p3 = luaL_optinteger(L, 3, 0); ++ l_seeknum offset = (l_seeknum)p3; ++ luaL_argcheck(L, (lua_Integer)offset == p3, 3, ++ "not an integer in proper range"); ++ op = l_fseek(f, offset, mode[op]); ++ if (l_unlikely(op)) ++ return luaL_fileresult(L, 0, NULL); /* error */ ++ else { ++ lua_pushinteger(L, (lua_Integer)l_ftell(f)); ++ return 1; ++ } ++} ++ ++ ++static int f_setvbuf (lua_State *L) { ++ static const int mode[] = {_IONBF, _IOFBF, _IOLBF}; ++ static const char *const modenames[] = {"no", "full", "line", NULL}; ++ FILE *f = tofile(L); ++ int op = luaL_checkoption(L, 2, NULL, modenames); ++ lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE); ++ int res = setvbuf(f, NULL, mode[op], (size_t)sz); ++ return luaL_fileresult(L, res == 0, NULL); ++} ++ ++ ++ ++static int io_flush (lua_State *L) { ++ return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL); ++} ++ ++ ++static int f_flush (lua_State *L) { ++ return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL); ++} ++ ++ ++/* ++** functions for 'io' library ++*/ ++static const luaL_Reg iolib[] = { ++ {"close", io_close}, ++ {"flush", io_flush}, ++ {"input", io_input}, ++ {"lines", io_lines}, ++ {"open", io_open}, ++ {"output", io_output}, ++ {"popen", io_popen}, ++ {"read", io_read}, ++ {"tmpfile", io_tmpfile}, ++ {"type", io_type}, ++ {"write", io_write}, ++ {NULL, NULL} ++}; ++ ++ ++/* ++** methods for file handles ++*/ ++static const luaL_Reg meth[] = { ++ {"read", f_read}, ++ {"write", f_write}, ++ {"lines", f_lines}, ++ {"flush", f_flush}, ++ {"seek", f_seek}, ++ {"close", f_close}, ++ {"setvbuf", f_setvbuf}, ++ {NULL, NULL} ++}; ++ ++ ++/* ++** metamethods for file handles ++*/ ++static const luaL_Reg metameth[] = { ++ {"__index", NULL}, /* place holder */ ++ {"__gc", f_gc}, ++ {"__close", f_gc}, ++ {"__tostring", f_tostring}, ++ {NULL, NULL} ++}; ++ ++ ++static void createmeta (lua_State *L) { ++ luaL_newmetatable(L, LUA_FILEHANDLE); /* metatable for file handles */ ++ luaL_setfuncs(L, metameth, 0); /* add metamethods to new metatable */ ++ luaL_newlibtable(L, meth); /* create method table */ ++ luaL_setfuncs(L, meth, 0); /* add file methods to method table */ ++ lua_setfield(L, -2, "__index"); /* metatable.__index = method table */ ++ lua_pop(L, 1); /* pop metatable */ ++} ++ ++ ++/* ++** function to (not) close the standard files stdin, stdout, and stderr ++*/ ++static int io_noclose (lua_State *L) { ++ LStream *p = tolstream(L); ++ p->closef = &io_noclose; /* keep file opened */ ++ luaL_pushfail(L); ++ lua_pushliteral(L, "cannot close standard file"); ++ return 2; ++} ++ ++ ++static void createstdfile (lua_State *L, FILE *f, const char *k, ++ const char *fname) { ++ LStream *p = newprefile(L); ++ p->f = f; ++ p->closef = &io_noclose; ++ if (k != NULL) { ++ lua_pushvalue(L, -1); ++ lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */ ++ } ++ lua_setfield(L, -2, fname); /* add file to module */ ++} ++ ++ ++LUAMOD_API int luaopen_io (lua_State *L) { ++ luaL_newlib(L, iolib); /* new module */ ++ createmeta(L); ++ /* create (and set) default files */ ++ createstdfile(L, stdin, IO_INPUT, "stdin"); ++ createstdfile(L, stdout, IO_OUTPUT, "stdout"); ++ createstdfile(L, stderr, NULL, "stderr"); ++ return 1; ++} ++ +diff --git a/src/bin/lua/ljumptab.h b/src/bin/lua/ljumptab.h +new file mode 100644 +index 0000000000..8306f250cc +--- /dev/null ++++ b/src/bin/lua/ljumptab.h +@@ -0,0 +1,112 @@ ++/* ++** $Id: ljumptab.h $ ++** Jump Table for the Lua interpreter ++** See Copyright Notice in lua.h ++*/ ++ ++ ++#undef vmdispatch ++#undef vmcase ++#undef vmbreak ++ ++#define vmdispatch(x) goto *disptab[x]; ++ ++#define vmcase(l) L_##l: ++ ++#define vmbreak vmfetch(); vmdispatch(GET_OPCODE(i)); ++ ++ ++static const void *const disptab[NUM_OPCODES] = { ++ ++#if 0 ++** you can update the following list with this command: ++** ++** sed -n '/^OP_/\!d; s/OP_/\&\&L_OP_/ ; s/,.*/,/ ; s/\/.*// ; p' lopcodes.h ++** ++#endif ++ ++&&L_OP_MOVE, ++&&L_OP_LOADI, ++&&L_OP_LOADF, ++&&L_OP_LOADK, ++&&L_OP_LOADKX, ++&&L_OP_LOADFALSE, ++&&L_OP_LFALSESKIP, ++&&L_OP_LOADTRUE, ++&&L_OP_LOADNIL, ++&&L_OP_GETUPVAL, ++&&L_OP_SETUPVAL, ++&&L_OP_GETTABUP, ++&&L_OP_GETTABLE, ++&&L_OP_GETI, ++&&L_OP_GETFIELD, ++&&L_OP_SETTABUP, ++&&L_OP_SETTABLE, ++&&L_OP_SETI, ++&&L_OP_SETFIELD, ++&&L_OP_NEWTABLE, ++&&L_OP_SELF, ++&&L_OP_ADDI, ++&&L_OP_ADDK, ++&&L_OP_SUBK, ++&&L_OP_MULK, ++&&L_OP_MODK, ++&&L_OP_POWK, ++&&L_OP_DIVK, ++&&L_OP_IDIVK, ++&&L_OP_BANDK, ++&&L_OP_BORK, ++&&L_OP_BXORK, ++&&L_OP_SHRI, ++&&L_OP_SHLI, ++&&L_OP_ADD, ++&&L_OP_SUB, ++&&L_OP_MUL, ++&&L_OP_MOD, ++&&L_OP_POW, ++&&L_OP_DIV, ++&&L_OP_IDIV, ++&&L_OP_BAND, ++&&L_OP_BOR, ++&&L_OP_BXOR, ++&&L_OP_SHL, ++&&L_OP_SHR, ++&&L_OP_MMBIN, ++&&L_OP_MMBINI, ++&&L_OP_MMBINK, ++&&L_OP_UNM, ++&&L_OP_BNOT, ++&&L_OP_NOT, ++&&L_OP_LEN, ++&&L_OP_CONCAT, ++&&L_OP_CLOSE, ++&&L_OP_TBC, ++&&L_OP_JMP, ++&&L_OP_EQ, ++&&L_OP_LT, ++&&L_OP_LE, ++&&L_OP_EQK, ++&&L_OP_EQI, ++&&L_OP_LTI, ++&&L_OP_LEI, ++&&L_OP_GTI, ++&&L_OP_GEI, ++&&L_OP_TEST, ++&&L_OP_TESTSET, ++&&L_OP_CALL, ++&&L_OP_TAILCALL, ++&&L_OP_RETURN, ++&&L_OP_RETURN0, ++&&L_OP_RETURN1, ++&&L_OP_FORLOOP, ++&&L_OP_FORPREP, ++&&L_OP_TFORPREP, ++&&L_OP_TFORCALL, ++&&L_OP_TFORLOOP, ++&&L_OP_SETLIST, ++&&L_OP_CLOSURE, ++&&L_OP_VARARG, ++&&L_OP_VARARGPREP, ++&&L_OP_EXTRAARG ++ ++}; +diff --git a/src/bin/lua/llex.c b/src/bin/lua/llex.c +new file mode 100644 +index 0000000000..e99151787a +--- /dev/null ++++ b/src/bin/lua/llex.c +@@ -0,0 +1,581 @@ ++/* ++** $Id: llex.c $ ++** Lexical Analyzer ++** See Copyright Notice in lua.h ++*/ ++ ++#define llex_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++ ++#include "lua.h" ++ ++#include "lctype.h" ++#include "ldebug.h" ++#include "ldo.h" ++#include "lgc.h" ++#include "llex.h" ++#include "lobject.h" ++#include "lparser.h" ++#include "lstate.h" ++#include "lstring.h" ++#include "ltable.h" ++#include "lzio.h" ++ ++ ++ ++#define next(ls) (ls->current = zgetc(ls->z)) ++ ++ ++ ++#define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r') ++ ++ ++/* ORDER RESERVED */ ++static const char *const luaX_tokens [] = { ++ "and", "break", "do", "else", "elseif", ++ "end", "false", "for", "function", "goto", "if", ++ "in", "local", "nil", "not", "or", "repeat", ++ "return", "then", "true", "until", "while", ++ "//", "..", "...", "==", ">=", "<=", "~=", ++ "<<", ">>", "::", "", ++ "", "", "", "" ++}; ++ ++ ++#define save_and_next(ls) (save(ls, ls->current), next(ls)) ++ ++ ++static l_noret lexerror (LexState *ls, const char *msg, int token); ++ ++ ++static void save (LexState *ls, int c) { ++ Mbuffer *b = ls->buff; ++ if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) { ++ size_t newsize; ++ if (luaZ_sizebuffer(b) >= MAX_SIZE/2) ++ lexerror(ls, "lexical element too long", 0); ++ newsize = luaZ_sizebuffer(b) * 2; ++ luaZ_resizebuffer(ls->L, b, newsize); ++ } ++ b->buffer[luaZ_bufflen(b)++] = cast_char(c); ++} ++ ++ ++void luaX_init (lua_State *L) { ++ int i; ++ TString *e = luaS_newliteral(L, LUA_ENV); /* create env name */ ++ luaC_fix(L, obj2gco(e)); /* never collect this name */ ++ for (i=0; iextra = cast_byte(i+1); /* reserved word */ ++ } ++} ++ ++ ++const char *luaX_token2str (LexState *ls, int token) { ++ if (token < FIRST_RESERVED) { /* single-byte symbols? */ ++ if (lisprint(token)) ++ return luaO_pushfstring(ls->L, "'%c'", token); ++ else /* control character */ ++ return luaO_pushfstring(ls->L, "'<\\%d>'", token); ++ } ++ else { ++ const char *s = luaX_tokens[token - FIRST_RESERVED]; ++ if (token < TK_EOS) /* fixed format (symbols and reserved words)? */ ++ return luaO_pushfstring(ls->L, "'%s'", s); ++ else /* names, strings, and numerals */ ++ return s; ++ } ++} ++ ++ ++static const char *txtToken (LexState *ls, int token) { ++ switch (token) { ++ case TK_NAME: case TK_STRING: ++ case TK_FLT: case TK_INT: ++ save(ls, '\0'); ++ return luaO_pushfstring(ls->L, "'%s'", luaZ_buffer(ls->buff)); ++ default: ++ return luaX_token2str(ls, token); ++ } ++} ++ ++ ++static l_noret lexerror (LexState *ls, const char *msg, int token) { ++ msg = luaG_addinfo(ls->L, msg, ls->source, ls->linenumber); ++ if (token) ++ luaO_pushfstring(ls->L, "%s near %s", msg, txtToken(ls, token)); ++ luaD_throw(ls->L, LUA_ERRSYNTAX); ++} ++ ++ ++l_noret luaX_syntaxerror (LexState *ls, const char *msg) { ++ lexerror(ls, msg, ls->t.token); ++} ++ ++ ++/* ++** Creates a new string and anchors it in scanner's table so that it ++** will not be collected until the end of the compilation; by that time ++** it should be anchored somewhere. It also internalizes long strings, ++** ensuring there is only one copy of each unique string. The table ++** here is used as a set: the string enters as the key, while its value ++** is irrelevant. We use the string itself as the value only because it ++** is a TValue readly available. Later, the code generation can change ++** this value. ++*/ ++TString *luaX_newstring (LexState *ls, const char *str, size_t l) { ++ lua_State *L = ls->L; ++ TString *ts = luaS_newlstr(L, str, l); /* create new string */ ++ const TValue *o = luaH_getstr(ls->h, ts); ++ if (!ttisnil(o)) /* string already present? */ ++ ts = keystrval(nodefromval(o)); /* get saved copy */ ++ else { /* not in use yet */ ++ TValue *stv = s2v(L->top++); /* reserve stack space for string */ ++ setsvalue(L, stv, ts); /* temporarily anchor the string */ ++ luaH_finishset(L, ls->h, stv, o, stv); /* t[string] = string */ ++ /* table is not a metatable, so it does not need to invalidate cache */ ++ luaC_checkGC(L); ++ L->top--; /* remove string from stack */ ++ } ++ return ts; ++} ++ ++ ++/* ++** increment line number and skips newline sequence (any of ++** \n, \r, \n\r, or \r\n) ++*/ ++static void inclinenumber (LexState *ls) { ++ int old = ls->current; ++ lua_assert(currIsNewline(ls)); ++ next(ls); /* skip '\n' or '\r' */ ++ if (currIsNewline(ls) && ls->current != old) ++ next(ls); /* skip '\n\r' or '\r\n' */ ++ if (++ls->linenumber >= MAX_INT) ++ lexerror(ls, "chunk has too many lines", 0); ++} ++ ++ ++void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source, ++ int firstchar) { ++ ls->t.token = 0; ++ ls->L = L; ++ ls->current = firstchar; ++ ls->lookahead.token = TK_EOS; /* no look-ahead token */ ++ ls->z = z; ++ ls->fs = NULL; ++ ls->linenumber = 1; ++ ls->lastline = 1; ++ ls->source = source; ++ ls->envn = luaS_newliteral(L, LUA_ENV); /* get env name */ ++ luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */ ++} ++ ++ ++ ++/* ++** ======================================================= ++** LEXICAL ANALYZER ++** ======================================================= ++*/ ++ ++ ++static int check_next1 (LexState *ls, int c) { ++ if (ls->current == c) { ++ next(ls); ++ return 1; ++ } ++ else return 0; ++} ++ ++ ++/* ++** Check whether current char is in set 'set' (with two chars) and ++** saves it ++*/ ++static int check_next2 (LexState *ls, const char *set) { ++ lua_assert(set[2] == '\0'); ++ if (ls->current == set[0] || ls->current == set[1]) { ++ save_and_next(ls); ++ return 1; ++ } ++ else return 0; ++} ++ ++ ++/* LUA_NUMBER */ ++/* ++** This function is quite liberal in what it accepts, as 'luaO_str2num' ++** will reject ill-formed numerals. Roughly, it accepts the following ++** pattern: ++** ++** %d(%x|%.|([Ee][+-]?))* | 0[Xx](%x|%.|([Pp][+-]?))* ++** ++** The only tricky part is to accept [+-] only after a valid exponent ++** mark, to avoid reading '3-4' or '0xe+1' as a single number. ++** ++** The caller might have already read an initial dot. ++*/ ++static int read_numeral (LexState *ls, SemInfo *seminfo) { ++ TValue obj; ++ const char *expo = "Ee"; ++ int first = ls->current; ++ lua_assert(lisdigit(ls->current)); ++ save_and_next(ls); ++ if (first == '0' && check_next2(ls, "xX")) /* hexadecimal? */ ++ expo = "Pp"; ++ for (;;) { ++ if (check_next2(ls, expo)) /* exponent mark? */ ++ check_next2(ls, "-+"); /* optional exponent sign */ ++ else if (lisxdigit(ls->current) || ls->current == '.') /* '%x|%.' */ ++ save_and_next(ls); ++ else break; ++ } ++ if (lislalpha(ls->current)) /* is numeral touching a letter? */ ++ save_and_next(ls); /* force an error */ ++ save(ls, '\0'); ++ if (luaO_str2num(luaZ_buffer(ls->buff), &obj) == 0) /* format error? */ ++ lexerror(ls, "malformed number", TK_FLT); ++ if (ttisinteger(&obj)) { ++ seminfo->i = ivalue(&obj); ++ return TK_INT; ++ } ++ else { ++ lua_assert(ttisfloat(&obj)); ++ seminfo->r = fltvalue(&obj); ++ return TK_FLT; ++ } ++} ++ ++ ++/* ++** read a sequence '[=*[' or ']=*]', leaving the last bracket. If ++** sequence is well formed, return its number of '='s + 2; otherwise, ++** return 1 if it is a single bracket (no '='s and no 2nd bracket); ++** otherwise (an unfinished '[==...') return 0. ++*/ ++static size_t skip_sep (LexState *ls) { ++ size_t count = 0; ++ int s = ls->current; ++ lua_assert(s == '[' || s == ']'); ++ save_and_next(ls); ++ while (ls->current == '=') { ++ save_and_next(ls); ++ count++; ++ } ++ return (ls->current == s) ? count + 2 ++ : (count == 0) ? 1 ++ : 0; ++} ++ ++ ++static void read_long_string (LexState *ls, SemInfo *seminfo, size_t sep) { ++ int line = ls->linenumber; /* initial line (for error message) */ ++ save_and_next(ls); /* skip 2nd '[' */ ++ if (currIsNewline(ls)) /* string starts with a newline? */ ++ inclinenumber(ls); /* skip it */ ++ for (;;) { ++ switch (ls->current) { ++ case EOZ: { /* error */ ++ const char *what = (seminfo ? "string" : "comment"); ++ const char *msg = luaO_pushfstring(ls->L, ++ "unfinished long %s (starting at line %d)", what, line); ++ lexerror(ls, msg, TK_EOS); ++ break; /* to avoid warnings */ ++ } ++ case ']': { ++ if (skip_sep(ls) == sep) { ++ save_and_next(ls); /* skip 2nd ']' */ ++ goto endloop; ++ } ++ break; ++ } ++ case '\n': case '\r': { ++ save(ls, '\n'); ++ inclinenumber(ls); ++ if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */ ++ break; ++ } ++ default: { ++ if (seminfo) save_and_next(ls); ++ else next(ls); ++ } ++ } ++ } endloop: ++ if (seminfo) ++ seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + sep, ++ luaZ_bufflen(ls->buff) - 2 * sep); ++} ++ ++ ++static void esccheck (LexState *ls, int c, const char *msg) { ++ if (!c) { ++ if (ls->current != EOZ) ++ save_and_next(ls); /* add current to buffer for error message */ ++ lexerror(ls, msg, TK_STRING); ++ } ++} ++ ++ ++static int gethexa (LexState *ls) { ++ save_and_next(ls); ++ esccheck (ls, lisxdigit(ls->current), "hexadecimal digit expected"); ++ return luaO_hexavalue(ls->current); ++} ++ ++ ++static int readhexaesc (LexState *ls) { ++ int r = gethexa(ls); ++ r = (r << 4) + gethexa(ls); ++ luaZ_buffremove(ls->buff, 2); /* remove saved chars from buffer */ ++ return r; ++} ++ ++ ++static unsigned long readutf8esc (LexState *ls) { ++ unsigned long r; ++ int i = 4; /* chars to be removed: '\', 'u', '{', and first digit */ ++ save_and_next(ls); /* skip 'u' */ ++ esccheck(ls, ls->current == '{', "missing '{'"); ++ r = gethexa(ls); /* must have at least one digit */ ++ while (cast_void(save_and_next(ls)), lisxdigit(ls->current)) { ++ i++; ++ esccheck(ls, r <= (0x7FFFFFFFu >> 4), "UTF-8 value too large"); ++ r = (r << 4) + luaO_hexavalue(ls->current); ++ } ++ esccheck(ls, ls->current == '}', "missing '}'"); ++ next(ls); /* skip '}' */ ++ luaZ_buffremove(ls->buff, i); /* remove saved chars from buffer */ ++ return r; ++} ++ ++ ++static void utf8esc (LexState *ls) { ++ char buff[UTF8BUFFSZ]; ++ int n = luaO_utf8esc(buff, readutf8esc(ls)); ++ for (; n > 0; n--) /* add 'buff' to string */ ++ save(ls, buff[UTF8BUFFSZ - n]); ++} ++ ++ ++static int readdecesc (LexState *ls) { ++ int i; ++ int r = 0; /* result accumulator */ ++ for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */ ++ r = 10*r + ls->current - '0'; ++ save_and_next(ls); ++ } ++ esccheck(ls, r <= UCHAR_MAX, "decimal escape too large"); ++ luaZ_buffremove(ls->buff, i); /* remove read digits from buffer */ ++ return r; ++} ++ ++ ++static void read_string (LexState *ls, int del, SemInfo *seminfo) { ++ save_and_next(ls); /* keep delimiter (for error messages) */ ++ while (ls->current != del) { ++ switch (ls->current) { ++ case EOZ: ++ lexerror(ls, "unfinished string", TK_EOS); ++ break; /* to avoid warnings */ ++ case '\n': ++ case '\r': ++ lexerror(ls, "unfinished string", TK_STRING); ++ break; /* to avoid warnings */ ++ case '\\': { /* escape sequences */ ++ int c; /* final character to be saved */ ++ save_and_next(ls); /* keep '\\' for error messages */ ++ switch (ls->current) { ++ case 'a': c = '\a'; goto read_save; ++ case 'b': c = '\b'; goto read_save; ++ case 'f': c = '\f'; goto read_save; ++ case 'n': c = '\n'; goto read_save; ++ case 'r': c = '\r'; goto read_save; ++ case 't': c = '\t'; goto read_save; ++ case 'v': c = '\v'; goto read_save; ++ case 'x': c = readhexaesc(ls); goto read_save; ++ case 'u': utf8esc(ls); goto no_save; ++ case '\n': case '\r': ++ inclinenumber(ls); c = '\n'; goto only_save; ++ case '\\': case '\"': case '\'': ++ c = ls->current; goto read_save; ++ case EOZ: goto no_save; /* will raise an error next loop */ ++ case 'z': { /* zap following span of spaces */ ++ luaZ_buffremove(ls->buff, 1); /* remove '\\' */ ++ next(ls); /* skip the 'z' */ ++ while (lisspace(ls->current)) { ++ if (currIsNewline(ls)) inclinenumber(ls); ++ else next(ls); ++ } ++ goto no_save; ++ } ++ default: { ++ esccheck(ls, lisdigit(ls->current), "invalid escape sequence"); ++ c = readdecesc(ls); /* digital escape '\ddd' */ ++ goto only_save; ++ } ++ } ++ read_save: ++ next(ls); ++ /* go through */ ++ only_save: ++ luaZ_buffremove(ls->buff, 1); /* remove '\\' */ ++ save(ls, c); ++ /* go through */ ++ no_save: break; ++ } ++ default: ++ save_and_next(ls); ++ } ++ } ++ save_and_next(ls); /* skip delimiter */ ++ seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1, ++ luaZ_bufflen(ls->buff) - 2); ++} ++ ++ ++static int llex (LexState *ls, SemInfo *seminfo) { ++ luaZ_resetbuffer(ls->buff); ++ for (;;) { ++ switch (ls->current) { ++ case '\n': case '\r': { /* line breaks */ ++ inclinenumber(ls); ++ break; ++ } ++ case ' ': case '\f': case '\t': case '\v': { /* spaces */ ++ next(ls); ++ break; ++ } ++ case '-': { /* '-' or '--' (comment) */ ++ next(ls); ++ if (ls->current != '-') return '-'; ++ /* else is a comment */ ++ next(ls); ++ if (ls->current == '[') { /* long comment? */ ++ size_t sep = skip_sep(ls); ++ luaZ_resetbuffer(ls->buff); /* 'skip_sep' may dirty the buffer */ ++ if (sep >= 2) { ++ read_long_string(ls, NULL, sep); /* skip long comment */ ++ luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */ ++ break; ++ } ++ } ++ /* else short comment */ ++ while (!currIsNewline(ls) && ls->current != EOZ) ++ next(ls); /* skip until end of line (or end of file) */ ++ break; ++ } ++ case '[': { /* long string or simply '[' */ ++ size_t sep = skip_sep(ls); ++ if (sep >= 2) { ++ read_long_string(ls, seminfo, sep); ++ return TK_STRING; ++ } ++ else if (sep == 0) /* '[=...' missing second bracket? */ ++ lexerror(ls, "invalid long string delimiter", TK_STRING); ++ return '['; ++ } ++ case '=': { ++ next(ls); ++ if (check_next1(ls, '=')) return TK_EQ; /* '==' */ ++ else return '='; ++ } ++ case '<': { ++ next(ls); ++ if (check_next1(ls, '=')) return TK_LE; /* '<=' */ ++ else if (check_next1(ls, '<')) return TK_SHL; /* '<<' */ ++ else return '<'; ++ } ++ case '>': { ++ next(ls); ++ if (check_next1(ls, '=')) return TK_GE; /* '>=' */ ++ else if (check_next1(ls, '>')) return TK_SHR; /* '>>' */ ++ else return '>'; ++ } ++ case '/': { ++ next(ls); ++ if (check_next1(ls, '/')) return TK_IDIV; /* '//' */ ++ else return '/'; ++ } ++ case '~': { ++ next(ls); ++ if (check_next1(ls, '=')) return TK_NE; /* '~=' */ ++ else return '~'; ++ } ++ case ':': { ++ next(ls); ++ if (check_next1(ls, ':')) return TK_DBCOLON; /* '::' */ ++ else return ':'; ++ } ++ case '"': case '\'': { /* short literal strings */ ++ read_string(ls, ls->current, seminfo); ++ return TK_STRING; ++ } ++ case '.': { /* '.', '..', '...', or number */ ++ save_and_next(ls); ++ if (check_next1(ls, '.')) { ++ if (check_next1(ls, '.')) ++ return TK_DOTS; /* '...' */ ++ else return TK_CONCAT; /* '..' */ ++ } ++ else if (!lisdigit(ls->current)) return '.'; ++ else return read_numeral(ls, seminfo); ++ } ++ case '0': case '1': case '2': case '3': case '4': ++ case '5': case '6': case '7': case '8': case '9': { ++ return read_numeral(ls, seminfo); ++ } ++ case EOZ: { ++ return TK_EOS; ++ } ++ default: { ++ if (lislalpha(ls->current)) { /* identifier or reserved word? */ ++ TString *ts; ++ do { ++ save_and_next(ls); ++ } while (lislalnum(ls->current)); ++ ts = luaX_newstring(ls, luaZ_buffer(ls->buff), ++ luaZ_bufflen(ls->buff)); ++ seminfo->ts = ts; ++ if (isreserved(ts)) /* reserved word? */ ++ return ts->extra - 1 + FIRST_RESERVED; ++ else { ++ return TK_NAME; ++ } ++ } ++ else { /* single-char tokens ('+', '*', '%', '{', '}', ...) */ ++ int c = ls->current; ++ next(ls); ++ return c; ++ } ++ } ++ } ++ } ++} ++ ++ ++void luaX_next (LexState *ls) { ++ ls->lastline = ls->linenumber; ++ if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */ ++ ls->t = ls->lookahead; /* use this one */ ++ ls->lookahead.token = TK_EOS; /* and discharge it */ ++ } ++ else ++ ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */ ++} ++ ++ ++int luaX_lookahead (LexState *ls) { ++ lua_assert(ls->lookahead.token == TK_EOS); ++ ls->lookahead.token = llex(ls, &ls->lookahead.seminfo); ++ return ls->lookahead.token; ++} ++ +diff --git a/src/bin/lua/llex.h b/src/bin/lua/llex.h +new file mode 100644 +index 0000000000..389d2f8635 +--- /dev/null ++++ b/src/bin/lua/llex.h +@@ -0,0 +1,91 @@ ++/* ++** $Id: llex.h $ ++** Lexical Analyzer ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef llex_h ++#define llex_h ++ ++#include ++ ++#include "lobject.h" ++#include "lzio.h" ++ ++ ++/* ++** Single-char tokens (terminal symbols) are represented by their own ++** numeric code. Other tokens start at the following value. ++*/ ++#define FIRST_RESERVED (UCHAR_MAX + 1) ++ ++ ++#if !defined(LUA_ENV) ++#define LUA_ENV "_ENV" ++#endif ++ ++ ++/* ++* WARNING: if you change the order of this enumeration, ++* grep "ORDER RESERVED" ++*/ ++enum RESERVED { ++ /* terminal symbols denoted by reserved words */ ++ TK_AND = FIRST_RESERVED, TK_BREAK, ++ TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION, ++ TK_GOTO, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT, ++ TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE, ++ /* other terminal symbols */ ++ TK_IDIV, TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, ++ TK_SHL, TK_SHR, ++ TK_DBCOLON, TK_EOS, ++ TK_FLT, TK_INT, TK_NAME, TK_STRING ++}; ++ ++/* number of reserved words */ ++#define NUM_RESERVED (cast_int(TK_WHILE-FIRST_RESERVED + 1)) ++ ++ ++typedef union { ++ lua_Number r; ++ lua_Integer i; ++ TString *ts; ++} SemInfo; /* semantics information */ ++ ++ ++typedef struct Token { ++ int token; ++ SemInfo seminfo; ++} Token; ++ ++ ++/* state of the lexer plus state of the parser when shared by all ++ functions */ ++typedef struct LexState { ++ int current; /* current character (charint) */ ++ int linenumber; /* input line counter */ ++ int lastline; /* line of last token 'consumed' */ ++ Token t; /* current token */ ++ Token lookahead; /* look ahead token */ ++ struct FuncState *fs; /* current function (parser) */ ++ struct lua_State *L; ++ ZIO *z; /* input stream */ ++ Mbuffer *buff; /* buffer for tokens */ ++ Table *h; /* to avoid collection/reuse strings */ ++ struct Dyndata *dyd; /* dynamic structures used by the parser */ ++ TString *source; /* current source name */ ++ TString *envn; /* environment variable name */ ++} LexState; ++ ++ ++LUAI_FUNC void luaX_init (lua_State *L); ++LUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, ++ TString *source, int firstchar); ++LUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l); ++LUAI_FUNC void luaX_next (LexState *ls); ++LUAI_FUNC int luaX_lookahead (LexState *ls); ++LUAI_FUNC l_noret luaX_syntaxerror (LexState *ls, const char *s); ++LUAI_FUNC const char *luaX_token2str (LexState *ls, int token); ++ ++ ++#endif +diff --git a/src/bin/lua/llimits.h b/src/bin/lua/llimits.h +new file mode 100644 +index 0000000000..025f1c82cd +--- /dev/null ++++ b/src/bin/lua/llimits.h +@@ -0,0 +1,353 @@ ++/* ++** $Id: llimits.h $ ++** Limits, basic types, and some other 'installation-dependent' definitions ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef llimits_h ++#define llimits_h ++ ++ ++#include ++#include ++ ++ ++#include "lua.h" ++ ++ ++/* ++** 'lu_mem' and 'l_mem' are unsigned/signed integers big enough to count ++** the total memory used by Lua (in bytes). Usually, 'size_t' and ++** 'ptrdiff_t' should work, but we use 'long' for 16-bit machines. ++*/ ++#if defined(LUAI_MEM) /* { external definitions? */ ++typedef LUAI_UMEM lu_mem; ++typedef LUAI_MEM l_mem; ++#elif LUAI_IS32INT /* }{ */ ++typedef size_t lu_mem; ++typedef ptrdiff_t l_mem; ++#else /* 16-bit ints */ /* }{ */ ++typedef unsigned long lu_mem; ++typedef long l_mem; ++#endif /* } */ ++ ++ ++/* chars used as small naturals (so that 'char' is reserved for characters) */ ++typedef unsigned char lu_byte; ++typedef signed char ls_byte; ++ ++ ++/* maximum value for size_t */ ++#define MAX_SIZET ((size_t)(~(size_t)0)) ++ ++/* maximum size visible for Lua (must be representable in a lua_Integer) */ ++#define MAX_SIZE (sizeof(size_t) < sizeof(lua_Integer) ? MAX_SIZET \ ++ : (size_t)(LUA_MAXINTEGER)) ++ ++ ++#define MAX_LUMEM ((lu_mem)(~(lu_mem)0)) ++ ++#define MAX_LMEM ((l_mem)(MAX_LUMEM >> 1)) ++ ++ ++#define MAX_INT INT_MAX /* maximum value of an int */ ++ ++ ++/* ++** floor of the log2 of the maximum signed value for integral type 't'. ++** (That is, maximum 'n' such that '2^n' fits in the given signed type.) ++*/ ++#define log2maxs(t) (sizeof(t) * 8 - 2) ++ ++ ++/* ++** test whether an unsigned value is a power of 2 (or zero) ++*/ ++#define ispow2(x) (((x) & ((x) - 1)) == 0) ++ ++ ++/* number of chars of a literal string without the ending \0 */ ++#define LL(x) (sizeof(x)/sizeof(char) - 1) ++ ++ ++/* ++** conversion of pointer to unsigned integer: ++** this is for hashing only; there is no problem if the integer ++** cannot hold the whole pointer value ++*/ ++#define point2uint(p) ((unsigned int)((size_t)(p) & UINT_MAX)) ++ ++ ++ ++/* types of 'usual argument conversions' for lua_Number and lua_Integer */ ++typedef LUAI_UACNUMBER l_uacNumber; ++typedef LUAI_UACINT l_uacInt; ++ ++ ++/* ++** Internal assertions for in-house debugging ++*/ ++#if defined LUAI_ASSERT ++#undef NDEBUG ++#include ++#define lua_assert(c) assert(c) ++#endif ++ ++#if defined(lua_assert) ++#define check_exp(c,e) (lua_assert(c), (e)) ++/* to avoid problems with conditions too long */ ++#define lua_longassert(c) ((c) ? (void)0 : lua_assert(0)) ++#else ++#define lua_assert(c) ((void)0) ++#define check_exp(c,e) (e) ++#define lua_longassert(c) ((void)0) ++#endif ++ ++/* ++** assertion for checking API calls ++*/ ++#if !defined(luai_apicheck) ++#define luai_apicheck(l,e) ((void)l, lua_assert(e)) ++#endif ++ ++#define api_check(l,e,msg) luai_apicheck(l,(e) && msg) ++ ++ ++/* macro to avoid warnings about unused variables */ ++#if !defined(UNUSED) ++#define UNUSED(x) ((void)(x)) ++#endif ++ ++ ++/* type casts (a macro highlights casts in the code) */ ++#define cast(t, exp) ((t)(exp)) ++ ++#define cast_void(i) cast(void, (i)) ++#define cast_voidp(i) cast(void *, (i)) ++#define cast_num(i) cast(lua_Number, (i)) ++#define cast_int(i) cast(int, (i)) ++#define cast_uint(i) cast(unsigned int, (i)) ++#define cast_byte(i) cast(lu_byte, (i)) ++#define cast_uchar(i) cast(unsigned char, (i)) ++#define cast_char(i) cast(char, (i)) ++#define cast_charp(i) cast(char *, (i)) ++#define cast_sizet(i) cast(size_t, (i)) ++ ++ ++/* cast a signed lua_Integer to lua_Unsigned */ ++#if !defined(l_castS2U) ++#define l_castS2U(i) ((lua_Unsigned)(i)) ++#endif ++ ++/* ++** cast a lua_Unsigned to a signed lua_Integer; this cast is ++** not strict ISO C, but two-complement architectures should ++** work fine. ++*/ ++#if !defined(l_castU2S) ++#define l_castU2S(i) ((lua_Integer)(i)) ++#endif ++ ++ ++/* ++** non-return type ++*/ ++#if !defined(l_noret) ++ ++#if defined(__GNUC__) ++#define l_noret void __attribute__((noreturn)) ++#elif defined(_MSC_VER) && _MSC_VER >= 1200 ++#define l_noret void __declspec(noreturn) ++#else ++#define l_noret void ++#endif ++ ++#endif ++ ++ ++/* ++** type for virtual-machine instructions; ++** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h) ++*/ ++#if LUAI_IS32INT ++typedef unsigned int l_uint32; ++#else ++typedef unsigned long l_uint32; ++#endif ++ ++typedef l_uint32 Instruction; ++ ++ ++ ++/* ++** Maximum length for short strings, that is, strings that are ++** internalized. (Cannot be smaller than reserved words or tags for ++** metamethods, as these strings must be internalized; ++** #("function") = 8, #("__newindex") = 10.) ++*/ ++#if !defined(LUAI_MAXSHORTLEN) ++#define LUAI_MAXSHORTLEN 40 ++#endif ++ ++ ++/* ++** Initial size for the string table (must be power of 2). ++** The Lua core alone registers ~50 strings (reserved words + ++** metaevent keys + a few others). Libraries would typically add ++** a few dozens more. ++*/ ++#if !defined(MINSTRTABSIZE) ++#define MINSTRTABSIZE 128 ++#endif ++ ++ ++/* ++** Size of cache for strings in the API. 'N' is the number of ++** sets (better be a prime) and "M" is the size of each set (M == 1 ++** makes a direct cache.) ++*/ ++#if !defined(STRCACHE_N) ++#define STRCACHE_N 53 ++#define STRCACHE_M 2 ++#endif ++ ++ ++/* minimum size for string buffer */ ++#if !defined(LUA_MINBUFFER) ++#define LUA_MINBUFFER 32 ++#endif ++ ++ ++/* ++** Maximum depth for nested C calls, syntactical nested non-terminals, ++** and other features implemented through recursion in C. (Value must ++** fit in a 16-bit unsigned integer. It must also be compatible with ++** the size of the C stack.) ++*/ ++#if !defined(LUAI_MAXCCALLS) ++#define LUAI_MAXCCALLS 200 ++#endif ++ ++ ++/* ++** macros that are executed whenever program enters the Lua core ++** ('lua_lock') and leaves the core ('lua_unlock') ++*/ ++#if !defined(lua_lock) ++#define lua_lock(L) ((void) 0) ++#define lua_unlock(L) ((void) 0) ++#endif ++ ++/* ++** macro executed during Lua functions at points where the ++** function can yield. ++*/ ++#if !defined(luai_threadyield) ++#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);} ++#endif ++ ++ ++/* ++** these macros allow user-specific actions when a thread is ++** created/deleted/resumed/yielded. ++*/ ++#if !defined(luai_userstateopen) ++#define luai_userstateopen(L) ((void)L) ++#endif ++ ++#if !defined(luai_userstateclose) ++#define luai_userstateclose(L) ((void)L) ++#endif ++ ++#if !defined(luai_userstatethread) ++#define luai_userstatethread(L,L1) ((void)L) ++#endif ++ ++#if !defined(luai_userstatefree) ++#define luai_userstatefree(L,L1) ((void)L) ++#endif ++ ++#if !defined(luai_userstateresume) ++#define luai_userstateresume(L,n) ((void)L) ++#endif ++ ++#if !defined(luai_userstateyield) ++#define luai_userstateyield(L,n) ((void)L) ++#endif ++ ++ ++ ++/* ++** The luai_num* macros define the primitive operations over numbers. ++*/ ++ ++/* floor division (defined as 'floor(a/b)') */ ++#if !defined(luai_numidiv) ++#define luai_numidiv(L,a,b) ((void)L, l_floor(luai_numdiv(L,a,b))) ++#endif ++ ++/* float division */ ++#if !defined(luai_numdiv) ++#define luai_numdiv(L,a,b) ((a)/(b)) ++#endif ++ ++/* ++** modulo: defined as 'a - floor(a/b)*b'; the direct computation ++** using this definition has several problems with rounding errors, ++** so it is better to use 'fmod'. 'fmod' gives the result of ++** 'a - trunc(a/b)*b', and therefore must be corrected when ++** 'trunc(a/b) ~= floor(a/b)'. That happens when the division has a ++** non-integer negative result: non-integer result is equivalent to ++** a non-zero remainder 'm'; negative result is equivalent to 'a' and ++** 'b' with different signs, or 'm' and 'b' with different signs ++** (as the result 'm' of 'fmod' has the same sign of 'a'). ++*/ ++#if !defined(luai_nummod) ++#define luai_nummod(L,a,b,m) \ ++ { (void)L; (m) = l_mathop(fmod)(a,b); \ ++ if (((m) > 0) ? (b) < 0 : ((m) < 0 && (b) > 0)) (m) += (b); } ++#endif ++ ++/* exponentiation */ ++#if !defined(luai_numpow) ++#define luai_numpow(L,a,b) \ ++ ((void)L, (b == 2) ? (a)*(a) : l_mathop(pow)(a,b)) ++#endif ++ ++/* the others are quite standard operations */ ++#if !defined(luai_numadd) ++#define luai_numadd(L,a,b) ((a)+(b)) ++#define luai_numsub(L,a,b) ((a)-(b)) ++#define luai_nummul(L,a,b) ((a)*(b)) ++#define luai_numunm(L,a) (-(a)) ++#define luai_numeq(a,b) ((a)==(b)) ++#define luai_numlt(a,b) ((a)<(b)) ++#define luai_numle(a,b) ((a)<=(b)) ++#define luai_numgt(a,b) ((a)>(b)) ++#define luai_numge(a,b) ((a)>=(b)) ++#define luai_numisnan(a) (!luai_numeq((a), (a))) ++#endif ++ ++ ++ ++ ++ ++/* ++** macro to control inclusion of some hard tests on stack reallocation ++*/ ++#if !defined(HARDSTACKTESTS) ++#define condmovestack(L,pre,pos) ((void)0) ++#else ++/* realloc stack keeping its size */ ++#define condmovestack(L,pre,pos) \ ++ { int sz_ = stacksize(L); pre; luaD_reallocstack((L), sz_, 0); pos; } ++#endif ++ ++#if !defined(HARDMEMTESTS) ++#define condchangemem(L,pre,pos) ((void)0) ++#else ++#define condchangemem(L,pre,pos) \ ++ { if (G(L)->gcrunning) { pre; luaC_fullgc(L, 0); pos; } } ++#endif ++ ++#endif +diff --git a/src/bin/lua/lmathlib.c b/src/bin/lua/lmathlib.c +new file mode 100644 +index 0000000000..5f5983a438 +--- /dev/null ++++ b/src/bin/lua/lmathlib.c +@@ -0,0 +1,764 @@ ++/* ++** $Id: lmathlib.c $ ++** Standard mathematical library ++** See Copyright Notice in lua.h ++*/ ++ ++#define lmathlib_c ++#define LUA_LIB ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++#include ++#include ++#include ++ ++#include "lua.h" ++ ++#include "lauxlib.h" ++#include "lualib.h" ++ ++ ++#undef PI ++#define PI (l_mathop(3.141592653589793238462643383279502884)) ++ ++ ++static int math_abs (lua_State *L) { ++ if (lua_isinteger(L, 1)) { ++ lua_Integer n = lua_tointeger(L, 1); ++ if (n < 0) n = (lua_Integer)(0u - (lua_Unsigned)n); ++ lua_pushinteger(L, n); ++ } ++ else ++ lua_pushnumber(L, l_mathop(fabs)(luaL_checknumber(L, 1))); ++ return 1; ++} ++ ++static int math_sin (lua_State *L) { ++ lua_pushnumber(L, l_mathop(sin)(luaL_checknumber(L, 1))); ++ return 1; ++} ++ ++static int math_cos (lua_State *L) { ++ lua_pushnumber(L, l_mathop(cos)(luaL_checknumber(L, 1))); ++ return 1; ++} ++ ++static int math_tan (lua_State *L) { ++ lua_pushnumber(L, l_mathop(tan)(luaL_checknumber(L, 1))); ++ return 1; ++} ++ ++static int math_asin (lua_State *L) { ++ lua_pushnumber(L, l_mathop(asin)(luaL_checknumber(L, 1))); ++ return 1; ++} ++ ++static int math_acos (lua_State *L) { ++ lua_pushnumber(L, l_mathop(acos)(luaL_checknumber(L, 1))); ++ return 1; ++} ++ ++static int math_atan (lua_State *L) { ++ lua_Number y = luaL_checknumber(L, 1); ++ lua_Number x = luaL_optnumber(L, 2, 1); ++ lua_pushnumber(L, l_mathop(atan2)(y, x)); ++ return 1; ++} ++ ++ ++static int math_toint (lua_State *L) { ++ int valid; ++ lua_Integer n = lua_tointegerx(L, 1, &valid); ++ if (l_likely(valid)) ++ lua_pushinteger(L, n); ++ else { ++ luaL_checkany(L, 1); ++ luaL_pushfail(L); /* value is not convertible to integer */ ++ } ++ return 1; ++} ++ ++ ++static void pushnumint (lua_State *L, lua_Number d) { ++ lua_Integer n; ++ if (lua_numbertointeger(d, &n)) /* does 'd' fit in an integer? */ ++ lua_pushinteger(L, n); /* result is integer */ ++ else ++ lua_pushnumber(L, d); /* result is float */ ++} ++ ++ ++static int math_floor (lua_State *L) { ++ if (lua_isinteger(L, 1)) ++ lua_settop(L, 1); /* integer is its own floor */ ++ else { ++ lua_Number d = l_mathop(floor)(luaL_checknumber(L, 1)); ++ pushnumint(L, d); ++ } ++ return 1; ++} ++ ++ ++static int math_ceil (lua_State *L) { ++ if (lua_isinteger(L, 1)) ++ lua_settop(L, 1); /* integer is its own ceil */ ++ else { ++ lua_Number d = l_mathop(ceil)(luaL_checknumber(L, 1)); ++ pushnumint(L, d); ++ } ++ return 1; ++} ++ ++ ++static int math_fmod (lua_State *L) { ++ if (lua_isinteger(L, 1) && lua_isinteger(L, 2)) { ++ lua_Integer d = lua_tointeger(L, 2); ++ if ((lua_Unsigned)d + 1u <= 1u) { /* special cases: -1 or 0 */ ++ luaL_argcheck(L, d != 0, 2, "zero"); ++ lua_pushinteger(L, 0); /* avoid overflow with 0x80000... / -1 */ ++ } ++ else ++ lua_pushinteger(L, lua_tointeger(L, 1) % d); ++ } ++ else ++ lua_pushnumber(L, l_mathop(fmod)(luaL_checknumber(L, 1), ++ luaL_checknumber(L, 2))); ++ return 1; ++} ++ ++ ++/* ++** next function does not use 'modf', avoiding problems with 'double*' ++** (which is not compatible with 'float*') when lua_Number is not ++** 'double'. ++*/ ++static int math_modf (lua_State *L) { ++ if (lua_isinteger(L ,1)) { ++ lua_settop(L, 1); /* number is its own integer part */ ++ lua_pushnumber(L, 0); /* no fractional part */ ++ } ++ else { ++ lua_Number n = luaL_checknumber(L, 1); ++ /* integer part (rounds toward zero) */ ++ lua_Number ip = (n < 0) ? l_mathop(ceil)(n) : l_mathop(floor)(n); ++ pushnumint(L, ip); ++ /* fractional part (test needed for inf/-inf) */ ++ lua_pushnumber(L, (n == ip) ? l_mathop(0.0) : (n - ip)); ++ } ++ return 2; ++} ++ ++ ++static int math_sqrt (lua_State *L) { ++ lua_pushnumber(L, l_mathop(sqrt)(luaL_checknumber(L, 1))); ++ return 1; ++} ++ ++ ++static int math_ult (lua_State *L) { ++ lua_Integer a = luaL_checkinteger(L, 1); ++ lua_Integer b = luaL_checkinteger(L, 2); ++ lua_pushboolean(L, (lua_Unsigned)a < (lua_Unsigned)b); ++ return 1; ++} ++ ++static int math_log (lua_State *L) { ++ lua_Number x = luaL_checknumber(L, 1); ++ lua_Number res; ++ if (lua_isnoneornil(L, 2)) ++ res = l_mathop(log)(x); ++ else { ++ lua_Number base = luaL_checknumber(L, 2); ++#if !defined(LUA_USE_C89) ++ if (base == l_mathop(2.0)) ++ res = l_mathop(log2)(x); ++ else ++#endif ++ if (base == l_mathop(10.0)) ++ res = l_mathop(log10)(x); ++ else ++ res = l_mathop(log)(x)/l_mathop(log)(base); ++ } ++ lua_pushnumber(L, res); ++ return 1; ++} ++ ++static int math_exp (lua_State *L) { ++ lua_pushnumber(L, l_mathop(exp)(luaL_checknumber(L, 1))); ++ return 1; ++} ++ ++static int math_deg (lua_State *L) { ++ lua_pushnumber(L, luaL_checknumber(L, 1) * (l_mathop(180.0) / PI)); ++ return 1; ++} ++ ++static int math_rad (lua_State *L) { ++ lua_pushnumber(L, luaL_checknumber(L, 1) * (PI / l_mathop(180.0))); ++ return 1; ++} ++ ++ ++static int math_min (lua_State *L) { ++ int n = lua_gettop(L); /* number of arguments */ ++ int imin = 1; /* index of current minimum value */ ++ int i; ++ luaL_argcheck(L, n >= 1, 1, "value expected"); ++ for (i = 2; i <= n; i++) { ++ if (lua_compare(L, i, imin, LUA_OPLT)) ++ imin = i; ++ } ++ lua_pushvalue(L, imin); ++ return 1; ++} ++ ++ ++static int math_max (lua_State *L) { ++ int n = lua_gettop(L); /* number of arguments */ ++ int imax = 1; /* index of current maximum value */ ++ int i; ++ luaL_argcheck(L, n >= 1, 1, "value expected"); ++ for (i = 2; i <= n; i++) { ++ if (lua_compare(L, imax, i, LUA_OPLT)) ++ imax = i; ++ } ++ lua_pushvalue(L, imax); ++ return 1; ++} ++ ++ ++static int math_type (lua_State *L) { ++ if (lua_type(L, 1) == LUA_TNUMBER) ++ lua_pushstring(L, (lua_isinteger(L, 1)) ? "integer" : "float"); ++ else { ++ luaL_checkany(L, 1); ++ luaL_pushfail(L); ++ } ++ return 1; ++} ++ ++ ++ ++/* ++** {================================================================== ++** Pseudo-Random Number Generator based on 'xoshiro256**'. ++** =================================================================== ++*/ ++ ++/* number of binary digits in the mantissa of a float */ ++#define FIGS l_floatatt(MANT_DIG) ++ ++#if FIGS > 64 ++/* there are only 64 random bits; use them all */ ++#undef FIGS ++#define FIGS 64 ++#endif ++ ++ ++/* ++** LUA_RAND32 forces the use of 32-bit integers in the implementation ++** of the PRN generator (mainly for testing). ++*/ ++#if !defined(LUA_RAND32) && !defined(Rand64) ++ ++/* try to find an integer type with at least 64 bits */ ++ ++#if (ULONG_MAX >> 31 >> 31) >= 3 ++ ++/* 'long' has at least 64 bits */ ++#define Rand64 unsigned long ++ ++#elif !defined(LUA_USE_C89) && defined(LLONG_MAX) ++ ++/* there is a 'long long' type (which must have at least 64 bits) */ ++#define Rand64 unsigned long long ++ ++#elif (LUA_MAXUNSIGNED >> 31 >> 31) >= 3 ++ ++/* 'lua_Integer' has at least 64 bits */ ++#define Rand64 lua_Unsigned ++ ++#endif ++ ++#endif ++ ++ ++#if defined(Rand64) /* { */ ++ ++/* ++** Standard implementation, using 64-bit integers. ++** If 'Rand64' has more than 64 bits, the extra bits do not interfere ++** with the 64 initial bits, except in a right shift. Moreover, the ++** final result has to discard the extra bits. ++*/ ++ ++/* avoid using extra bits when needed */ ++#define trim64(x) ((x) & 0xffffffffffffffffu) ++ ++ ++/* rotate left 'x' by 'n' bits */ ++static Rand64 rotl (Rand64 x, int n) { ++ return (x << n) | (trim64(x) >> (64 - n)); ++} ++ ++static Rand64 nextrand (Rand64 *state) { ++ Rand64 state0 = state[0]; ++ Rand64 state1 = state[1]; ++ Rand64 state2 = state[2] ^ state0; ++ Rand64 state3 = state[3] ^ state1; ++ Rand64 res = rotl(state1 * 5, 7) * 9; ++ state[0] = state0 ^ state3; ++ state[1] = state1 ^ state2; ++ state[2] = state2 ^ (state1 << 17); ++ state[3] = rotl(state3, 45); ++ return res; ++} ++ ++ ++/* must take care to not shift stuff by more than 63 slots */ ++ ++ ++/* ++** Convert bits from a random integer into a float in the ++** interval [0,1), getting the higher FIG bits from the ++** random unsigned integer and converting that to a float. ++*/ ++ ++/* must throw out the extra (64 - FIGS) bits */ ++#define shift64_FIG (64 - FIGS) ++ ++/* to scale to [0, 1), multiply by scaleFIG = 2^(-FIGS) */ ++#define scaleFIG (l_mathop(0.5) / ((Rand64)1 << (FIGS - 1))) ++ ++static lua_Number I2d (Rand64 x) { ++ return (lua_Number)(trim64(x) >> shift64_FIG) * scaleFIG; ++} ++ ++/* convert a 'Rand64' to a 'lua_Unsigned' */ ++#define I2UInt(x) ((lua_Unsigned)trim64(x)) ++ ++/* convert a 'lua_Unsigned' to a 'Rand64' */ ++#define Int2I(x) ((Rand64)(x)) ++ ++ ++#else /* no 'Rand64' }{ */ ++ ++/* get an integer with at least 32 bits */ ++#if LUAI_IS32INT ++typedef unsigned int lu_int32; ++#else ++typedef unsigned long lu_int32; ++#endif ++ ++ ++/* ++** Use two 32-bit integers to represent a 64-bit quantity. ++*/ ++typedef struct Rand64 { ++ lu_int32 h; /* higher half */ ++ lu_int32 l; /* lower half */ ++} Rand64; ++ ++ ++/* ++** If 'lu_int32' has more than 32 bits, the extra bits do not interfere ++** with the 32 initial bits, except in a right shift and comparisons. ++** Moreover, the final result has to discard the extra bits. ++*/ ++ ++/* avoid using extra bits when needed */ ++#define trim32(x) ((x) & 0xffffffffu) ++ ++ ++/* ++** basic operations on 'Rand64' values ++*/ ++ ++/* build a new Rand64 value */ ++static Rand64 packI (lu_int32 h, lu_int32 l) { ++ Rand64 result; ++ result.h = h; ++ result.l = l; ++ return result; ++} ++ ++/* return i << n */ ++static Rand64 Ishl (Rand64 i, int n) { ++ lua_assert(n > 0 && n < 32); ++ return packI((i.h << n) | (trim32(i.l) >> (32 - n)), i.l << n); ++} ++ ++/* i1 ^= i2 */ ++static void Ixor (Rand64 *i1, Rand64 i2) { ++ i1->h ^= i2.h; ++ i1->l ^= i2.l; ++} ++ ++/* return i1 + i2 */ ++static Rand64 Iadd (Rand64 i1, Rand64 i2) { ++ Rand64 result = packI(i1.h + i2.h, i1.l + i2.l); ++ if (trim32(result.l) < trim32(i1.l)) /* carry? */ ++ result.h++; ++ return result; ++} ++ ++/* return i * 5 */ ++static Rand64 times5 (Rand64 i) { ++ return Iadd(Ishl(i, 2), i); /* i * 5 == (i << 2) + i */ ++} ++ ++/* return i * 9 */ ++static Rand64 times9 (Rand64 i) { ++ return Iadd(Ishl(i, 3), i); /* i * 9 == (i << 3) + i */ ++} ++ ++/* return 'i' rotated left 'n' bits */ ++static Rand64 rotl (Rand64 i, int n) { ++ lua_assert(n > 0 && n < 32); ++ return packI((i.h << n) | (trim32(i.l) >> (32 - n)), ++ (trim32(i.h) >> (32 - n)) | (i.l << n)); ++} ++ ++/* for offsets larger than 32, rotate right by 64 - offset */ ++static Rand64 rotl1 (Rand64 i, int n) { ++ lua_assert(n > 32 && n < 64); ++ n = 64 - n; ++ return packI((trim32(i.h) >> n) | (i.l << (32 - n)), ++ (i.h << (32 - n)) | (trim32(i.l) >> n)); ++} ++ ++/* ++** implementation of 'xoshiro256**' algorithm on 'Rand64' values ++*/ ++static Rand64 nextrand (Rand64 *state) { ++ Rand64 res = times9(rotl(times5(state[1]), 7)); ++ Rand64 t = Ishl(state[1], 17); ++ Ixor(&state[2], state[0]); ++ Ixor(&state[3], state[1]); ++ Ixor(&state[1], state[2]); ++ Ixor(&state[0], state[3]); ++ Ixor(&state[2], t); ++ state[3] = rotl1(state[3], 45); ++ return res; ++} ++ ++ ++/* ++** Converts a 'Rand64' into a float. ++*/ ++ ++/* an unsigned 1 with proper type */ ++#define UONE ((lu_int32)1) ++ ++ ++#if FIGS <= 32 ++ ++/* 2^(-FIGS) */ ++#define scaleFIG (l_mathop(0.5) / (UONE << (FIGS - 1))) ++ ++/* ++** get up to 32 bits from higher half, shifting right to ++** throw out the extra bits. ++*/ ++static lua_Number I2d (Rand64 x) { ++ lua_Number h = (lua_Number)(trim32(x.h) >> (32 - FIGS)); ++ return h * scaleFIG; ++} ++ ++#else /* 32 < FIGS <= 64 */ ++ ++/* must take care to not shift stuff by more than 31 slots */ ++ ++/* 2^(-FIGS) = 1.0 / 2^30 / 2^3 / 2^(FIGS-33) */ ++#define scaleFIG \ ++ ((lua_Number)1.0 / (UONE << 30) / 8.0 / (UONE << (FIGS - 33))) ++ ++/* ++** use FIGS - 32 bits from lower half, throwing out the other ++** (32 - (FIGS - 32)) = (64 - FIGS) bits ++*/ ++#define shiftLOW (64 - FIGS) ++ ++/* ++** higher 32 bits go after those (FIGS - 32) bits: shiftHI = 2^(FIGS - 32) ++*/ ++#define shiftHI ((lua_Number)(UONE << (FIGS - 33)) * 2.0) ++ ++ ++static lua_Number I2d (Rand64 x) { ++ lua_Number h = (lua_Number)trim32(x.h) * shiftHI; ++ lua_Number l = (lua_Number)(trim32(x.l) >> shiftLOW); ++ return (h + l) * scaleFIG; ++} ++ ++#endif ++ ++ ++/* convert a 'Rand64' to a 'lua_Unsigned' */ ++static lua_Unsigned I2UInt (Rand64 x) { ++ return ((lua_Unsigned)trim32(x.h) << 31 << 1) | (lua_Unsigned)trim32(x.l); ++} ++ ++/* convert a 'lua_Unsigned' to a 'Rand64' */ ++static Rand64 Int2I (lua_Unsigned n) { ++ return packI((lu_int32)(n >> 31 >> 1), (lu_int32)n); ++} ++ ++#endif /* } */ ++ ++ ++/* ++** A state uses four 'Rand64' values. ++*/ ++typedef struct { ++ Rand64 s[4]; ++} RanState; ++ ++ ++/* ++** Project the random integer 'ran' into the interval [0, n]. ++** Because 'ran' has 2^B possible values, the projection can only be ++** uniform when the size of the interval is a power of 2 (exact ++** division). Otherwise, to get a uniform projection into [0, n], we ++** first compute 'lim', the smallest Mersenne number not smaller than ++** 'n'. We then project 'ran' into the interval [0, lim]. If the result ++** is inside [0, n], we are done. Otherwise, we try with another 'ran', ++** until we have a result inside the interval. ++*/ ++static lua_Unsigned project (lua_Unsigned ran, lua_Unsigned n, ++ RanState *state) { ++ if ((n & (n + 1)) == 0) /* is 'n + 1' a power of 2? */ ++ return ran & n; /* no bias */ ++ else { ++ lua_Unsigned lim = n; ++ /* compute the smallest (2^b - 1) not smaller than 'n' */ ++ lim |= (lim >> 1); ++ lim |= (lim >> 2); ++ lim |= (lim >> 4); ++ lim |= (lim >> 8); ++ lim |= (lim >> 16); ++#if (LUA_MAXUNSIGNED >> 31) >= 3 ++ lim |= (lim >> 32); /* integer type has more than 32 bits */ ++#endif ++ lua_assert((lim & (lim + 1)) == 0 /* 'lim + 1' is a power of 2, */ ++ && lim >= n /* not smaller than 'n', */ ++ && (lim >> 1) < n); /* and it is the smallest one */ ++ while ((ran &= lim) > n) /* project 'ran' into [0..lim] */ ++ ran = I2UInt(nextrand(state->s)); /* not inside [0..n]? try again */ ++ return ran; ++ } ++} ++ ++ ++static int math_random (lua_State *L) { ++ lua_Integer low, up; ++ lua_Unsigned p; ++ RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1)); ++ Rand64 rv = nextrand(state->s); /* next pseudo-random value */ ++ switch (lua_gettop(L)) { /* check number of arguments */ ++ case 0: { /* no arguments */ ++ lua_pushnumber(L, I2d(rv)); /* float between 0 and 1 */ ++ return 1; ++ } ++ case 1: { /* only upper limit */ ++ low = 1; ++ up = luaL_checkinteger(L, 1); ++ if (up == 0) { /* single 0 as argument? */ ++ lua_pushinteger(L, I2UInt(rv)); /* full random integer */ ++ return 1; ++ } ++ break; ++ } ++ case 2: { /* lower and upper limits */ ++ low = luaL_checkinteger(L, 1); ++ up = luaL_checkinteger(L, 2); ++ break; ++ } ++ default: return luaL_error(L, "wrong number of arguments"); ++ } ++ /* random integer in the interval [low, up] */ ++ luaL_argcheck(L, low <= up, 1, "interval is empty"); ++ /* project random integer into the interval [0, up - low] */ ++ p = project(I2UInt(rv), (lua_Unsigned)up - (lua_Unsigned)low, state); ++ lua_pushinteger(L, p + (lua_Unsigned)low); ++ return 1; ++} ++ ++ ++static void setseed (lua_State *L, Rand64 *state, ++ lua_Unsigned n1, lua_Unsigned n2) { ++ int i; ++ state[0] = Int2I(n1); ++ state[1] = Int2I(0xff); /* avoid a zero state */ ++ state[2] = Int2I(n2); ++ state[3] = Int2I(0); ++ for (i = 0; i < 16; i++) ++ nextrand(state); /* discard initial values to "spread" seed */ ++ lua_pushinteger(L, n1); ++ lua_pushinteger(L, n2); ++} ++ ++ ++/* ++** Set a "random" seed. To get some randomness, use the current time ++** and the address of 'L' (in case the machine does address space layout ++** randomization). ++*/ ++static void randseed (lua_State *L, RanState *state) { ++ lua_Unsigned seed1 = (lua_Unsigned)time(NULL); ++ lua_Unsigned seed2 = (lua_Unsigned)(size_t)L; ++ setseed(L, state->s, seed1, seed2); ++} ++ ++ ++static int math_randomseed (lua_State *L) { ++ RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1)); ++ if (lua_isnone(L, 1)) { ++ randseed(L, state); ++ } ++ else { ++ lua_Integer n1 = luaL_checkinteger(L, 1); ++ lua_Integer n2 = luaL_optinteger(L, 2, 0); ++ setseed(L, state->s, n1, n2); ++ } ++ return 2; /* return seeds */ ++} ++ ++ ++static const luaL_Reg randfuncs[] = { ++ {"random", math_random}, ++ {"randomseed", math_randomseed}, ++ {NULL, NULL} ++}; ++ ++ ++/* ++** Register the random functions and initialize their state. ++*/ ++static void setrandfunc (lua_State *L) { ++ RanState *state = (RanState *)lua_newuserdatauv(L, sizeof(RanState), 0); ++ randseed(L, state); /* initialize with a "random" seed */ ++ lua_pop(L, 2); /* remove pushed seeds */ ++ luaL_setfuncs(L, randfuncs, 1); ++} ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Deprecated functions (for compatibility only) ++** =================================================================== ++*/ ++#if defined(LUA_COMPAT_MATHLIB) ++ ++static int math_cosh (lua_State *L) { ++ lua_pushnumber(L, l_mathop(cosh)(luaL_checknumber(L, 1))); ++ return 1; ++} ++ ++static int math_sinh (lua_State *L) { ++ lua_pushnumber(L, l_mathop(sinh)(luaL_checknumber(L, 1))); ++ return 1; ++} ++ ++static int math_tanh (lua_State *L) { ++ lua_pushnumber(L, l_mathop(tanh)(luaL_checknumber(L, 1))); ++ return 1; ++} ++ ++static int math_pow (lua_State *L) { ++ lua_Number x = luaL_checknumber(L, 1); ++ lua_Number y = luaL_checknumber(L, 2); ++ lua_pushnumber(L, l_mathop(pow)(x, y)); ++ return 1; ++} ++ ++static int math_frexp (lua_State *L) { ++ int e; ++ lua_pushnumber(L, l_mathop(frexp)(luaL_checknumber(L, 1), &e)); ++ lua_pushinteger(L, e); ++ return 2; ++} ++ ++static int math_ldexp (lua_State *L) { ++ lua_Number x = luaL_checknumber(L, 1); ++ int ep = (int)luaL_checkinteger(L, 2); ++ lua_pushnumber(L, l_mathop(ldexp)(x, ep)); ++ return 1; ++} ++ ++static int math_log10 (lua_State *L) { ++ lua_pushnumber(L, l_mathop(log10)(luaL_checknumber(L, 1))); ++ return 1; ++} ++ ++#endif ++/* }================================================================== */ ++ ++ ++ ++static const luaL_Reg mathlib[] = { ++ {"abs", math_abs}, ++ {"acos", math_acos}, ++ {"asin", math_asin}, ++ {"atan", math_atan}, ++ {"ceil", math_ceil}, ++ {"cos", math_cos}, ++ {"deg", math_deg}, ++ {"exp", math_exp}, ++ {"tointeger", math_toint}, ++ {"floor", math_floor}, ++ {"fmod", math_fmod}, ++ {"ult", math_ult}, ++ {"log", math_log}, ++ {"max", math_max}, ++ {"min", math_min}, ++ {"modf", math_modf}, ++ {"rad", math_rad}, ++ {"sin", math_sin}, ++ {"sqrt", math_sqrt}, ++ {"tan", math_tan}, ++ {"type", math_type}, ++#if defined(LUA_COMPAT_MATHLIB) ++ {"atan2", math_atan}, ++ {"cosh", math_cosh}, ++ {"sinh", math_sinh}, ++ {"tanh", math_tanh}, ++ {"pow", math_pow}, ++ {"frexp", math_frexp}, ++ {"ldexp", math_ldexp}, ++ {"log10", math_log10}, ++#endif ++ /* placeholders */ ++ {"random", NULL}, ++ {"randomseed", NULL}, ++ {"pi", NULL}, ++ {"huge", NULL}, ++ {"maxinteger", NULL}, ++ {"mininteger", NULL}, ++ {NULL, NULL} ++}; ++ ++ ++/* ++** Open math library ++*/ ++LUAMOD_API int luaopen_math (lua_State *L) { ++ luaL_newlib(L, mathlib); ++ lua_pushnumber(L, PI); ++ lua_setfield(L, -2, "pi"); ++ lua_pushnumber(L, (lua_Number)HUGE_VAL); ++ lua_setfield(L, -2, "huge"); ++ lua_pushinteger(L, LUA_MAXINTEGER); ++ lua_setfield(L, -2, "maxinteger"); ++ lua_pushinteger(L, LUA_MININTEGER); ++ lua_setfield(L, -2, "mininteger"); ++ setrandfunc(L); ++ return 1; ++} ++ +diff --git a/src/bin/lua/lmem.c b/src/bin/lua/lmem.c +new file mode 100644 +index 0000000000..9029d588c1 +--- /dev/null ++++ b/src/bin/lua/lmem.c +@@ -0,0 +1,201 @@ ++/* ++** $Id: lmem.c $ ++** Interface to Memory Manager ++** See Copyright Notice in lua.h ++*/ ++ ++#define lmem_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++#include ++ ++#include "lua.h" ++ ++#include "ldebug.h" ++#include "ldo.h" ++#include "lgc.h" ++#include "lmem.h" ++#include "lobject.h" ++#include "lstate.h" ++ ++ ++#if defined(EMERGENCYGCTESTS) ++/* ++** First allocation will fail whenever not building initial state. ++** (This fail will trigger 'tryagain' and a full GC cycle at every ++** allocation.) ++*/ ++static void *firsttry (global_State *g, void *block, size_t os, size_t ns) { ++ if (completestate(g) && ns > 0) /* frees never fail */ ++ return NULL; /* fail */ ++ else /* normal allocation */ ++ return (*g->frealloc)(g->ud, block, os, ns); ++} ++#else ++#define firsttry(g,block,os,ns) ((*g->frealloc)(g->ud, block, os, ns)) ++#endif ++ ++ ++ ++ ++ ++/* ++** About the realloc function: ++** void *frealloc (void *ud, void *ptr, size_t osize, size_t nsize); ++** ('osize' is the old size, 'nsize' is the new size) ++** ++** - frealloc(ud, p, x, 0) frees the block 'p' and returns NULL. ++** Particularly, frealloc(ud, NULL, 0, 0) does nothing, ++** which is equivalent to free(NULL) in ISO C. ++** ++** - frealloc(ud, NULL, x, s) creates a new block of size 's' ++** (no matter 'x'). Returns NULL if it cannot create the new block. ++** ++** - otherwise, frealloc(ud, b, x, y) reallocates the block 'b' from ++** size 'x' to size 'y'. Returns NULL if it cannot reallocate the ++** block to the new size. ++*/ ++ ++ ++ ++ ++/* ++** {================================================================== ++** Functions to allocate/deallocate arrays for the Parser ++** =================================================================== ++*/ ++ ++/* ++** Minimum size for arrays during parsing, to avoid overhead of ++** reallocating to size 1, then 2, and then 4. All these arrays ++** will be reallocated to exact sizes or erased when parsing ends. ++*/ ++#define MINSIZEARRAY 4 ++ ++ ++void *luaM_growaux_ (lua_State *L, void *block, int nelems, int *psize, ++ int size_elems, int limit, const char *what) { ++ void *newblock; ++ int size = *psize; ++ if (nelems + 1 <= size) /* does one extra element still fit? */ ++ return block; /* nothing to be done */ ++ if (size >= limit / 2) { /* cannot double it? */ ++ if (l_unlikely(size >= limit)) /* cannot grow even a little? */ ++ luaG_runerror(L, "too many %s (limit is %d)", what, limit); ++ size = limit; /* still have at least one free place */ ++ } ++ else { ++ size *= 2; ++ if (size < MINSIZEARRAY) ++ size = MINSIZEARRAY; /* minimum size */ ++ } ++ lua_assert(nelems + 1 <= size && size <= limit); ++ /* 'limit' ensures that multiplication will not overflow */ ++ newblock = luaM_saferealloc_(L, block, cast_sizet(*psize) * size_elems, ++ cast_sizet(size) * size_elems); ++ *psize = size; /* update only when everything else is OK */ ++ return newblock; ++} ++ ++ ++/* ++** In prototypes, the size of the array is also its number of ++** elements (to save memory). So, if it cannot shrink an array ++** to its number of elements, the only option is to raise an ++** error. ++*/ ++void *luaM_shrinkvector_ (lua_State *L, void *block, int *size, ++ int final_n, int size_elem) { ++ void *newblock; ++ size_t oldsize = cast_sizet((*size) * size_elem); ++ size_t newsize = cast_sizet(final_n * size_elem); ++ lua_assert(newsize <= oldsize); ++ newblock = luaM_saferealloc_(L, block, oldsize, newsize); ++ *size = final_n; ++ return newblock; ++} ++ ++/* }================================================================== */ ++ ++ ++l_noret luaM_toobig (lua_State *L) { ++ luaG_runerror(L, "memory allocation error: block too big"); ++} ++ ++ ++/* ++** Free memory ++*/ ++void luaM_free_ (lua_State *L, void *block, size_t osize) { ++ global_State *g = G(L); ++ lua_assert((osize == 0) == (block == NULL)); ++ (*g->frealloc)(g->ud, block, osize, 0); ++ g->GCdebt -= osize; ++} ++ ++ ++/* ++** In case of allocation fail, this function will do an emergency ++** collection to free some memory and then try the allocation again. ++** The GC should not be called while state is not fully built, as the ++** collector is not yet fully initialized. Also, it should not be called ++** when 'gcstopem' is true, because then the interpreter is in the ++** middle of a collection step. ++*/ ++static void *tryagain (lua_State *L, void *block, ++ size_t osize, size_t nsize) { ++ global_State *g = G(L); ++ if (completestate(g) && !g->gcstopem) { ++ luaC_fullgc(L, 1); /* try to free some memory... */ ++ return (*g->frealloc)(g->ud, block, osize, nsize); /* try again */ ++ } ++ else return NULL; /* cannot free any memory without a full state */ ++} ++ ++ ++/* ++** Generic allocation routine. ++*/ ++void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) { ++ void *newblock; ++ global_State *g = G(L); ++ lua_assert((osize == 0) == (block == NULL)); ++ newblock = firsttry(g, block, osize, nsize); ++ if (l_unlikely(newblock == NULL && nsize > 0)) { ++ newblock = tryagain(L, block, osize, nsize); ++ if (newblock == NULL) /* still no memory? */ ++ return NULL; /* do not update 'GCdebt' */ ++ } ++ lua_assert((nsize == 0) == (newblock == NULL)); ++ g->GCdebt = (g->GCdebt + nsize) - osize; ++ return newblock; ++} ++ ++ ++void *luaM_saferealloc_ (lua_State *L, void *block, size_t osize, ++ size_t nsize) { ++ void *newblock = luaM_realloc_(L, block, osize, nsize); ++ if (l_unlikely(newblock == NULL && nsize > 0)) /* allocation failed? */ ++ luaM_error(L); ++ return newblock; ++} ++ ++ ++void *luaM_malloc_ (lua_State *L, size_t size, int tag) { ++ if (size == 0) ++ return NULL; /* that's all */ ++ else { ++ global_State *g = G(L); ++ void *newblock = firsttry(g, NULL, tag, size); ++ if (l_unlikely(newblock == NULL)) { ++ newblock = tryagain(L, NULL, tag, size); ++ if (newblock == NULL) ++ luaM_error(L); ++ } ++ g->GCdebt += size; ++ return newblock; ++ } ++} +diff --git a/src/bin/lua/lmem.h b/src/bin/lua/lmem.h +new file mode 100644 +index 0000000000..8c75a44beb +--- /dev/null ++++ b/src/bin/lua/lmem.h +@@ -0,0 +1,93 @@ ++/* ++** $Id: lmem.h $ ++** Interface to Memory Manager ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef lmem_h ++#define lmem_h ++ ++ ++#include ++ ++#include "llimits.h" ++#include "lua.h" ++ ++ ++#define luaM_error(L) luaD_throw(L, LUA_ERRMEM) ++ ++ ++/* ++** This macro tests whether it is safe to multiply 'n' by the size of ++** type 't' without overflows. Because 'e' is always constant, it avoids ++** the runtime division MAX_SIZET/(e). ++** (The macro is somewhat complex to avoid warnings: The 'sizeof' ++** comparison avoids a runtime comparison when overflow cannot occur. ++** The compiler should be able to optimize the real test by itself, but ++** when it does it, it may give a warning about "comparison is always ++** false due to limited range of data type"; the +1 tricks the compiler, ++** avoiding this warning but also this optimization.) ++*/ ++#define luaM_testsize(n,e) \ ++ (sizeof(n) >= sizeof(size_t) && cast_sizet((n)) + 1 > MAX_SIZET/(e)) ++ ++#define luaM_checksize(L,n,e) \ ++ (luaM_testsize(n,e) ? luaM_toobig(L) : cast_void(0)) ++ ++ ++/* ++** Computes the minimum between 'n' and 'MAX_SIZET/sizeof(t)', so that ++** the result is not larger than 'n' and cannot overflow a 'size_t' ++** when multiplied by the size of type 't'. (Assumes that 'n' is an ++** 'int' or 'unsigned int' and that 'int' is not larger than 'size_t'.) ++*/ ++#define luaM_limitN(n,t) \ ++ ((cast_sizet(n) <= MAX_SIZET/sizeof(t)) ? (n) : \ ++ cast_uint((MAX_SIZET/sizeof(t)))) ++ ++ ++/* ++** Arrays of chars do not need any test ++*/ ++#define luaM_reallocvchar(L,b,on,n) \ ++ cast_charp(luaM_saferealloc_(L, (b), (on)*sizeof(char), (n)*sizeof(char))) ++ ++#define luaM_freemem(L, b, s) luaM_free_(L, (b), (s)) ++#define luaM_free(L, b) luaM_free_(L, (b), sizeof(*(b))) ++#define luaM_freearray(L, b, n) luaM_free_(L, (b), (n)*sizeof(*(b))) ++ ++#define luaM_new(L,t) cast(t*, luaM_malloc_(L, sizeof(t), 0)) ++#define luaM_newvector(L,n,t) cast(t*, luaM_malloc_(L, (n)*sizeof(t), 0)) ++#define luaM_newvectorchecked(L,n,t) \ ++ (luaM_checksize(L,n,sizeof(t)), luaM_newvector(L,n,t)) ++ ++#define luaM_newobject(L,tag,s) luaM_malloc_(L, (s), tag) ++ ++#define luaM_growvector(L,v,nelems,size,t,limit,e) \ ++ ((v)=cast(t *, luaM_growaux_(L,v,nelems,&(size),sizeof(t), \ ++ luaM_limitN(limit,t),e))) ++ ++#define luaM_reallocvector(L, v,oldn,n,t) \ ++ (cast(t *, luaM_realloc_(L, v, cast_sizet(oldn) * sizeof(t), \ ++ cast_sizet(n) * sizeof(t)))) ++ ++#define luaM_shrinkvector(L,v,size,fs,t) \ ++ ((v)=cast(t *, luaM_shrinkvector_(L, v, &(size), fs, sizeof(t)))) ++ ++LUAI_FUNC l_noret luaM_toobig (lua_State *L); ++ ++/* not to be called directly */ ++LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize, ++ size_t size); ++LUAI_FUNC void *luaM_saferealloc_ (lua_State *L, void *block, size_t oldsize, ++ size_t size); ++LUAI_FUNC void luaM_free_ (lua_State *L, void *block, size_t osize); ++LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int nelems, ++ int *size, int size_elem, int limit, ++ const char *what); ++LUAI_FUNC void *luaM_shrinkvector_ (lua_State *L, void *block, int *nelem, ++ int final_n, int size_elem); ++LUAI_FUNC void *luaM_malloc_ (lua_State *L, size_t size, int tag); ++ ++#endif ++ +diff --git a/src/bin/lua/loadlib.c b/src/bin/lua/loadlib.c +new file mode 100644 +index 0000000000..6f9fa37366 +--- /dev/null ++++ b/src/bin/lua/loadlib.c +@@ -0,0 +1,762 @@ ++/* ++** $Id: loadlib.c $ ++** Dynamic library loader for Lua ++** See Copyright Notice in lua.h ++** ++** This module contains an implementation of loadlib for Unix systems ++** that have dlfcn, an implementation for Windows, and a stub for other ++** systems. ++*/ ++ ++#define loadlib_c ++#define LUA_LIB ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++#include ++ ++#include "lua.h" ++ ++#include "lauxlib.h" ++#include "lualib.h" ++ ++ ++/* ++** LUA_IGMARK is a mark to ignore all before it when building the ++** luaopen_ function name. ++*/ ++#if !defined (LUA_IGMARK) ++#define LUA_IGMARK "-" ++#endif ++ ++ ++/* ++** LUA_CSUBSEP is the character that replaces dots in submodule names ++** when searching for a C loader. ++** LUA_LSUBSEP is the character that replaces dots in submodule names ++** when searching for a Lua loader. ++*/ ++#if !defined(LUA_CSUBSEP) ++#define LUA_CSUBSEP LUA_DIRSEP ++#endif ++ ++#if !defined(LUA_LSUBSEP) ++#define LUA_LSUBSEP LUA_DIRSEP ++#endif ++ ++ ++/* prefix for open functions in C libraries */ ++#define LUA_POF "luaopen_" ++ ++/* separator for open functions in C libraries */ ++#define LUA_OFSEP "_" ++ ++ ++/* ++** key for table in the registry that keeps handles ++** for all loaded C libraries ++*/ ++static const char *const CLIBS = "_CLIBS"; ++ ++#define LIB_FAIL "open" ++ ++ ++#define setprogdir(L) ((void)0) ++ ++ ++/* ++** Special type equivalent to '(void*)' for functions in gcc ++** (to suppress warnings when converting function pointers) ++*/ ++typedef void (*voidf)(void); ++ ++ ++/* ++** system-dependent functions ++*/ ++ ++/* ++** unload library 'lib' ++*/ ++static void lsys_unloadlib (void *lib); ++ ++/* ++** load C library in file 'path'. If 'seeglb', load with all names in ++** the library global. ++** Returns the library; in case of error, returns NULL plus an ++** error string in the stack. ++*/ ++static void *lsys_load (lua_State *L, const char *path, int seeglb); ++ ++/* ++** Try to find a function named 'sym' in library 'lib'. ++** Returns the function; in case of error, returns NULL plus an ++** error string in the stack. ++*/ ++static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym); ++ ++ ++ ++ ++#if defined(LUA_USE_DLOPEN) /* { */ ++/* ++** {======================================================================== ++** This is an implementation of loadlib based on the dlfcn interface. ++** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD, ++** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least ++** as an emulation layer on top of native functions. ++** ========================================================================= ++*/ ++ ++#include ++ ++/* ++** Macro to convert pointer-to-void* to pointer-to-function. This cast ++** is undefined according to ISO C, but POSIX assumes that it works. ++** (The '__extension__' in gnu compilers is only to avoid warnings.) ++*/ ++#if defined(__GNUC__) ++#define cast_func(p) (__extension__ (lua_CFunction)(p)) ++#else ++#define cast_func(p) ((lua_CFunction)(p)) ++#endif ++ ++ ++static void lsys_unloadlib (void *lib) { ++ dlclose(lib); ++} ++ ++ ++static void *lsys_load (lua_State *L, const char *path, int seeglb) { ++ void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL)); ++ if (l_unlikely(lib == NULL)) ++ lua_pushstring(L, dlerror()); ++ return lib; ++} ++ ++ ++static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { ++ lua_CFunction f = cast_func(dlsym(lib, sym)); ++ if (l_unlikely(f == NULL)) ++ lua_pushstring(L, dlerror()); ++ return f; ++} ++ ++/* }====================================================== */ ++ ++ ++ ++#elif defined(LUA_DL_DLL) /* }{ */ ++/* ++** {====================================================================== ++** This is an implementation of loadlib for Windows using native functions. ++** ======================================================================= ++*/ ++ ++#include ++ ++ ++/* ++** optional flags for LoadLibraryEx ++*/ ++#if !defined(LUA_LLE_FLAGS) ++#define LUA_LLE_FLAGS 0 ++#endif ++ ++ ++#undef setprogdir ++ ++ ++/* ++** Replace in the path (on the top of the stack) any occurrence ++** of LUA_EXEC_DIR with the executable's path. ++*/ ++static void setprogdir (lua_State *L) { ++ char buff[MAX_PATH + 1]; ++ char *lb; ++ DWORD nsize = sizeof(buff)/sizeof(char); ++ DWORD n = GetModuleFileNameA(NULL, buff, nsize); /* get exec. name */ ++ if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL) ++ luaL_error(L, "unable to get ModuleFileName"); ++ else { ++ *lb = '\0'; /* cut name on the last '\\' to get the path */ ++ luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff); ++ lua_remove(L, -2); /* remove original string */ ++ } ++} ++ ++ ++ ++ ++static void pusherror (lua_State *L) { ++ int error = GetLastError(); ++ char buffer[128]; ++ if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, ++ NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL)) ++ lua_pushstring(L, buffer); ++ else ++ lua_pushfstring(L, "system error %d\n", error); ++} ++ ++static void lsys_unloadlib (void *lib) { ++ FreeLibrary((HMODULE)lib); ++} ++ ++ ++static void *lsys_load (lua_State *L, const char *path, int seeglb) { ++ HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS); ++ (void)(seeglb); /* not used: symbols are 'global' by default */ ++ if (lib == NULL) pusherror(L); ++ return lib; ++} ++ ++ ++static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { ++ lua_CFunction f = (lua_CFunction)(voidf)GetProcAddress((HMODULE)lib, sym); ++ if (f == NULL) pusherror(L); ++ return f; ++} ++ ++/* }====================================================== */ ++ ++ ++#else /* }{ */ ++/* ++** {====================================================== ++** Fallback for other systems ++** ======================================================= ++*/ ++ ++#undef LIB_FAIL ++#define LIB_FAIL "absent" ++ ++ ++#define DLMSG "dynamic libraries not enabled; check your Lua installation" ++ ++ ++static void lsys_unloadlib (void *lib) { ++ (void)(lib); /* not used */ ++} ++ ++ ++static void *lsys_load (lua_State *L, const char *path, int seeglb) { ++ (void)(path); (void)(seeglb); /* not used */ ++ lua_pushliteral(L, DLMSG); ++ return NULL; ++} ++ ++ ++static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { ++ (void)(lib); (void)(sym); /* not used */ ++ lua_pushliteral(L, DLMSG); ++ return NULL; ++} ++ ++/* }====================================================== */ ++#endif /* } */ ++ ++ ++/* ++** {================================================================== ++** Set Paths ++** =================================================================== ++*/ ++ ++/* ++** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment ++** variables that Lua check to set its paths. ++*/ ++#if !defined(LUA_PATH_VAR) ++#define LUA_PATH_VAR "LUA_PATH" ++#endif ++ ++#if !defined(LUA_CPATH_VAR) ++#define LUA_CPATH_VAR "LUA_CPATH" ++#endif ++ ++ ++ ++/* ++** return registry.LUA_NOENV as a boolean ++*/ ++static int noenv (lua_State *L) { ++ int b; ++ lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); ++ b = lua_toboolean(L, -1); ++ lua_pop(L, 1); /* remove value */ ++ return b; ++} ++ ++ ++/* ++** Set a path ++*/ ++static void setpath (lua_State *L, const char *fieldname, ++ const char *envname, ++ const char *dft) { ++ const char *dftmark; ++ const char *nver = lua_pushfstring(L, "%s%s", envname, LUA_VERSUFFIX); ++ const char *path = getenv(nver); /* try versioned name */ ++ if (path == NULL) /* no versioned environment variable? */ ++ path = getenv(envname); /* try unversioned name */ ++ if (path == NULL || noenv(L)) /* no environment variable? */ ++ lua_pushstring(L, dft); /* use default */ ++ else if ((dftmark = strstr(path, LUA_PATH_SEP LUA_PATH_SEP)) == NULL) ++ lua_pushstring(L, path); /* nothing to change */ ++ else { /* path contains a ";;": insert default path in its place */ ++ size_t len = strlen(path); ++ luaL_Buffer b; ++ luaL_buffinit(L, &b); ++ if (path < dftmark) { /* is there a prefix before ';;'? */ ++ luaL_addlstring(&b, path, dftmark - path); /* add it */ ++ luaL_addchar(&b, *LUA_PATH_SEP); ++ } ++ luaL_addstring(&b, dft); /* add default */ ++ if (dftmark < path + len - 2) { /* is there a suffix after ';;'? */ ++ luaL_addchar(&b, *LUA_PATH_SEP); ++ luaL_addlstring(&b, dftmark + 2, (path + len - 2) - dftmark); ++ } ++ luaL_pushresult(&b); ++ } ++ setprogdir(L); ++ lua_setfield(L, -3, fieldname); /* package[fieldname] = path value */ ++ lua_pop(L, 1); /* pop versioned variable name ('nver') */ ++} ++ ++/* }================================================================== */ ++ ++ ++/* ++** return registry.CLIBS[path] ++*/ ++static void *checkclib (lua_State *L, const char *path) { ++ void *plib; ++ lua_getfield(L, LUA_REGISTRYINDEX, CLIBS); ++ lua_getfield(L, -1, path); ++ plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */ ++ lua_pop(L, 2); /* pop CLIBS table and 'plib' */ ++ return plib; ++} ++ ++ ++/* ++** registry.CLIBS[path] = plib -- for queries ++** registry.CLIBS[#CLIBS + 1] = plib -- also keep a list of all libraries ++*/ ++static void addtoclib (lua_State *L, const char *path, void *plib) { ++ lua_getfield(L, LUA_REGISTRYINDEX, CLIBS); ++ lua_pushlightuserdata(L, plib); ++ lua_pushvalue(L, -1); ++ lua_setfield(L, -3, path); /* CLIBS[path] = plib */ ++ lua_rawseti(L, -2, luaL_len(L, -2) + 1); /* CLIBS[#CLIBS + 1] = plib */ ++ lua_pop(L, 1); /* pop CLIBS table */ ++} ++ ++ ++/* ++** __gc tag method for CLIBS table: calls 'lsys_unloadlib' for all lib ++** handles in list CLIBS ++*/ ++static int gctm (lua_State *L) { ++ lua_Integer n = luaL_len(L, 1); ++ for (; n >= 1; n--) { /* for each handle, in reverse order */ ++ lua_rawgeti(L, 1, n); /* get handle CLIBS[n] */ ++ lsys_unloadlib(lua_touserdata(L, -1)); ++ lua_pop(L, 1); /* pop handle */ ++ } ++ return 0; ++} ++ ++ ++ ++/* error codes for 'lookforfunc' */ ++#define ERRLIB 1 ++#define ERRFUNC 2 ++ ++/* ++** Look for a C function named 'sym' in a dynamically loaded library ++** 'path'. ++** First, check whether the library is already loaded; if not, try ++** to load it. ++** Then, if 'sym' is '*', return true (as library has been loaded). ++** Otherwise, look for symbol 'sym' in the library and push a ++** C function with that symbol. ++** Return 0 and 'true' or a function in the stack; in case of ++** errors, return an error code and an error message in the stack. ++*/ ++static int lookforfunc (lua_State *L, const char *path, const char *sym) { ++ void *reg = checkclib(L, path); /* check loaded C libraries */ ++ if (reg == NULL) { /* must load library? */ ++ reg = lsys_load(L, path, *sym == '*'); /* global symbols if 'sym'=='*' */ ++ if (reg == NULL) return ERRLIB; /* unable to load library */ ++ addtoclib(L, path, reg); ++ } ++ if (*sym == '*') { /* loading only library (no function)? */ ++ lua_pushboolean(L, 1); /* return 'true' */ ++ return 0; /* no errors */ ++ } ++ else { ++ lua_CFunction f = lsys_sym(L, reg, sym); ++ if (f == NULL) ++ return ERRFUNC; /* unable to find function */ ++ lua_pushcfunction(L, f); /* else create new function */ ++ return 0; /* no errors */ ++ } ++} ++ ++ ++static int ll_loadlib (lua_State *L) { ++ const char *path = luaL_checkstring(L, 1); ++ const char *init = luaL_checkstring(L, 2); ++ int stat = lookforfunc(L, path, init); ++ if (l_likely(stat == 0)) /* no errors? */ ++ return 1; /* return the loaded function */ ++ else { /* error; error message is on stack top */ ++ luaL_pushfail(L); ++ lua_insert(L, -2); ++ lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init"); ++ return 3; /* return fail, error message, and where */ ++ } ++} ++ ++ ++ ++/* ++** {====================================================== ++** 'require' function ++** ======================================================= ++*/ ++ ++ ++static int readable (const char *filename) { ++ FILE *f = fopen(filename, "r"); /* try to open file */ ++ if (f == NULL) return 0; /* open failed */ ++ fclose(f); ++ return 1; ++} ++ ++ ++/* ++** Get the next name in '*path' = 'name1;name2;name3;...', changing ++** the ending ';' to '\0' to create a zero-terminated string. Return ++** NULL when list ends. ++*/ ++static const char *getnextfilename (char **path, char *end) { ++ char *sep; ++ char *name = *path; ++ if (name == end) ++ return NULL; /* no more names */ ++ else if (*name == '\0') { /* from previous iteration? */ ++ *name = *LUA_PATH_SEP; /* restore separator */ ++ name++; /* skip it */ ++ } ++ sep = strchr(name, *LUA_PATH_SEP); /* find next separator */ ++ if (sep == NULL) /* separator not found? */ ++ sep = end; /* name goes until the end */ ++ *sep = '\0'; /* finish file name */ ++ *path = sep; /* will start next search from here */ ++ return name; ++} ++ ++ ++/* ++** Given a path such as ";blabla.so;blublu.so", pushes the string ++** ++** no file 'blabla.so' ++** no file 'blublu.so' ++*/ ++static void pusherrornotfound (lua_State *L, const char *path) { ++ luaL_Buffer b; ++ luaL_buffinit(L, &b); ++ luaL_addstring(&b, "no file '"); ++ luaL_addgsub(&b, path, LUA_PATH_SEP, "'\n\tno file '"); ++ luaL_addstring(&b, "'"); ++ luaL_pushresult(&b); ++} ++ ++ ++static const char *searchpath (lua_State *L, const char *name, ++ const char *path, ++ const char *sep, ++ const char *dirsep) { ++ luaL_Buffer buff; ++ char *pathname; /* path with name inserted */ ++ char *endpathname; /* its end */ ++ const char *filename; ++ /* separator is non-empty and appears in 'name'? */ ++ if (*sep != '\0' && strchr(name, *sep) != NULL) ++ name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */ ++ luaL_buffinit(L, &buff); ++ /* add path to the buffer, replacing marks ('?') with the file name */ ++ luaL_addgsub(&buff, path, LUA_PATH_MARK, name); ++ luaL_addchar(&buff, '\0'); ++ pathname = luaL_buffaddr(&buff); /* writable list of file names */ ++ endpathname = pathname + luaL_bufflen(&buff) - 1; ++ while ((filename = getnextfilename(&pathname, endpathname)) != NULL) { ++ if (readable(filename)) /* does file exist and is readable? */ ++ return lua_pushstring(L, filename); /* save and return name */ ++ } ++ luaL_pushresult(&buff); /* push path to create error message */ ++ pusherrornotfound(L, lua_tostring(L, -1)); /* create error message */ ++ return NULL; /* not found */ ++} ++ ++ ++static int ll_searchpath (lua_State *L) { ++ const char *f = searchpath(L, luaL_checkstring(L, 1), ++ luaL_checkstring(L, 2), ++ luaL_optstring(L, 3, "."), ++ luaL_optstring(L, 4, LUA_DIRSEP)); ++ if (f != NULL) return 1; ++ else { /* error message is on top of the stack */ ++ luaL_pushfail(L); ++ lua_insert(L, -2); ++ return 2; /* return fail + error message */ ++ } ++} ++ ++ ++static const char *findfile (lua_State *L, const char *name, ++ const char *pname, ++ const char *dirsep) { ++ const char *path; ++ lua_getfield(L, lua_upvalueindex(1), pname); ++ path = lua_tostring(L, -1); ++ if (l_unlikely(path == NULL)) ++ luaL_error(L, "'package.%s' must be a string", pname); ++ return searchpath(L, name, path, ".", dirsep); ++} ++ ++ ++static int checkload (lua_State *L, int stat, const char *filename) { ++ if (l_likely(stat)) { /* module loaded successfully? */ ++ lua_pushstring(L, filename); /* will be 2nd argument to module */ ++ return 2; /* return open function and file name */ ++ } ++ else ++ return luaL_error(L, "error loading module '%s' from file '%s':\n\t%s", ++ lua_tostring(L, 1), filename, lua_tostring(L, -1)); ++} ++ ++ ++static int searcher_Lua (lua_State *L) { ++ const char *filename; ++ const char *name = luaL_checkstring(L, 1); ++ filename = findfile(L, name, "path", LUA_LSUBSEP); ++ if (filename == NULL) return 1; /* module not found in this path */ ++ return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename); ++} ++ ++ ++/* ++** Try to find a load function for module 'modname' at file 'filename'. ++** First, change '.' to '_' in 'modname'; then, if 'modname' has ++** the form X-Y (that is, it has an "ignore mark"), build a function ++** name "luaopen_X" and look for it. (For compatibility, if that ++** fails, it also tries "luaopen_Y".) If there is no ignore mark, ++** look for a function named "luaopen_modname". ++*/ ++static int loadfunc (lua_State *L, const char *filename, const char *modname) { ++ const char *openfunc; ++ const char *mark; ++ modname = luaL_gsub(L, modname, ".", LUA_OFSEP); ++ mark = strchr(modname, *LUA_IGMARK); ++ if (mark) { ++ int stat; ++ openfunc = lua_pushlstring(L, modname, mark - modname); ++ openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc); ++ stat = lookforfunc(L, filename, openfunc); ++ if (stat != ERRFUNC) return stat; ++ modname = mark + 1; /* else go ahead and try old-style name */ ++ } ++ openfunc = lua_pushfstring(L, LUA_POF"%s", modname); ++ return lookforfunc(L, filename, openfunc); ++} ++ ++ ++static int searcher_C (lua_State *L) { ++ const char *name = luaL_checkstring(L, 1); ++ const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP); ++ if (filename == NULL) return 1; /* module not found in this path */ ++ return checkload(L, (loadfunc(L, filename, name) == 0), filename); ++} ++ ++ ++static int searcher_Croot (lua_State *L) { ++ const char *filename; ++ const char *name = luaL_checkstring(L, 1); ++ const char *p = strchr(name, '.'); ++ int stat; ++ if (p == NULL) return 0; /* is root */ ++ lua_pushlstring(L, name, p - name); ++ filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP); ++ if (filename == NULL) return 1; /* root not found */ ++ if ((stat = loadfunc(L, filename, name)) != 0) { ++ if (stat != ERRFUNC) ++ return checkload(L, 0, filename); /* real error */ ++ else { /* open function not found */ ++ lua_pushfstring(L, "no module '%s' in file '%s'", name, filename); ++ return 1; ++ } ++ } ++ lua_pushstring(L, filename); /* will be 2nd argument to module */ ++ return 2; ++} ++ ++ ++static int searcher_preload (lua_State *L) { ++ const char *name = luaL_checkstring(L, 1); ++ lua_getfield(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); ++ if (lua_getfield(L, -1, name) == LUA_TNIL) { /* not found? */ ++ lua_pushfstring(L, "no field package.preload['%s']", name); ++ return 1; ++ } ++ else { ++ lua_pushliteral(L, ":preload:"); ++ return 2; ++ } ++} ++ ++ ++static void findloader (lua_State *L, const char *name) { ++ int i; ++ luaL_Buffer msg; /* to build error message */ ++ /* push 'package.searchers' to index 3 in the stack */ ++ if (l_unlikely(lua_getfield(L, lua_upvalueindex(1), "searchers") ++ != LUA_TTABLE)) ++ luaL_error(L, "'package.searchers' must be a table"); ++ luaL_buffinit(L, &msg); ++ /* iterate over available searchers to find a loader */ ++ for (i = 1; ; i++) { ++ luaL_addstring(&msg, "\n\t"); /* error-message prefix */ ++ if (l_unlikely(lua_rawgeti(L, 3, i) == LUA_TNIL)) { /* no more searchers? */ ++ lua_pop(L, 1); /* remove nil */ ++ luaL_buffsub(&msg, 2); /* remove prefix */ ++ luaL_pushresult(&msg); /* create error message */ ++ luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1)); ++ } ++ lua_pushstring(L, name); ++ lua_call(L, 1, 2); /* call it */ ++ if (lua_isfunction(L, -2)) /* did it find a loader? */ ++ return; /* module loader found */ ++ else if (lua_isstring(L, -2)) { /* searcher returned error message? */ ++ lua_pop(L, 1); /* remove extra return */ ++ luaL_addvalue(&msg); /* concatenate error message */ ++ } ++ else { /* no error message */ ++ lua_pop(L, 2); /* remove both returns */ ++ luaL_buffsub(&msg, 2); /* remove prefix */ ++ } ++ } ++} ++ ++ ++static int ll_require (lua_State *L) { ++ const char *name = luaL_checkstring(L, 1); ++ lua_settop(L, 1); /* LOADED table will be at index 2 */ ++ lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); ++ lua_getfield(L, 2, name); /* LOADED[name] */ ++ if (lua_toboolean(L, -1)) /* is it there? */ ++ return 1; /* package is already loaded */ ++ /* else must load package */ ++ lua_pop(L, 1); /* remove 'getfield' result */ ++ findloader(L, name); ++ lua_rotate(L, -2, 1); /* function <-> loader data */ ++ lua_pushvalue(L, 1); /* name is 1st argument to module loader */ ++ lua_pushvalue(L, -3); /* loader data is 2nd argument */ ++ /* stack: ...; loader data; loader function; mod. name; loader data */ ++ lua_call(L, 2, 1); /* run loader to load module */ ++ /* stack: ...; loader data; result from loader */ ++ if (!lua_isnil(L, -1)) /* non-nil return? */ ++ lua_setfield(L, 2, name); /* LOADED[name] = returned value */ ++ else ++ lua_pop(L, 1); /* pop nil */ ++ if (lua_getfield(L, 2, name) == LUA_TNIL) { /* module set no value? */ ++ lua_pushboolean(L, 1); /* use true as result */ ++ lua_copy(L, -1, -2); /* replace loader result */ ++ lua_setfield(L, 2, name); /* LOADED[name] = true */ ++ } ++ lua_rotate(L, -2, 1); /* loader data <-> module result */ ++ return 2; /* return module result and loader data */ ++} ++ ++/* }====================================================== */ ++ ++ ++ ++ ++static const luaL_Reg pk_funcs[] = { ++ {"loadlib", ll_loadlib}, ++ {"searchpath", ll_searchpath}, ++ /* placeholders */ ++ {"preload", NULL}, ++ {"cpath", NULL}, ++ {"path", NULL}, ++ {"searchers", NULL}, ++ {"loaded", NULL}, ++ {NULL, NULL} ++}; ++ ++ ++static const luaL_Reg ll_funcs[] = { ++ {"require", ll_require}, ++ {NULL, NULL} ++}; ++ ++ ++static void createsearcherstable (lua_State *L) { ++ static const lua_CFunction searchers[] = ++ {searcher_preload, searcher_Lua, searcher_C, searcher_Croot, NULL}; ++ int i; ++ /* create 'searchers' table */ ++ lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0); ++ /* fill it with predefined searchers */ ++ for (i=0; searchers[i] != NULL; i++) { ++ lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */ ++ lua_pushcclosure(L, searchers[i], 1); ++ lua_rawseti(L, -2, i+1); ++ } ++ lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */ ++} ++ ++ ++/* ++** create table CLIBS to keep track of loaded C libraries, ++** setting a finalizer to close all libraries when closing state. ++*/ ++static void createclibstable (lua_State *L) { ++ luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS); /* create CLIBS table */ ++ lua_createtable(L, 0, 1); /* create metatable for CLIBS */ ++ lua_pushcfunction(L, gctm); ++ lua_setfield(L, -2, "__gc"); /* set finalizer for CLIBS table */ ++ lua_setmetatable(L, -2); ++} ++ ++ ++LUAMOD_API int luaopen_package (lua_State *L) { ++ createclibstable(L); ++ luaL_newlib(L, pk_funcs); /* create 'package' table */ ++ createsearcherstable(L); ++ /* set paths */ ++ setpath(L, "path", LUA_PATH_VAR, LUA_PATH_DEFAULT); ++ setpath(L, "cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT); ++ /* store config information */ ++ lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n" ++ LUA_EXEC_DIR "\n" LUA_IGMARK "\n"); ++ lua_setfield(L, -2, "config"); ++ /* set field 'loaded' */ ++ luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); ++ lua_setfield(L, -2, "loaded"); ++ /* set field 'preload' */ ++ luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); ++ lua_setfield(L, -2, "preload"); ++ lua_pushglobaltable(L); ++ lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */ ++ luaL_setfuncs(L, ll_funcs, 1); /* open lib into global table */ ++ lua_pop(L, 1); /* pop global table */ ++ return 1; /* return 'package' table */ ++} ++ +diff --git a/src/bin/lua/lobject.c b/src/bin/lua/lobject.c +new file mode 100644 +index 0000000000..0e504be03e +--- /dev/null ++++ b/src/bin/lua/lobject.c +@@ -0,0 +1,592 @@ ++/* ++** $Id: lobject.c $ ++** Some generic functions over Lua objects ++** See Copyright Notice in lua.h ++*/ ++ ++#define lobject_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "lua.h" ++ ++#include "lctype.h" ++#include "ldebug.h" ++#include "ldo.h" ++#include "lmem.h" ++#include "lobject.h" ++#include "lstate.h" ++#include "lstring.h" ++#include "lvm.h" ++ ++ ++/* ++** Computes ceil(log2(x)) ++*/ ++int luaO_ceillog2 (unsigned int x) { ++ static const lu_byte log_2[256] = { /* log_2[i] = ceil(log2(i - 1)) */ ++ 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, ++ 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, ++ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, ++ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, ++ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, ++ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, ++ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, ++ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8 ++ }; ++ int l = 0; ++ x--; ++ while (x >= 256) { l += 8; x >>= 8; } ++ return l + log_2[x]; ++} ++ ++ ++static lua_Integer intarith (lua_State *L, int op, lua_Integer v1, ++ lua_Integer v2) { ++ switch (op) { ++ case LUA_OPADD: return intop(+, v1, v2); ++ case LUA_OPSUB:return intop(-, v1, v2); ++ case LUA_OPMUL:return intop(*, v1, v2); ++ case LUA_OPMOD: return luaV_mod(L, v1, v2); ++ case LUA_OPIDIV: return luaV_idiv(L, v1, v2); ++ case LUA_OPBAND: return intop(&, v1, v2); ++ case LUA_OPBOR: return intop(|, v1, v2); ++ case LUA_OPBXOR: return intop(^, v1, v2); ++ case LUA_OPSHL: return luaV_shiftl(v1, v2); ++ case LUA_OPSHR: return luaV_shiftl(v1, -v2); ++ case LUA_OPUNM: return intop(-, 0, v1); ++ case LUA_OPBNOT: return intop(^, ~l_castS2U(0), v1); ++ default: lua_assert(0); return 0; ++ } ++} ++ ++ ++static lua_Number numarith (lua_State *L, int op, lua_Number v1, ++ lua_Number v2) { ++ switch (op) { ++ case LUA_OPADD: return luai_numadd(L, v1, v2); ++ case LUA_OPSUB: return luai_numsub(L, v1, v2); ++ case LUA_OPMUL: return luai_nummul(L, v1, v2); ++ case LUA_OPDIV: return luai_numdiv(L, v1, v2); ++ case LUA_OPPOW: return luai_numpow(L, v1, v2); ++ case LUA_OPIDIV: return luai_numidiv(L, v1, v2); ++ case LUA_OPUNM: return luai_numunm(L, v1); ++ case LUA_OPMOD: return luaV_modf(L, v1, v2); ++ default: lua_assert(0); return 0; ++ } ++} ++ ++ ++int luaO_rawarith (lua_State *L, int op, const TValue *p1, const TValue *p2, ++ TValue *res) { ++ switch (op) { ++ case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR: ++ case LUA_OPSHL: case LUA_OPSHR: ++ case LUA_OPBNOT: { /* operate only on integers */ ++ lua_Integer i1; lua_Integer i2; ++ if (tointegerns(p1, &i1) && tointegerns(p2, &i2)) { ++ setivalue(res, intarith(L, op, i1, i2)); ++ return 1; ++ } ++ else return 0; /* fail */ ++ } ++ case LUA_OPDIV: case LUA_OPPOW: { /* operate only on floats */ ++ lua_Number n1; lua_Number n2; ++ if (tonumberns(p1, n1) && tonumberns(p2, n2)) { ++ setfltvalue(res, numarith(L, op, n1, n2)); ++ return 1; ++ } ++ else return 0; /* fail */ ++ } ++ default: { /* other operations */ ++ lua_Number n1; lua_Number n2; ++ if (ttisinteger(p1) && ttisinteger(p2)) { ++ setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2))); ++ return 1; ++ } ++ else if (tonumberns(p1, n1) && tonumberns(p2, n2)) { ++ setfltvalue(res, numarith(L, op, n1, n2)); ++ return 1; ++ } ++ else return 0; /* fail */ ++ } ++ } ++} ++ ++ ++void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2, ++ StkId res) { ++ if (!luaO_rawarith(L, op, p1, p2, s2v(res))) { ++ /* could not perform raw operation; try metamethod */ ++ luaT_trybinTM(L, p1, p2, res, cast(TMS, (op - LUA_OPADD) + TM_ADD)); ++ } ++} ++ ++ ++int luaO_hexavalue (int c) { ++ if (lisdigit(c)) return c - '0'; ++ else return (ltolower(c) - 'a') + 10; ++} ++ ++ ++static int isneg (const char **s) { ++ if (**s == '-') { (*s)++; return 1; } ++ else if (**s == '+') (*s)++; ++ return 0; ++} ++ ++ ++ ++/* ++** {================================================================== ++** Lua's implementation for 'lua_strx2number' ++** =================================================================== ++*/ ++ ++#if !defined(lua_strx2number) ++ ++/* maximum number of significant digits to read (to avoid overflows ++ even with single floats) */ ++#define MAXSIGDIG 30 ++ ++/* ++** convert a hexadecimal numeric string to a number, following ++** C99 specification for 'strtod' ++*/ ++static lua_Number lua_strx2number (const char *s, char **endptr) { ++ int dot = lua_getlocaledecpoint(); ++ lua_Number r = 0.0; /* result (accumulator) */ ++ int sigdig = 0; /* number of significant digits */ ++ int nosigdig = 0; /* number of non-significant digits */ ++ int e = 0; /* exponent correction */ ++ int neg; /* 1 if number is negative */ ++ int hasdot = 0; /* true after seen a dot */ ++ *endptr = cast_charp(s); /* nothing is valid yet */ ++ while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */ ++ neg = isneg(&s); /* check sign */ ++ if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */ ++ return 0.0; /* invalid format (no '0x') */ ++ for (s += 2; ; s++) { /* skip '0x' and read numeral */ ++ if (*s == dot) { ++ if (hasdot) break; /* second dot? stop loop */ ++ else hasdot = 1; ++ } ++ else if (lisxdigit(cast_uchar(*s))) { ++ if (sigdig == 0 && *s == '0') /* non-significant digit (zero)? */ ++ nosigdig++; ++ else if (++sigdig <= MAXSIGDIG) /* can read it without overflow? */ ++ r = (r * cast_num(16.0)) + luaO_hexavalue(*s); ++ else e++; /* too many digits; ignore, but still count for exponent */ ++ if (hasdot) e--; /* decimal digit? correct exponent */ ++ } ++ else break; /* neither a dot nor a digit */ ++ } ++ if (nosigdig + sigdig == 0) /* no digits? */ ++ return 0.0; /* invalid format */ ++ *endptr = cast_charp(s); /* valid up to here */ ++ e *= 4; /* each digit multiplies/divides value by 2^4 */ ++ if (*s == 'p' || *s == 'P') { /* exponent part? */ ++ int exp1 = 0; /* exponent value */ ++ int neg1; /* exponent sign */ ++ s++; /* skip 'p' */ ++ neg1 = isneg(&s); /* sign */ ++ if (!lisdigit(cast_uchar(*s))) ++ return 0.0; /* invalid; must have at least one digit */ ++ while (lisdigit(cast_uchar(*s))) /* read exponent */ ++ exp1 = exp1 * 10 + *(s++) - '0'; ++ if (neg1) exp1 = -exp1; ++ e += exp1; ++ *endptr = cast_charp(s); /* valid up to here */ ++ } ++ if (neg) r = -r; ++ return l_mathop(ldexp)(r, e); ++} ++ ++#endif ++/* }====================================================== */ ++ ++ ++/* maximum length of a numeral to be converted to a number */ ++#if !defined (L_MAXLENNUM) ++#define L_MAXLENNUM 200 ++#endif ++ ++/* ++** Convert string 's' to a Lua number (put in 'result'). Return NULL on ++** fail or the address of the ending '\0' on success. ('mode' == 'x') ++** means a hexadecimal numeral. ++*/ ++static const char *l_str2dloc (const char *s, lua_Number *result, int mode) { ++ char *endptr; ++ *result = (mode == 'x') ? lua_strx2number(s, &endptr) /* try to convert */ ++ : lua_str2number(s, &endptr); ++ if (endptr == s) return NULL; /* nothing recognized? */ ++ while (lisspace(cast_uchar(*endptr))) endptr++; /* skip trailing spaces */ ++ return (*endptr == '\0') ? endptr : NULL; /* OK iff no trailing chars */ ++} ++ ++ ++/* ++** Convert string 's' to a Lua number (put in 'result') handling the ++** current locale. ++** This function accepts both the current locale or a dot as the radix ++** mark. If the conversion fails, it may mean number has a dot but ++** locale accepts something else. In that case, the code copies 's' ++** to a buffer (because 's' is read-only), changes the dot to the ++** current locale radix mark, and tries to convert again. ++** The variable 'mode' checks for special characters in the string: ++** - 'n' means 'inf' or 'nan' (which should be rejected) ++** - 'x' means a hexadecimal numeral ++** - '.' just optimizes the search for the common case (no special chars) ++*/ ++static const char *l_str2d (const char *s, lua_Number *result) { ++ const char *endptr; ++ const char *pmode = strpbrk(s, ".xXnN"); /* look for special chars */ ++ int mode = pmode ? ltolower(cast_uchar(*pmode)) : 0; ++ if (mode == 'n') /* reject 'inf' and 'nan' */ ++ return NULL; ++ endptr = l_str2dloc(s, result, mode); /* try to convert */ ++ if (endptr == NULL) { /* failed? may be a different locale */ ++ char buff[L_MAXLENNUM + 1]; ++ const char *pdot = strchr(s, '.'); ++ if (pdot == NULL || strlen(s) > L_MAXLENNUM) ++ return NULL; /* string too long or no dot; fail */ ++ strcpy(buff, s); /* copy string to buffer */ ++ buff[pdot - s] = lua_getlocaledecpoint(); /* correct decimal point */ ++ endptr = l_str2dloc(buff, result, mode); /* try again */ ++ if (endptr != NULL) ++ endptr = s + (endptr - buff); /* make relative to 's' */ ++ } ++ return endptr; ++} ++ ++ ++#define MAXBY10 cast(lua_Unsigned, LUA_MAXINTEGER / 10) ++#define MAXLASTD cast_int(LUA_MAXINTEGER % 10) ++ ++static const char *l_str2int (const char *s, lua_Integer *result) { ++ lua_Unsigned a = 0; ++ int empty = 1; ++ int neg; ++ while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */ ++ neg = isneg(&s); ++ if (s[0] == '0' && ++ (s[1] == 'x' || s[1] == 'X')) { /* hex? */ ++ s += 2; /* skip '0x' */ ++ for (; lisxdigit(cast_uchar(*s)); s++) { ++ a = a * 16 + luaO_hexavalue(*s); ++ empty = 0; ++ } ++ } ++ else { /* decimal */ ++ for (; lisdigit(cast_uchar(*s)); s++) { ++ int d = *s - '0'; ++ if (a >= MAXBY10 && (a > MAXBY10 || d > MAXLASTD + neg)) /* overflow? */ ++ return NULL; /* do not accept it (as integer) */ ++ a = a * 10 + d; ++ empty = 0; ++ } ++ } ++ while (lisspace(cast_uchar(*s))) s++; /* skip trailing spaces */ ++ if (empty || *s != '\0') return NULL; /* something wrong in the numeral */ ++ else { ++ *result = l_castU2S((neg) ? 0u - a : a); ++ return s; ++ } ++} ++ ++ ++size_t luaO_str2num (const char *s, TValue *o) { ++ lua_Integer i; lua_Number n; ++ const char *e; ++ if ((e = l_str2int(s, &i)) != NULL) { /* try as an integer */ ++ setivalue(o, i); ++ } ++ else if ((e = l_str2d(s, &n)) != NULL) { /* else try as a float */ ++ setfltvalue(o, n); ++ } ++ else ++ return 0; /* conversion failed */ ++ return (e - s) + 1; /* success; return string size */ ++} ++ ++ ++int luaO_utf8esc (char *buff, unsigned long x) { ++ int n = 1; /* number of bytes put in buffer (backwards) */ ++ lua_assert(x <= 0x7FFFFFFFu); ++ if (x < 0x80) /* ascii? */ ++ buff[UTF8BUFFSZ - 1] = cast_char(x); ++ else { /* need continuation bytes */ ++ unsigned int mfb = 0x3f; /* maximum that fits in first byte */ ++ do { /* add continuation bytes */ ++ buff[UTF8BUFFSZ - (n++)] = cast_char(0x80 | (x & 0x3f)); ++ x >>= 6; /* remove added bits */ ++ mfb >>= 1; /* now there is one less bit available in first byte */ ++ } while (x > mfb); /* still needs continuation byte? */ ++ buff[UTF8BUFFSZ - n] = cast_char((~mfb << 1) | x); /* add first byte */ ++ } ++ return n; ++} ++ ++ ++/* ++** Maximum length of the conversion of a number to a string. Must be ++** enough to accommodate both LUA_INTEGER_FMT and LUA_NUMBER_FMT. ++** (For a long long int, this is 19 digits plus a sign and a final '\0', ++** adding to 21. For a long double, it can go to a sign, 33 digits, ++** the dot, an exponent letter, an exponent sign, 5 exponent digits, ++** and a final '\0', adding to 43.) ++*/ ++#define MAXNUMBER2STR 44 ++ ++ ++/* ++** Convert a number object to a string, adding it to a buffer ++*/ ++static int tostringbuff (TValue *obj, char *buff) { ++ int len; ++ lua_assert(ttisnumber(obj)); ++ if (ttisinteger(obj)) ++ len = lua_integer2str(buff, MAXNUMBER2STR, ivalue(obj)); ++ else { ++ len = lua_number2str(buff, MAXNUMBER2STR, fltvalue(obj)); ++ if (buff[strspn(buff, "-0123456789")] == '\0') { /* looks like an int? */ ++ buff[len++] = lua_getlocaledecpoint(); ++ buff[len++] = '0'; /* adds '.0' to result */ ++ } ++ } ++ return len; ++} ++ ++ ++/* ++** Convert a number object to a Lua string, replacing the value at 'obj' ++*/ ++void luaO_tostring (lua_State *L, TValue *obj) { ++ char buff[MAXNUMBER2STR]; ++ int len = tostringbuff(obj, buff); ++ setsvalue(L, obj, luaS_newlstr(L, buff, len)); ++} ++ ++ ++ ++ ++/* ++** {================================================================== ++** 'luaO_pushvfstring' ++** =================================================================== ++*/ ++ ++/* size for buffer space used by 'luaO_pushvfstring' */ ++#define BUFVFS 200 ++ ++/* buffer used by 'luaO_pushvfstring' */ ++typedef struct BuffFS { ++ lua_State *L; ++ int pushed; /* number of string pieces already on the stack */ ++ int blen; /* length of partial string in 'space' */ ++ char space[BUFVFS]; /* holds last part of the result */ ++} BuffFS; ++ ++ ++/* ++** Push given string to the stack, as part of the buffer, and ++** join the partial strings in the stack into one. ++*/ ++static void pushstr (BuffFS *buff, const char *str, size_t l) { ++ lua_State *L = buff->L; ++ setsvalue2s(L, L->top, luaS_newlstr(L, str, l)); ++ L->top++; /* may use one extra slot */ ++ buff->pushed++; ++ luaV_concat(L, buff->pushed); /* join partial results into one */ ++ buff->pushed = 1; ++} ++ ++ ++/* ++** empty the buffer space into the stack ++*/ ++static void clearbuff (BuffFS *buff) { ++ pushstr(buff, buff->space, buff->blen); /* push buffer contents */ ++ buff->blen = 0; /* space now is empty */ ++} ++ ++ ++/* ++** Get a space of size 'sz' in the buffer. If buffer has not enough ++** space, empty it. 'sz' must fit in an empty buffer. ++*/ ++static char *getbuff (BuffFS *buff, int sz) { ++ lua_assert(buff->blen <= BUFVFS); lua_assert(sz <= BUFVFS); ++ if (sz > BUFVFS - buff->blen) /* not enough space? */ ++ clearbuff(buff); ++ return buff->space + buff->blen; ++} ++ ++ ++#define addsize(b,sz) ((b)->blen += (sz)) ++ ++ ++/* ++** Add 'str' to the buffer. If string is larger than the buffer space, ++** push the string directly to the stack. ++*/ ++static void addstr2buff (BuffFS *buff, const char *str, size_t slen) { ++ if (slen <= BUFVFS) { /* does string fit into buffer? */ ++ char *bf = getbuff(buff, cast_int(slen)); ++ memcpy(bf, str, slen); /* add string to buffer */ ++ addsize(buff, cast_int(slen)); ++ } ++ else { /* string larger than buffer */ ++ clearbuff(buff); /* string comes after buffer's content */ ++ pushstr(buff, str, slen); /* push string */ ++ } ++} ++ ++ ++/* ++** Add a number to the buffer. ++*/ ++static void addnum2buff (BuffFS *buff, TValue *num) { ++ char *numbuff = getbuff(buff, MAXNUMBER2STR); ++ int len = tostringbuff(num, numbuff); /* format number into 'numbuff' */ ++ addsize(buff, len); ++} ++ ++ ++/* ++** this function handles only '%d', '%c', '%f', '%p', '%s', and '%%' ++ conventional formats, plus Lua-specific '%I' and '%U' ++*/ ++const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { ++ BuffFS buff; /* holds last part of the result */ ++ const char *e; /* points to next '%' */ ++ buff.pushed = buff.blen = 0; ++ buff.L = L; ++ while ((e = strchr(fmt, '%')) != NULL) { ++ addstr2buff(&buff, fmt, e - fmt); /* add 'fmt' up to '%' */ ++ switch (*(e + 1)) { /* conversion specifier */ ++ case 's': { /* zero-terminated string */ ++ const char *s = va_arg(argp, char *); ++ if (s == NULL) s = "(null)"; ++ addstr2buff(&buff, s, strlen(s)); ++ break; ++ } ++ case 'c': { /* an 'int' as a character */ ++ char c = cast_uchar(va_arg(argp, int)); ++ addstr2buff(&buff, &c, sizeof(char)); ++ break; ++ } ++ case 'd': { /* an 'int' */ ++ TValue num; ++ setivalue(&num, va_arg(argp, int)); ++ addnum2buff(&buff, &num); ++ break; ++ } ++ case 'I': { /* a 'lua_Integer' */ ++ TValue num; ++ setivalue(&num, cast(lua_Integer, va_arg(argp, l_uacInt))); ++ addnum2buff(&buff, &num); ++ break; ++ } ++ case 'f': { /* a 'lua_Number' */ ++ TValue num; ++ setfltvalue(&num, cast_num(va_arg(argp, l_uacNumber))); ++ addnum2buff(&buff, &num); ++ break; ++ } ++ case 'p': { /* a pointer */ ++ const int sz = 3 * sizeof(void*) + 8; /* enough space for '%p' */ ++ char *bf = getbuff(&buff, sz); ++ void *p = va_arg(argp, void *); ++ int len = lua_pointer2str(bf, sz, p); ++ addsize(&buff, len); ++ break; ++ } ++ case 'U': { /* a 'long' as a UTF-8 sequence */ ++ char bf[UTF8BUFFSZ]; ++ int len = luaO_utf8esc(bf, va_arg(argp, long)); ++ addstr2buff(&buff, bf + UTF8BUFFSZ - len, len); ++ break; ++ } ++ case '%': { ++ addstr2buff(&buff, "%", 1); ++ break; ++ } ++ default: { ++ luaG_runerror(L, "invalid option '%%%c' to 'lua_pushfstring'", ++ *(e + 1)); ++ } ++ } ++ fmt = e + 2; /* skip '%' and the specifier */ ++ } ++ addstr2buff(&buff, fmt, strlen(fmt)); /* rest of 'fmt' */ ++ clearbuff(&buff); /* empty buffer into the stack */ ++ lua_assert(buff.pushed == 1); ++ return svalue(s2v(L->top - 1)); ++} ++ ++ ++const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) { ++ const char *msg; ++ va_list argp; ++ va_start(argp, fmt); ++ msg = luaO_pushvfstring(L, fmt, argp); ++ va_end(argp); ++ return msg; ++} ++ ++/* }================================================================== */ ++ ++ ++#define RETS "..." ++#define PRE "[string \"" ++#define POS "\"]" ++ ++#define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) ) ++ ++void luaO_chunkid (char *out, const char *source, size_t srclen) { ++ size_t bufflen = LUA_IDSIZE; /* free space in buffer */ ++ if (*source == '=') { /* 'literal' source */ ++ if (srclen <= bufflen) /* small enough? */ ++ memcpy(out, source + 1, srclen * sizeof(char)); ++ else { /* truncate it */ ++ addstr(out, source + 1, bufflen - 1); ++ *out = '\0'; ++ } ++ } ++ else if (*source == '@') { /* file name */ ++ if (srclen <= bufflen) /* small enough? */ ++ memcpy(out, source + 1, srclen * sizeof(char)); ++ else { /* add '...' before rest of name */ ++ addstr(out, RETS, LL(RETS)); ++ bufflen -= LL(RETS); ++ memcpy(out, source + 1 + srclen - bufflen, bufflen * sizeof(char)); ++ } ++ } ++ else { /* string; format as [string "source"] */ ++ const char *nl = strchr(source, '\n'); /* find first new line (if any) */ ++ addstr(out, PRE, LL(PRE)); /* add prefix */ ++ bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */ ++ if (srclen < bufflen && nl == NULL) { /* small one-line source? */ ++ addstr(out, source, srclen); /* keep it */ ++ } ++ else { ++ if (nl != NULL) srclen = nl - source; /* stop at first newline */ ++ if (srclen > bufflen) srclen = bufflen; ++ addstr(out, source, srclen); ++ addstr(out, RETS, LL(RETS)); ++ } ++ memcpy(out, POS, (LL(POS) + 1) * sizeof(char)); ++ } ++} ++ +diff --git a/src/bin/lua/lobject.h b/src/bin/lua/lobject.h +new file mode 100644 +index 0000000000..950bebbde2 +--- /dev/null ++++ b/src/bin/lua/lobject.h +@@ -0,0 +1,800 @@ ++/* ++** $Id: lobject.h $ ++** Type definitions for Lua objects ++** See Copyright Notice in lua.h ++*/ ++ ++ ++#ifndef lobject_h ++#define lobject_h ++ ++ ++#include ++ ++ ++#include "llimits.h" ++#include "lua.h" ++ ++ ++/* ++** Extra types for collectable non-values ++*/ ++#define LUA_TUPVAL LUA_NUMTYPES /* upvalues */ ++#define LUA_TPROTO (LUA_NUMTYPES+1) /* function prototypes */ ++#define LUA_TDEADKEY (LUA_NUMTYPES+2) /* removed keys in tables */ ++ ++ ++ ++/* ++** number of all possible types (including LUA_TNONE but excluding DEADKEY) ++*/ ++#define LUA_TOTALTYPES (LUA_TPROTO + 2) ++ ++ ++/* ++** tags for Tagged Values have the following use of bits: ++** bits 0-3: actual tag (a LUA_T* constant) ++** bits 4-5: variant bits ++** bit 6: whether value is collectable ++*/ ++ ++/* add variant bits to a type */ ++#define makevariant(t,v) ((t) | ((v) << 4)) ++ ++ ++ ++/* ++** Union of all Lua values ++*/ ++typedef union Value { ++ struct GCObject *gc; /* collectable objects */ ++ void *p; /* light userdata */ ++ lua_CFunction f; /* light C functions */ ++ lua_Integer i; /* integer numbers */ ++ lua_Number n; /* float numbers */ ++} Value; ++ ++ ++/* ++** Tagged Values. This is the basic representation of values in Lua: ++** an actual value plus a tag with its type. ++*/ ++ ++#define TValuefields Value value_; lu_byte tt_ ++ ++typedef struct TValue { ++ TValuefields; ++} TValue; ++ ++ ++#define val_(o) ((o)->value_) ++#define valraw(o) (&val_(o)) ++ ++ ++/* raw type tag of a TValue */ ++#define rawtt(o) ((o)->tt_) ++ ++/* tag with no variants (bits 0-3) */ ++#define novariant(t) ((t) & 0x0F) ++ ++/* type tag of a TValue (bits 0-3 for tags + variant bits 4-5) */ ++#define withvariant(t) ((t) & 0x3F) ++#define ttypetag(o) withvariant(rawtt(o)) ++ ++/* type of a TValue */ ++#define ttype(o) (novariant(rawtt(o))) ++ ++ ++/* Macros to test type */ ++#define checktag(o,t) (rawtt(o) == (t)) ++#define checktype(o,t) (ttype(o) == (t)) ++ ++ ++/* Macros for internal tests */ ++ ++/* collectable object has the same tag as the original value */ ++#define righttt(obj) (ttypetag(obj) == gcvalue(obj)->tt) ++ ++/* ++** Any value being manipulated by the program either is non ++** collectable, or the collectable object has the right tag ++** and it is not dead. The option 'L == NULL' allows other ++** macros using this one to be used where L is not available. ++*/ ++#define checkliveness(L,obj) \ ++ ((void)L, lua_longassert(!iscollectable(obj) || \ ++ (righttt(obj) && (L == NULL || !isdead(G(L),gcvalue(obj)))))) ++ ++ ++/* Macros to set values */ ++ ++/* set a value's tag */ ++#define settt_(o,t) ((o)->tt_=(t)) ++ ++ ++/* main macro to copy values (from 'obj1' to 'obj2') */ ++#define setobj(L,obj1,obj2) \ ++ { TValue *io1=(obj1); const TValue *io2=(obj2); \ ++ io1->value_ = io2->value_; settt_(io1, io2->tt_); \ ++ checkliveness(L,io1); lua_assert(!isnonstrictnil(io1)); } ++ ++/* ++** Different types of assignments, according to source and destination. ++** (They are mostly equal now, but may be different in the future.) ++*/ ++ ++/* from stack to stack */ ++#define setobjs2s(L,o1,o2) setobj(L,s2v(o1),s2v(o2)) ++/* to stack (not from same stack) */ ++#define setobj2s(L,o1,o2) setobj(L,s2v(o1),o2) ++/* from table to same table */ ++#define setobjt2t setobj ++/* to new object */ ++#define setobj2n setobj ++/* to table */ ++#define setobj2t setobj ++ ++ ++/* ++** Entries in a Lua stack. Field 'tbclist' forms a list of all ++** to-be-closed variables active in this stack. Dummy entries are ++** used when the distance between two tbc variables does not fit ++** in an unsigned short. They are represented by delta==0, and ++** their real delta is always the maximum value that fits in ++** that field. ++*/ ++typedef union StackValue { ++ TValue val; ++ struct { ++ TValuefields; ++ unsigned short delta; ++ } tbclist; ++} StackValue; ++ ++ ++/* index to stack elements */ ++typedef StackValue *StkId; ++ ++/* convert a 'StackValue' to a 'TValue' */ ++#define s2v(o) (&(o)->val) ++ ++ ++ ++/* ++** {================================================================== ++** Nil ++** =================================================================== ++*/ ++ ++/* Standard nil */ ++#define LUA_VNIL makevariant(LUA_TNIL, 0) ++ ++/* Empty slot (which might be different from a slot containing nil) */ ++#define LUA_VEMPTY makevariant(LUA_TNIL, 1) ++ ++/* Value returned for a key not found in a table (absent key) */ ++#define LUA_VABSTKEY makevariant(LUA_TNIL, 2) ++ ++ ++/* macro to test for (any kind of) nil */ ++#define ttisnil(v) checktype((v), LUA_TNIL) ++ ++ ++/* macro to test for a standard nil */ ++#define ttisstrictnil(o) checktag((o), LUA_VNIL) ++ ++ ++#define setnilvalue(obj) settt_(obj, LUA_VNIL) ++ ++ ++#define isabstkey(v) checktag((v), LUA_VABSTKEY) ++ ++ ++/* ++** macro to detect non-standard nils (used only in assertions) ++*/ ++#define isnonstrictnil(v) (ttisnil(v) && !ttisstrictnil(v)) ++ ++ ++/* ++** By default, entries with any kind of nil are considered empty. ++** (In any definition, values associated with absent keys must also ++** be accepted as empty.) ++*/ ++#define isempty(v) ttisnil(v) ++ ++ ++/* macro defining a value corresponding to an absent key */ ++#define ABSTKEYCONSTANT {NULL}, LUA_VABSTKEY ++ ++ ++/* mark an entry as empty */ ++#define setempty(v) settt_(v, LUA_VEMPTY) ++ ++ ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Booleans ++** =================================================================== ++*/ ++ ++ ++#define LUA_VFALSE makevariant(LUA_TBOOLEAN, 0) ++#define LUA_VTRUE makevariant(LUA_TBOOLEAN, 1) ++ ++#define ttisboolean(o) checktype((o), LUA_TBOOLEAN) ++#define ttisfalse(o) checktag((o), LUA_VFALSE) ++#define ttistrue(o) checktag((o), LUA_VTRUE) ++ ++ ++#define l_isfalse(o) (ttisfalse(o) || ttisnil(o)) ++ ++ ++#define setbfvalue(obj) settt_(obj, LUA_VFALSE) ++#define setbtvalue(obj) settt_(obj, LUA_VTRUE) ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Threads ++** =================================================================== ++*/ ++ ++#define LUA_VTHREAD makevariant(LUA_TTHREAD, 0) ++ ++#define ttisthread(o) checktag((o), ctb(LUA_VTHREAD)) ++ ++#define thvalue(o) check_exp(ttisthread(o), gco2th(val_(o).gc)) ++ ++#define setthvalue(L,obj,x) \ ++ { TValue *io = (obj); lua_State *x_ = (x); \ ++ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VTHREAD)); \ ++ checkliveness(L,io); } ++ ++#define setthvalue2s(L,o,t) setthvalue(L,s2v(o),t) ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Collectable Objects ++** =================================================================== ++*/ ++ ++/* ++** Common Header for all collectable objects (in macro form, to be ++** included in other objects) ++*/ ++#define CommonHeader struct GCObject *next; lu_byte tt; lu_byte marked ++ ++ ++/* Common type for all collectable objects */ ++typedef struct GCObject { ++ CommonHeader; ++} GCObject; ++ ++ ++/* Bit mark for collectable types */ ++#define BIT_ISCOLLECTABLE (1 << 6) ++ ++#define iscollectable(o) (rawtt(o) & BIT_ISCOLLECTABLE) ++ ++/* mark a tag as collectable */ ++#define ctb(t) ((t) | BIT_ISCOLLECTABLE) ++ ++#define gcvalue(o) check_exp(iscollectable(o), val_(o).gc) ++ ++#define gcvalueraw(v) ((v).gc) ++ ++#define setgcovalue(L,obj,x) \ ++ { TValue *io = (obj); GCObject *i_g=(x); \ ++ val_(io).gc = i_g; settt_(io, ctb(i_g->tt)); } ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Numbers ++** =================================================================== ++*/ ++ ++/* Variant tags for numbers */ ++#define LUA_VNUMINT makevariant(LUA_TNUMBER, 0) /* integer numbers */ ++#define LUA_VNUMFLT makevariant(LUA_TNUMBER, 1) /* float numbers */ ++ ++#define ttisnumber(o) checktype((o), LUA_TNUMBER) ++#define ttisfloat(o) checktag((o), LUA_VNUMFLT) ++#define ttisinteger(o) checktag((o), LUA_VNUMINT) ++ ++#define nvalue(o) check_exp(ttisnumber(o), \ ++ (ttisinteger(o) ? cast_num(ivalue(o)) : fltvalue(o))) ++#define fltvalue(o) check_exp(ttisfloat(o), val_(o).n) ++#define ivalue(o) check_exp(ttisinteger(o), val_(o).i) ++ ++#define fltvalueraw(v) ((v).n) ++#define ivalueraw(v) ((v).i) ++ ++#define setfltvalue(obj,x) \ ++ { TValue *io=(obj); val_(io).n=(x); settt_(io, LUA_VNUMFLT); } ++ ++#define chgfltvalue(obj,x) \ ++ { TValue *io=(obj); lua_assert(ttisfloat(io)); val_(io).n=(x); } ++ ++#define setivalue(obj,x) \ ++ { TValue *io=(obj); val_(io).i=(x); settt_(io, LUA_VNUMINT); } ++ ++#define chgivalue(obj,x) \ ++ { TValue *io=(obj); lua_assert(ttisinteger(io)); val_(io).i=(x); } ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Strings ++** =================================================================== ++*/ ++ ++/* Variant tags for strings */ ++#define LUA_VSHRSTR makevariant(LUA_TSTRING, 0) /* short strings */ ++#define LUA_VLNGSTR makevariant(LUA_TSTRING, 1) /* long strings */ ++ ++#define ttisstring(o) checktype((o), LUA_TSTRING) ++#define ttisshrstring(o) checktag((o), ctb(LUA_VSHRSTR)) ++#define ttislngstring(o) checktag((o), ctb(LUA_VLNGSTR)) ++ ++#define tsvalueraw(v) (gco2ts((v).gc)) ++ ++#define tsvalue(o) check_exp(ttisstring(o), gco2ts(val_(o).gc)) ++ ++#define setsvalue(L,obj,x) \ ++ { TValue *io = (obj); TString *x_ = (x); \ ++ val_(io).gc = obj2gco(x_); settt_(io, ctb(x_->tt)); \ ++ checkliveness(L,io); } ++ ++/* set a string to the stack */ ++#define setsvalue2s(L,o,s) setsvalue(L,s2v(o),s) ++ ++/* set a string to a new object */ ++#define setsvalue2n setsvalue ++ ++ ++/* ++** Header for a string value. ++*/ ++typedef struct TString { ++ CommonHeader; ++ lu_byte extra; /* reserved words for short strings; "has hash" for longs */ ++ lu_byte shrlen; /* length for short strings */ ++ unsigned int hash; ++ union { ++ size_t lnglen; /* length for long strings */ ++ struct TString *hnext; /* linked list for hash table */ ++ } u; ++ char contents[1]; ++} TString; ++ ++ ++ ++/* ++** Get the actual string (array of bytes) from a 'TString'. ++*/ ++#define getstr(ts) ((ts)->contents) ++ ++ ++/* get the actual string (array of bytes) from a Lua value */ ++#define svalue(o) getstr(tsvalue(o)) ++ ++/* get string length from 'TString *s' */ ++#define tsslen(s) ((s)->tt == LUA_VSHRSTR ? (s)->shrlen : (s)->u.lnglen) ++ ++/* get string length from 'TValue *o' */ ++#define vslen(o) tsslen(tsvalue(o)) ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Userdata ++** =================================================================== ++*/ ++ ++ ++/* ++** Light userdata should be a variant of userdata, but for compatibility ++** reasons they are also different types. ++*/ ++#define LUA_VLIGHTUSERDATA makevariant(LUA_TLIGHTUSERDATA, 0) ++ ++#define LUA_VUSERDATA makevariant(LUA_TUSERDATA, 0) ++ ++#define ttislightuserdata(o) checktag((o), LUA_VLIGHTUSERDATA) ++#define ttisfulluserdata(o) checktag((o), ctb(LUA_VUSERDATA)) ++ ++#define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p) ++#define uvalue(o) check_exp(ttisfulluserdata(o), gco2u(val_(o).gc)) ++ ++#define pvalueraw(v) ((v).p) ++ ++#define setpvalue(obj,x) \ ++ { TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_VLIGHTUSERDATA); } ++ ++#define setuvalue(L,obj,x) \ ++ { TValue *io = (obj); Udata *x_ = (x); \ ++ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VUSERDATA)); \ ++ checkliveness(L,io); } ++ ++ ++/* Ensures that addresses after this type are always fully aligned. */ ++typedef union UValue { ++ TValue uv; ++ LUAI_MAXALIGN; /* ensures maximum alignment for udata bytes */ ++} UValue; ++ ++ ++/* ++** Header for userdata with user values; ++** memory area follows the end of this structure. ++*/ ++typedef struct Udata { ++ CommonHeader; ++ unsigned short nuvalue; /* number of user values */ ++ size_t len; /* number of bytes */ ++ struct Table *metatable; ++ GCObject *gclist; ++ UValue uv[1]; /* user values */ ++} Udata; ++ ++ ++/* ++** Header for userdata with no user values. These userdata do not need ++** to be gray during GC, and therefore do not need a 'gclist' field. ++** To simplify, the code always use 'Udata' for both kinds of userdata, ++** making sure it never accesses 'gclist' on userdata with no user values. ++** This structure here is used only to compute the correct size for ++** this representation. (The 'bindata' field in its end ensures correct ++** alignment for binary data following this header.) ++*/ ++typedef struct Udata0 { ++ CommonHeader; ++ unsigned short nuvalue; /* number of user values */ ++ size_t len; /* number of bytes */ ++ struct Table *metatable; ++ union {LUAI_MAXALIGN;} bindata; ++} Udata0; ++ ++ ++/* compute the offset of the memory area of a userdata */ ++#define udatamemoffset(nuv) \ ++ ((nuv) == 0 ? offsetof(Udata0, bindata) \ ++ : offsetof(Udata, uv) + (sizeof(UValue) * (nuv))) ++ ++/* get the address of the memory block inside 'Udata' */ ++#define getudatamem(u) (cast_charp(u) + udatamemoffset((u)->nuvalue)) ++ ++/* compute the size of a userdata */ ++#define sizeudata(nuv,nb) (udatamemoffset(nuv) + (nb)) ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Prototypes ++** =================================================================== ++*/ ++ ++#define LUA_VPROTO makevariant(LUA_TPROTO, 0) ++ ++ ++/* ++** Description of an upvalue for function prototypes ++*/ ++typedef struct Upvaldesc { ++ TString *name; /* upvalue name (for debug information) */ ++ lu_byte instack; /* whether it is in stack (register) */ ++ lu_byte idx; /* index of upvalue (in stack or in outer function's list) */ ++ lu_byte kind; /* kind of corresponding variable */ ++} Upvaldesc; ++ ++ ++/* ++** Description of a local variable for function prototypes ++** (used for debug information) ++*/ ++typedef struct LocVar { ++ TString *varname; ++ int startpc; /* first point where variable is active */ ++ int endpc; /* first point where variable is dead */ ++} LocVar; ++ ++ ++/* ++** Associates the absolute line source for a given instruction ('pc'). ++** The array 'lineinfo' gives, for each instruction, the difference in ++** lines from the previous instruction. When that difference does not ++** fit into a byte, Lua saves the absolute line for that instruction. ++** (Lua also saves the absolute line periodically, to speed up the ++** computation of a line number: we can use binary search in the ++** absolute-line array, but we must traverse the 'lineinfo' array ++** linearly to compute a line.) ++*/ ++typedef struct AbsLineInfo { ++ int pc; ++ int line; ++} AbsLineInfo; ++ ++/* ++** Function Prototypes ++*/ ++typedef struct Proto { ++ CommonHeader; ++ lu_byte numparams; /* number of fixed (named) parameters */ ++ lu_byte is_vararg; ++ lu_byte maxstacksize; /* number of registers needed by this function */ ++ int sizeupvalues; /* size of 'upvalues' */ ++ int sizek; /* size of 'k' */ ++ int sizecode; ++ int sizelineinfo; ++ int sizep; /* size of 'p' */ ++ int sizelocvars; ++ int sizeabslineinfo; /* size of 'abslineinfo' */ ++ int linedefined; /* debug information */ ++ int lastlinedefined; /* debug information */ ++ TValue *k; /* constants used by the function */ ++ Instruction *code; /* opcodes */ ++ struct Proto **p; /* functions defined inside the function */ ++ Upvaldesc *upvalues; /* upvalue information */ ++ ls_byte *lineinfo; /* information about source lines (debug information) */ ++ AbsLineInfo *abslineinfo; /* idem */ ++ LocVar *locvars; /* information about local variables (debug information) */ ++ TString *source; /* used for debug information */ ++ GCObject *gclist; ++} Proto; ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Functions ++** =================================================================== ++*/ ++ ++#define LUA_VUPVAL makevariant(LUA_TUPVAL, 0) ++ ++ ++/* Variant tags for functions */ ++#define LUA_VLCL makevariant(LUA_TFUNCTION, 0) /* Lua closure */ ++#define LUA_VLCF makevariant(LUA_TFUNCTION, 1) /* light C function */ ++#define LUA_VCCL makevariant(LUA_TFUNCTION, 2) /* C closure */ ++ ++#define ttisfunction(o) checktype(o, LUA_TFUNCTION) ++#define ttisLclosure(o) checktag((o), ctb(LUA_VLCL)) ++#define ttislcf(o) checktag((o), LUA_VLCF) ++#define ttisCclosure(o) checktag((o), ctb(LUA_VCCL)) ++#define ttisclosure(o) (ttisLclosure(o) || ttisCclosure(o)) ++ ++ ++#define isLfunction(o) ttisLclosure(o) ++ ++#define clvalue(o) check_exp(ttisclosure(o), gco2cl(val_(o).gc)) ++#define clLvalue(o) check_exp(ttisLclosure(o), gco2lcl(val_(o).gc)) ++#define fvalue(o) check_exp(ttislcf(o), val_(o).f) ++#define clCvalue(o) check_exp(ttisCclosure(o), gco2ccl(val_(o).gc)) ++ ++#define fvalueraw(v) ((v).f) ++ ++#define setclLvalue(L,obj,x) \ ++ { TValue *io = (obj); LClosure *x_ = (x); \ ++ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VLCL)); \ ++ checkliveness(L,io); } ++ ++#define setclLvalue2s(L,o,cl) setclLvalue(L,s2v(o),cl) ++ ++#define setfvalue(obj,x) \ ++ { TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_VLCF); } ++ ++#define setclCvalue(L,obj,x) \ ++ { TValue *io = (obj); CClosure *x_ = (x); \ ++ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VCCL)); \ ++ checkliveness(L,io); } ++ ++ ++/* ++** Upvalues for Lua closures ++*/ ++typedef struct UpVal { ++ CommonHeader; ++ lu_byte tbc; /* true if it represents a to-be-closed variable */ ++ TValue *v; /* points to stack or to its own value */ ++ union { ++ struct { /* (when open) */ ++ struct UpVal *next; /* linked list */ ++ struct UpVal **previous; ++ } open; ++ TValue value; /* the value (when closed) */ ++ } u; ++} UpVal; ++ ++ ++ ++#define ClosureHeader \ ++ CommonHeader; lu_byte nupvalues; GCObject *gclist ++ ++typedef struct CClosure { ++ ClosureHeader; ++ lua_CFunction f; ++ TValue upvalue[1]; /* list of upvalues */ ++} CClosure; ++ ++ ++typedef struct LClosure { ++ ClosureHeader; ++ struct Proto *p; ++ UpVal *upvals[1]; /* list of upvalues */ ++} LClosure; ++ ++ ++typedef union Closure { ++ CClosure c; ++ LClosure l; ++} Closure; ++ ++ ++#define getproto(o) (clLvalue(o)->p) ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Tables ++** =================================================================== ++*/ ++ ++#define LUA_VTABLE makevariant(LUA_TTABLE, 0) ++ ++#define ttistable(o) checktag((o), ctb(LUA_VTABLE)) ++ ++#define hvalue(o) check_exp(ttistable(o), gco2t(val_(o).gc)) ++ ++#define sethvalue(L,obj,x) \ ++ { TValue *io = (obj); Table *x_ = (x); \ ++ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VTABLE)); \ ++ checkliveness(L,io); } ++ ++#define sethvalue2s(L,o,h) sethvalue(L,s2v(o),h) ++ ++ ++/* ++** Nodes for Hash tables: A pack of two TValue's (key-value pairs) ++** plus a 'next' field to link colliding entries. The distribution ++** of the key's fields ('key_tt' and 'key_val') not forming a proper ++** 'TValue' allows for a smaller size for 'Node' both in 4-byte ++** and 8-byte alignments. ++*/ ++typedef union Node { ++ struct NodeKey { ++ TValuefields; /* fields for value */ ++ lu_byte key_tt; /* key type */ ++ int next; /* for chaining */ ++ Value key_val; /* key value */ ++ } u; ++ TValue i_val; /* direct access to node's value as a proper 'TValue' */ ++} Node; ++ ++ ++/* copy a value into a key */ ++#define setnodekey(L,node,obj) \ ++ { Node *n_=(node); const TValue *io_=(obj); \ ++ n_->u.key_val = io_->value_; n_->u.key_tt = io_->tt_; \ ++ checkliveness(L,io_); } ++ ++ ++/* copy a value from a key */ ++#define getnodekey(L,obj,node) \ ++ { TValue *io_=(obj); const Node *n_=(node); \ ++ io_->value_ = n_->u.key_val; io_->tt_ = n_->u.key_tt; \ ++ checkliveness(L,io_); } ++ ++ ++/* ++** About 'alimit': if 'isrealasize(t)' is true, then 'alimit' is the ++** real size of 'array'. Otherwise, the real size of 'array' is the ++** smallest power of two not smaller than 'alimit' (or zero iff 'alimit' ++** is zero); 'alimit' is then used as a hint for #t. ++*/ ++ ++#define BITRAS (1 << 7) ++#define isrealasize(t) (!((t)->flags & BITRAS)) ++#define setrealasize(t) ((t)->flags &= cast_byte(~BITRAS)) ++#define setnorealasize(t) ((t)->flags |= BITRAS) ++ ++ ++typedef struct Table { ++ CommonHeader; ++ lu_byte flags; /* 1<

u.key_tt) ++#define keyval(node) ((node)->u.key_val) ++ ++#define keyisnil(node) (keytt(node) == LUA_TNIL) ++#define keyisinteger(node) (keytt(node) == LUA_VNUMINT) ++#define keyival(node) (keyval(node).i) ++#define keyisshrstr(node) (keytt(node) == ctb(LUA_VSHRSTR)) ++#define keystrval(node) (gco2ts(keyval(node).gc)) ++ ++#define setnilkey(node) (keytt(node) = LUA_TNIL) ++ ++#define keyiscollectable(n) (keytt(n) & BIT_ISCOLLECTABLE) ++ ++#define gckey(n) (keyval(n).gc) ++#define gckeyN(n) (keyiscollectable(n) ? gckey(n) : NULL) ++ ++ ++/* ++** Dead keys in tables have the tag DEADKEY but keep their original ++** gcvalue. This distinguishes them from regular keys but allows them to ++** be found when searched in a special way. ('next' needs that to find ++** keys removed from a table during a traversal.) ++*/ ++#define setdeadkey(node) (keytt(node) = LUA_TDEADKEY) ++#define keyisdead(node) (keytt(node) == LUA_TDEADKEY) ++ ++/* }================================================================== */ ++ ++ ++ ++/* ++** 'module' operation for hashing (size is always a power of 2) ++*/ ++#define lmod(s,size) \ ++ (check_exp((size&(size-1))==0, (cast_int((s) & ((size)-1))))) ++ ++ ++#define twoto(x) (1<<(x)) ++#define sizenode(t) (twoto((t)->lsizenode)) ++ ++ ++/* size of buffer for 'luaO_utf8esc' function */ ++#define UTF8BUFFSZ 8 ++ ++LUAI_FUNC int luaO_utf8esc (char *buff, unsigned long x); ++LUAI_FUNC int luaO_ceillog2 (unsigned int x); ++LUAI_FUNC int luaO_rawarith (lua_State *L, int op, const TValue *p1, ++ const TValue *p2, TValue *res); ++LUAI_FUNC void luaO_arith (lua_State *L, int op, const TValue *p1, ++ const TValue *p2, StkId res); ++LUAI_FUNC size_t luaO_str2num (const char *s, TValue *o); ++LUAI_FUNC int luaO_hexavalue (int c); ++LUAI_FUNC void luaO_tostring (lua_State *L, TValue *obj); ++LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt, ++ va_list argp); ++LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...); ++LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t srclen); ++ ++ ++#endif ++ +diff --git a/src/bin/lua/lopcodes.c b/src/bin/lua/lopcodes.c +new file mode 100644 +index 0000000000..c67aa227c5 +--- /dev/null ++++ b/src/bin/lua/lopcodes.c +@@ -0,0 +1,104 @@ ++/* ++** $Id: lopcodes.c $ ++** Opcodes for Lua virtual machine ++** See Copyright Notice in lua.h ++*/ ++ ++#define lopcodes_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++#include "lopcodes.h" ++ ++ ++/* ORDER OP */ ++ ++LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = { ++/* MM OT IT T A mode opcode */ ++ opmode(0, 0, 0, 0, 1, iABC) /* OP_MOVE */ ++ ,opmode(0, 0, 0, 0, 1, iAsBx) /* OP_LOADI */ ++ ,opmode(0, 0, 0, 0, 1, iAsBx) /* OP_LOADF */ ++ ,opmode(0, 0, 0, 0, 1, iABx) /* OP_LOADK */ ++ ,opmode(0, 0, 0, 0, 1, iABx) /* OP_LOADKX */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADFALSE */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LFALSESKIP */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADTRUE */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADNIL */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETUPVAL */ ++ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETUPVAL */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETTABUP */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETTABLE */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETI */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETFIELD */ ++ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETTABUP */ ++ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETTABLE */ ++ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETI */ ++ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETFIELD */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_NEWTABLE */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SELF */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADDI */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADDK */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SUBK */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MULK */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MODK */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_POWK */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_DIVK */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_IDIVK */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BANDK */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BORK */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BXORK */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHRI */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHLI */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADD */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SUB */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MUL */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MOD */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_POW */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_DIV */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_IDIV */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BAND */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BOR */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BXOR */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHL */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHR */ ++ ,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBIN */ ++ ,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBINI*/ ++ ,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBINK*/ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_UNM */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BNOT */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_NOT */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LEN */ ++ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_CONCAT */ ++ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_CLOSE */ ++ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_TBC */ ++ ,opmode(0, 0, 0, 0, 0, isJ) /* OP_JMP */ ++ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQ */ ++ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LT */ ++ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LE */ ++ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQK */ ++ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQI */ ++ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LTI */ ++ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LEI */ ++ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_GTI */ ++ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_GEI */ ++ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_TEST */ ++ ,opmode(0, 0, 0, 1, 1, iABC) /* OP_TESTSET */ ++ ,opmode(0, 1, 1, 0, 1, iABC) /* OP_CALL */ ++ ,opmode(0, 1, 1, 0, 1, iABC) /* OP_TAILCALL */ ++ ,opmode(0, 0, 1, 0, 0, iABC) /* OP_RETURN */ ++ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_RETURN0 */ ++ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_RETURN1 */ ++ ,opmode(0, 0, 0, 0, 1, iABx) /* OP_FORLOOP */ ++ ,opmode(0, 0, 0, 0, 1, iABx) /* OP_FORPREP */ ++ ,opmode(0, 0, 0, 0, 0, iABx) /* OP_TFORPREP */ ++ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_TFORCALL */ ++ ,opmode(0, 0, 0, 0, 1, iABx) /* OP_TFORLOOP */ ++ ,opmode(0, 0, 1, 0, 0, iABC) /* OP_SETLIST */ ++ ,opmode(0, 0, 0, 0, 1, iABx) /* OP_CLOSURE */ ++ ,opmode(0, 1, 0, 0, 1, iABC) /* OP_VARARG */ ++ ,opmode(0, 0, 1, 0, 1, iABC) /* OP_VARARGPREP */ ++ ,opmode(0, 0, 0, 0, 0, iAx) /* OP_EXTRAARG */ ++}; ++ +diff --git a/src/bin/lua/lopcodes.h b/src/bin/lua/lopcodes.h +new file mode 100644 +index 0000000000..d6a47e5af9 +--- /dev/null ++++ b/src/bin/lua/lopcodes.h +@@ -0,0 +1,392 @@ ++/* ++** $Id: lopcodes.h $ ++** Opcodes for Lua virtual machine ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef lopcodes_h ++#define lopcodes_h ++ ++#include "llimits.h" ++ ++ ++/*=========================================================================== ++ We assume that instructions are unsigned 32-bit integers. ++ All instructions have an opcode in the first 7 bits. ++ Instructions can have the following formats: ++ ++ 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 ++ 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 ++iABC C(8) | B(8) |k| A(8) | Op(7) | ++iABx Bx(17) | A(8) | Op(7) | ++iAsBx sBx (signed)(17) | A(8) | Op(7) | ++iAx Ax(25) | Op(7) | ++isJ sJ(25) | Op(7) | ++ ++ A signed argument is represented in excess K: the represented value is ++ the written unsigned value minus K, where K is half the maximum for the ++ corresponding unsigned argument. ++===========================================================================*/ ++ ++ ++enum OpMode {iABC, iABx, iAsBx, iAx, isJ}; /* basic instruction formats */ ++ ++ ++/* ++** size and position of opcode arguments. ++*/ ++#define SIZE_C 8 ++#define SIZE_B 8 ++#define SIZE_Bx (SIZE_C + SIZE_B + 1) ++#define SIZE_A 8 ++#define SIZE_Ax (SIZE_Bx + SIZE_A) ++#define SIZE_sJ (SIZE_Bx + SIZE_A) ++ ++#define SIZE_OP 7 ++ ++#define POS_OP 0 ++ ++#define POS_A (POS_OP + SIZE_OP) ++#define POS_k (POS_A + SIZE_A) ++#define POS_B (POS_k + 1) ++#define POS_C (POS_B + SIZE_B) ++ ++#define POS_Bx POS_k ++ ++#define POS_Ax POS_A ++ ++#define POS_sJ POS_A ++ ++ ++/* ++** limits for opcode arguments. ++** we use (signed) 'int' to manipulate most arguments, ++** so they must fit in ints. ++*/ ++ ++/* Check whether type 'int' has at least 'b' bits ('b' < 32) */ ++#define L_INTHASBITS(b) ((UINT_MAX >> ((b) - 1)) >= 1) ++ ++ ++#if L_INTHASBITS(SIZE_Bx) ++#define MAXARG_Bx ((1<>1) /* 'sBx' is signed */ ++ ++ ++#if L_INTHASBITS(SIZE_Ax) ++#define MAXARG_Ax ((1<> 1) ++ ++ ++#define MAXARG_A ((1<> 1) ++ ++#define int2sC(i) ((i) + OFFSET_sC) ++#define sC2int(i) ((i) - OFFSET_sC) ++ ++ ++/* creates a mask with 'n' 1 bits at position 'p' */ ++#define MASK1(n,p) ((~((~(Instruction)0)<<(n)))<<(p)) ++ ++/* creates a mask with 'n' 0 bits at position 'p' */ ++#define MASK0(n,p) (~MASK1(n,p)) ++ ++/* ++** the following macros help to manipulate instructions ++*/ ++ ++#define GET_OPCODE(i) (cast(OpCode, ((i)>>POS_OP) & MASK1(SIZE_OP,0))) ++#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \ ++ ((cast(Instruction, o)<>(pos)) & MASK1(size,0))) ++#define setarg(i,v,pos,size) ((i) = (((i)&MASK0(size,pos)) | \ ++ ((cast(Instruction, v)<> sC */ ++OP_SHLI,/* A B sC R[A] := sC << R[B] */ ++ ++OP_ADD,/* A B C R[A] := R[B] + R[C] */ ++OP_SUB,/* A B C R[A] := R[B] - R[C] */ ++OP_MUL,/* A B C R[A] := R[B] * R[C] */ ++OP_MOD,/* A B C R[A] := R[B] % R[C] */ ++OP_POW,/* A B C R[A] := R[B] ^ R[C] */ ++OP_DIV,/* A B C R[A] := R[B] / R[C] */ ++OP_IDIV,/* A B C R[A] := R[B] // R[C] */ ++ ++OP_BAND,/* A B C R[A] := R[B] & R[C] */ ++OP_BOR,/* A B C R[A] := R[B] | R[C] */ ++OP_BXOR,/* A B C R[A] := R[B] ~ R[C] */ ++OP_SHL,/* A B C R[A] := R[B] << R[C] */ ++OP_SHR,/* A B C R[A] := R[B] >> R[C] */ ++ ++OP_MMBIN,/* A B C call C metamethod over R[A] and R[B] */ ++OP_MMBINI,/* A sB C k call C metamethod over R[A] and sB */ ++OP_MMBINK,/* A B C k call C metamethod over R[A] and K[B] */ ++ ++OP_UNM,/* A B R[A] := -R[B] */ ++OP_BNOT,/* A B R[A] := ~R[B] */ ++OP_NOT,/* A B R[A] := not R[B] */ ++OP_LEN,/* A B R[A] := #R[B] (length operator) */ ++ ++OP_CONCAT,/* A B R[A] := R[A].. ... ..R[A + B - 1] */ ++ ++OP_CLOSE,/* A close all upvalues >= R[A] */ ++OP_TBC,/* A mark variable A "to be closed" */ ++OP_JMP,/* sJ pc += sJ */ ++OP_EQ,/* A B k if ((R[A] == R[B]) ~= k) then pc++ */ ++OP_LT,/* A B k if ((R[A] < R[B]) ~= k) then pc++ */ ++OP_LE,/* A B k if ((R[A] <= R[B]) ~= k) then pc++ */ ++ ++OP_EQK,/* A B k if ((R[A] == K[B]) ~= k) then pc++ */ ++OP_EQI,/* A sB k if ((R[A] == sB) ~= k) then pc++ */ ++OP_LTI,/* A sB k if ((R[A] < sB) ~= k) then pc++ */ ++OP_LEI,/* A sB k if ((R[A] <= sB) ~= k) then pc++ */ ++OP_GTI,/* A sB k if ((R[A] > sB) ~= k) then pc++ */ ++OP_GEI,/* A sB k if ((R[A] >= sB) ~= k) then pc++ */ ++ ++OP_TEST,/* A k if (not R[A] == k) then pc++ */ ++OP_TESTSET,/* A B k if (not R[B] == k) then pc++ else R[A] := R[B] */ ++ ++OP_CALL,/* A B C R[A], ... ,R[A+C-2] := R[A](R[A+1], ... ,R[A+B-1]) */ ++OP_TAILCALL,/* A B C k return R[A](R[A+1], ... ,R[A+B-1]) */ ++ ++OP_RETURN,/* A B C k return R[A], ... ,R[A+B-2] (see note) */ ++OP_RETURN0,/* return */ ++OP_RETURN1,/* A return R[A] */ ++ ++OP_FORLOOP,/* A Bx update counters; if loop continues then pc-=Bx; */ ++OP_FORPREP,/* A Bx ; ++ if not to run then pc+=Bx+1; */ ++ ++OP_TFORPREP,/* A Bx create upvalue for R[A + 3]; pc+=Bx */ ++OP_TFORCALL,/* A C R[A+4], ... ,R[A+3+C] := R[A](R[A+1], R[A+2]); */ ++OP_TFORLOOP,/* A Bx if R[A+2] ~= nil then { R[A]=R[A+2]; pc -= Bx } */ ++ ++OP_SETLIST,/* A B C k R[A][C+i] := R[A+i], 1 <= i <= B */ ++ ++OP_CLOSURE,/* A Bx R[A] := closure(KPROTO[Bx]) */ ++ ++OP_VARARG,/* A C R[A], R[A+1], ..., R[A+C-2] = vararg */ ++ ++OP_VARARGPREP,/*A (adjust vararg parameters) */ ++ ++OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */ ++} OpCode; ++ ++ ++#define NUM_OPCODES ((int)(OP_EXTRAARG) + 1) ++ ++ ++ ++/*=========================================================================== ++ Notes: ++ (*) In OP_CALL, if (B == 0) then B = top - A. If (C == 0), then ++ 'top' is set to last_result+1, so next open instruction (OP_CALL, ++ OP_RETURN*, OP_SETLIST) may use 'top'. ++ ++ (*) In OP_VARARG, if (C == 0) then use actual number of varargs and ++ set top (like in OP_CALL with C == 0). ++ ++ (*) In OP_RETURN, if (B == 0) then return up to 'top'. ++ ++ (*) In OP_LOADKX and OP_NEWTABLE, the next instruction is always ++ OP_EXTRAARG. ++ ++ (*) In OP_SETLIST, if (B == 0) then real B = 'top'; if k, then ++ real C = EXTRAARG _ C (the bits of EXTRAARG concatenated with the ++ bits of C). ++ ++ (*) In OP_NEWTABLE, B is log2 of the hash size (which is always a ++ power of 2) plus 1, or zero for size zero. If not k, the array size ++ is C. Otherwise, the array size is EXTRAARG _ C. ++ ++ (*) For comparisons, k specifies what condition the test should accept ++ (true or false). ++ ++ (*) In OP_MMBINI/OP_MMBINK, k means the arguments were flipped ++ (the constant is the first operand). ++ ++ (*) All 'skips' (pc++) assume that next instruction is a jump. ++ ++ (*) In instructions OP_RETURN/OP_TAILCALL, 'k' specifies that the ++ function builds upvalues, which may need to be closed. C > 0 means ++ the function is vararg, so that its 'func' must be corrected before ++ returning; in this case, (C - 1) is its number of fixed parameters. ++ ++ (*) In comparisons with an immediate operand, C signals whether the ++ original operand was a float. (It must be corrected in case of ++ metamethods.) ++ ++===========================================================================*/ ++ ++ ++/* ++** masks for instruction properties. The format is: ++** bits 0-2: op mode ++** bit 3: instruction set register A ++** bit 4: operator is a test (next instruction must be a jump) ++** bit 5: instruction uses 'L->top' set by previous instruction (when B == 0) ++** bit 6: instruction sets 'L->top' for next instruction (when C == 0) ++** bit 7: instruction is an MM instruction (call a metamethod) ++*/ ++ ++LUAI_DDEC(const lu_byte luaP_opmodes[NUM_OPCODES];) ++ ++#define getOpMode(m) (cast(enum OpMode, luaP_opmodes[m] & 7)) ++#define testAMode(m) (luaP_opmodes[m] & (1 << 3)) ++#define testTMode(m) (luaP_opmodes[m] & (1 << 4)) ++#define testITMode(m) (luaP_opmodes[m] & (1 << 5)) ++#define testOTMode(m) (luaP_opmodes[m] & (1 << 6)) ++#define testMMMode(m) (luaP_opmodes[m] & (1 << 7)) ++ ++/* "out top" (set top for next instruction) */ ++#define isOT(i) \ ++ ((testOTMode(GET_OPCODE(i)) && GETARG_C(i) == 0) || \ ++ GET_OPCODE(i) == OP_TAILCALL) ++ ++/* "in top" (uses top from previous instruction) */ ++#define isIT(i) (testITMode(GET_OPCODE(i)) && GETARG_B(i) == 0) ++ ++#define opmode(mm,ot,it,t,a,m) \ ++ (((mm) << 7) | ((ot) << 6) | ((it) << 5) | ((t) << 4) | ((a) << 3) | (m)) ++ ++ ++/* number of list items to accumulate before a SETLIST instruction */ ++#define LFIELDS_PER_FLUSH 50 ++ ++#endif +diff --git a/src/bin/lua/lopnames.h b/src/bin/lua/lopnames.h +new file mode 100644 +index 0000000000..965cec9bf2 +--- /dev/null ++++ b/src/bin/lua/lopnames.h +@@ -0,0 +1,103 @@ ++/* ++** $Id: lopnames.h $ ++** Opcode names ++** See Copyright Notice in lua.h ++*/ ++ ++#if !defined(lopnames_h) ++#define lopnames_h ++ ++#include ++ ++ ++/* ORDER OP */ ++ ++static const char *const opnames[] = { ++ "MOVE", ++ "LOADI", ++ "LOADF", ++ "LOADK", ++ "LOADKX", ++ "LOADFALSE", ++ "LFALSESKIP", ++ "LOADTRUE", ++ "LOADNIL", ++ "GETUPVAL", ++ "SETUPVAL", ++ "GETTABUP", ++ "GETTABLE", ++ "GETI", ++ "GETFIELD", ++ "SETTABUP", ++ "SETTABLE", ++ "SETI", ++ "SETFIELD", ++ "NEWTABLE", ++ "SELF", ++ "ADDI", ++ "ADDK", ++ "SUBK", ++ "MULK", ++ "MODK", ++ "POWK", ++ "DIVK", ++ "IDIVK", ++ "BANDK", ++ "BORK", ++ "BXORK", ++ "SHRI", ++ "SHLI", ++ "ADD", ++ "SUB", ++ "MUL", ++ "MOD", ++ "POW", ++ "DIV", ++ "IDIV", ++ "BAND", ++ "BOR", ++ "BXOR", ++ "SHL", ++ "SHR", ++ "MMBIN", ++ "MMBINI", ++ "MMBINK", ++ "UNM", ++ "BNOT", ++ "NOT", ++ "LEN", ++ "CONCAT", ++ "CLOSE", ++ "TBC", ++ "JMP", ++ "EQ", ++ "LT", ++ "LE", ++ "EQK", ++ "EQI", ++ "LTI", ++ "LEI", ++ "GTI", ++ "GEI", ++ "TEST", ++ "TESTSET", ++ "CALL", ++ "TAILCALL", ++ "RETURN", ++ "RETURN0", ++ "RETURN1", ++ "FORLOOP", ++ "FORPREP", ++ "TFORPREP", ++ "TFORCALL", ++ "TFORLOOP", ++ "SETLIST", ++ "CLOSURE", ++ "VARARG", ++ "VARARGPREP", ++ "EXTRAARG", ++ NULL ++}; ++ ++#endif ++ +diff --git a/src/bin/lua/loslib.c b/src/bin/lua/loslib.c +new file mode 100644 +index 0000000000..3e20d622ba +--- /dev/null ++++ b/src/bin/lua/loslib.c +@@ -0,0 +1,430 @@ ++/* ++** $Id: loslib.c $ ++** Standard Operating System library ++** See Copyright Notice in lua.h ++*/ ++ ++#define loslib_c ++#define LUA_LIB ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++#include ++#include ++#include ++ ++#include "lua.h" ++ ++#include "lauxlib.h" ++#include "lualib.h" ++ ++ ++/* ++** {================================================================== ++** List of valid conversion specifiers for the 'strftime' function; ++** options are grouped by length; group of length 2 start with '||'. ++** =================================================================== ++*/ ++#if !defined(LUA_STRFTIMEOPTIONS) /* { */ ++ ++/* options for ANSI C 89 (only 1-char options) */ ++#define L_STRFTIMEC89 "aAbBcdHIjmMpSUwWxXyYZ%" ++ ++/* options for ISO C 99 and POSIX */ ++#define L_STRFTIMEC99 "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%" \ ++ "||" "EcECExEXEyEY" "OdOeOHOIOmOMOSOuOUOVOwOWOy" /* two-char options */ ++ ++/* options for Windows */ ++#define L_STRFTIMEWIN "aAbBcdHIjmMpSUwWxXyYzZ%" \ ++ "||" "#c#x#d#H#I#j#m#M#S#U#w#W#y#Y" /* two-char options */ ++ ++#if defined(LUA_USE_WINDOWS) ++#define LUA_STRFTIMEOPTIONS L_STRFTIMEWIN ++#elif defined(LUA_USE_C89) ++#define LUA_STRFTIMEOPTIONS L_STRFTIMEC89 ++#else /* C99 specification */ ++#define LUA_STRFTIMEOPTIONS L_STRFTIMEC99 ++#endif ++ ++#endif /* } */ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Configuration for time-related stuff ++** =================================================================== ++*/ ++ ++/* ++** type to represent time_t in Lua ++*/ ++#if !defined(LUA_NUMTIME) /* { */ ++ ++#define l_timet lua_Integer ++#define l_pushtime(L,t) lua_pushinteger(L,(lua_Integer)(t)) ++#define l_gettime(L,arg) luaL_checkinteger(L, arg) ++ ++#else /* }{ */ ++ ++#define l_timet lua_Number ++#define l_pushtime(L,t) lua_pushnumber(L,(lua_Number)(t)) ++#define l_gettime(L,arg) luaL_checknumber(L, arg) ++ ++#endif /* } */ ++ ++ ++#if !defined(l_gmtime) /* { */ ++/* ++** By default, Lua uses gmtime/localtime, except when POSIX is available, ++** where it uses gmtime_r/localtime_r ++*/ ++ ++#if defined(LUA_USE_POSIX) /* { */ ++ ++#define l_gmtime(t,r) gmtime_r(t,r) ++#define l_localtime(t,r) localtime_r(t,r) ++ ++#else /* }{ */ ++ ++/* ISO C definitions */ ++#define l_gmtime(t,r) ((void)(r)->tm_sec, gmtime(t)) ++#define l_localtime(t,r) ((void)(r)->tm_sec, localtime(t)) ++ ++#endif /* } */ ++ ++#endif /* } */ ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Configuration for 'tmpnam': ++** By default, Lua uses tmpnam except when POSIX is available, where ++** it uses mkstemp. ++** =================================================================== ++*/ ++#if !defined(lua_tmpnam) /* { */ ++ ++#if defined(LUA_USE_POSIX) /* { */ ++ ++#include ++ ++#define LUA_TMPNAMBUFSIZE 32 ++ ++#if !defined(LUA_TMPNAMTEMPLATE) ++#define LUA_TMPNAMTEMPLATE "/tmp/lua_XXXXXX" ++#endif ++ ++#define lua_tmpnam(b,e) { \ ++ strcpy(b, LUA_TMPNAMTEMPLATE); \ ++ e = mkstemp(b); \ ++ if (e != -1) close(e); \ ++ e = (e == -1); } ++ ++#else /* }{ */ ++ ++/* ISO C definitions */ ++#define LUA_TMPNAMBUFSIZE L_tmpnam ++#define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); } ++ ++#endif /* } */ ++ ++#endif /* } */ ++/* }================================================================== */ ++ ++ ++ ++static int os_execute (lua_State *L) { ++ const char *cmd = luaL_optstring(L, 1, NULL); ++ int stat; ++ errno = 0; ++ stat = system(cmd); ++ if (cmd != NULL) ++ return luaL_execresult(L, stat); ++ else { ++ lua_pushboolean(L, stat); /* true if there is a shell */ ++ return 1; ++ } ++} ++ ++ ++static int os_remove (lua_State *L) { ++ const char *filename = luaL_checkstring(L, 1); ++ return luaL_fileresult(L, remove(filename) == 0, filename); ++} ++ ++ ++static int os_rename (lua_State *L) { ++ const char *fromname = luaL_checkstring(L, 1); ++ const char *toname = luaL_checkstring(L, 2); ++ return luaL_fileresult(L, rename(fromname, toname) == 0, NULL); ++} ++ ++ ++static int os_tmpname (lua_State *L) { ++ char buff[LUA_TMPNAMBUFSIZE]; ++ int err; ++ lua_tmpnam(buff, err); ++ if (l_unlikely(err)) ++ return luaL_error(L, "unable to generate a unique filename"); ++ lua_pushstring(L, buff); ++ return 1; ++} ++ ++ ++static int os_getenv (lua_State *L) { ++ lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if NULL push nil */ ++ return 1; ++} ++ ++ ++static int os_clock (lua_State *L) { ++ lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC); ++ return 1; ++} ++ ++ ++/* ++** {====================================================== ++** Time/Date operations ++** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S, ++** wday=%w+1, yday=%j, isdst=? } ++** ======================================================= ++*/ ++ ++/* ++** About the overflow check: an overflow cannot occur when time ++** is represented by a lua_Integer, because either lua_Integer is ++** large enough to represent all int fields or it is not large enough ++** to represent a time that cause a field to overflow. However, if ++** times are represented as doubles and lua_Integer is int, then the ++** time 0x1.e1853b0d184f6p+55 would cause an overflow when adding 1900 ++** to compute the year. ++*/ ++static void setfield (lua_State *L, const char *key, int value, int delta) { ++ #if (defined(LUA_NUMTIME) && LUA_MAXINTEGER <= INT_MAX) ++ if (l_unlikely(value > LUA_MAXINTEGER - delta)) ++ luaL_error(L, "field '%s' is out-of-bound", key); ++ #endif ++ lua_pushinteger(L, (lua_Integer)value + delta); ++ lua_setfield(L, -2, key); ++} ++ ++ ++static void setboolfield (lua_State *L, const char *key, int value) { ++ if (value < 0) /* undefined? */ ++ return; /* does not set field */ ++ lua_pushboolean(L, value); ++ lua_setfield(L, -2, key); ++} ++ ++ ++/* ++** Set all fields from structure 'tm' in the table on top of the stack ++*/ ++static void setallfields (lua_State *L, struct tm *stm) { ++ setfield(L, "year", stm->tm_year, 1900); ++ setfield(L, "month", stm->tm_mon, 1); ++ setfield(L, "day", stm->tm_mday, 0); ++ setfield(L, "hour", stm->tm_hour, 0); ++ setfield(L, "min", stm->tm_min, 0); ++ setfield(L, "sec", stm->tm_sec, 0); ++ setfield(L, "yday", stm->tm_yday, 1); ++ setfield(L, "wday", stm->tm_wday, 1); ++ setboolfield(L, "isdst", stm->tm_isdst); ++} ++ ++ ++static int getboolfield (lua_State *L, const char *key) { ++ int res; ++ res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1); ++ lua_pop(L, 1); ++ return res; ++} ++ ++ ++static int getfield (lua_State *L, const char *key, int d, int delta) { ++ int isnum; ++ int t = lua_getfield(L, -1, key); /* get field and its type */ ++ lua_Integer res = lua_tointegerx(L, -1, &isnum); ++ if (!isnum) { /* field is not an integer? */ ++ if (l_unlikely(t != LUA_TNIL)) /* some other value? */ ++ return luaL_error(L, "field '%s' is not an integer", key); ++ else if (l_unlikely(d < 0)) /* absent field; no default? */ ++ return luaL_error(L, "field '%s' missing in date table", key); ++ res = d; ++ } ++ else { ++ /* unsigned avoids overflow when lua_Integer has 32 bits */ ++ if (!(res >= 0 ? (lua_Unsigned)res <= (lua_Unsigned)INT_MAX + delta ++ : (lua_Integer)INT_MIN + delta <= res)) ++ return luaL_error(L, "field '%s' is out-of-bound", key); ++ res -= delta; ++ } ++ lua_pop(L, 1); ++ return (int)res; ++} ++ ++ ++static const char *checkoption (lua_State *L, const char *conv, ++ ptrdiff_t convlen, char *buff) { ++ const char *option = LUA_STRFTIMEOPTIONS; ++ int oplen = 1; /* length of options being checked */ ++ for (; *option != '\0' && oplen <= convlen; option += oplen) { ++ if (*option == '|') /* next block? */ ++ oplen++; /* will check options with next length (+1) */ ++ else if (memcmp(conv, option, oplen) == 0) { /* match? */ ++ memcpy(buff, conv, oplen); /* copy valid option to buffer */ ++ buff[oplen] = '\0'; ++ return conv + oplen; /* return next item */ ++ } ++ } ++ luaL_argerror(L, 1, ++ lua_pushfstring(L, "invalid conversion specifier '%%%s'", conv)); ++ return conv; /* to avoid warnings */ ++} ++ ++ ++static time_t l_checktime (lua_State *L, int arg) { ++ l_timet t = l_gettime(L, arg); ++ luaL_argcheck(L, (time_t)t == t, arg, "time out-of-bounds"); ++ return (time_t)t; ++} ++ ++ ++/* maximum size for an individual 'strftime' item */ ++#define SIZETIMEFMT 250 ++ ++ ++static int os_date (lua_State *L) { ++ size_t slen; ++ const char *s = luaL_optlstring(L, 1, "%c", &slen); ++ time_t t = luaL_opt(L, l_checktime, 2, time(NULL)); ++ const char *se = s + slen; /* 's' end */ ++ struct tm tmr, *stm; ++ if (*s == '!') { /* UTC? */ ++ stm = l_gmtime(&t, &tmr); ++ s++; /* skip '!' */ ++ } ++ else ++ stm = l_localtime(&t, &tmr); ++ if (stm == NULL) /* invalid date? */ ++ return luaL_error(L, ++ "date result cannot be represented in this installation"); ++ if (strcmp(s, "*t") == 0) { ++ lua_createtable(L, 0, 9); /* 9 = number of fields */ ++ setallfields(L, stm); ++ } ++ else { ++ char cc[4]; /* buffer for individual conversion specifiers */ ++ luaL_Buffer b; ++ cc[0] = '%'; ++ luaL_buffinit(L, &b); ++ while (s < se) { ++ if (*s != '%') /* not a conversion specifier? */ ++ luaL_addchar(&b, *s++); ++ else { ++ size_t reslen; ++ char *buff = luaL_prepbuffsize(&b, SIZETIMEFMT); ++ s++; /* skip '%' */ ++ s = checkoption(L, s, se - s, cc + 1); /* copy specifier to 'cc' */ ++ reslen = strftime(buff, SIZETIMEFMT, cc, stm); ++ luaL_addsize(&b, reslen); ++ } ++ } ++ luaL_pushresult(&b); ++ } ++ return 1; ++} ++ ++ ++static int os_time (lua_State *L) { ++ time_t t; ++ if (lua_isnoneornil(L, 1)) /* called without args? */ ++ t = time(NULL); /* get current time */ ++ else { ++ struct tm ts; ++ luaL_checktype(L, 1, LUA_TTABLE); ++ lua_settop(L, 1); /* make sure table is at the top */ ++ ts.tm_year = getfield(L, "year", -1, 1900); ++ ts.tm_mon = getfield(L, "month", -1, 1); ++ ts.tm_mday = getfield(L, "day", -1, 0); ++ ts.tm_hour = getfield(L, "hour", 12, 0); ++ ts.tm_min = getfield(L, "min", 0, 0); ++ ts.tm_sec = getfield(L, "sec", 0, 0); ++ ts.tm_isdst = getboolfield(L, "isdst"); ++ t = mktime(&ts); ++ setallfields(L, &ts); /* update fields with normalized values */ ++ } ++ if (t != (time_t)(l_timet)t || t == (time_t)(-1)) ++ return luaL_error(L, ++ "time result cannot be represented in this installation"); ++ l_pushtime(L, t); ++ return 1; ++} ++ ++ ++static int os_difftime (lua_State *L) { ++ time_t t1 = l_checktime(L, 1); ++ time_t t2 = l_checktime(L, 2); ++ lua_pushnumber(L, (lua_Number)difftime(t1, t2)); ++ return 1; ++} ++ ++/* }====================================================== */ ++ ++ ++static int os_setlocale (lua_State *L) { ++ static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, ++ LC_NUMERIC, LC_TIME}; ++ static const char *const catnames[] = {"all", "collate", "ctype", "monetary", ++ "numeric", "time", NULL}; ++ const char *l = luaL_optstring(L, 1, NULL); ++ int op = luaL_checkoption(L, 2, "all", catnames); ++ lua_pushstring(L, setlocale(cat[op], l)); ++ return 1; ++} ++ ++ ++static int os_exit (lua_State *L) { ++ int status; ++ if (lua_isboolean(L, 1)) ++ status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE); ++ else ++ status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS); ++ if (lua_toboolean(L, 2)) ++ lua_close(L); ++ if (L) exit(status); /* 'if' to avoid warnings for unreachable 'return' */ ++ return 0; ++} ++ ++ ++static const luaL_Reg syslib[] = { ++ {"clock", os_clock}, ++ {"date", os_date}, ++ {"difftime", os_difftime}, ++ {"execute", os_execute}, ++ {"exit", os_exit}, ++ {"getenv", os_getenv}, ++ {"remove", os_remove}, ++ {"rename", os_rename}, ++ {"setlocale", os_setlocale}, ++ {"time", os_time}, ++ {"tmpname", os_tmpname}, ++ {NULL, NULL} ++}; ++ ++/* }====================================================== */ ++ ++ ++ ++LUAMOD_API int luaopen_os (lua_State *L) { ++ luaL_newlib(L, syslib); ++ return 1; ++} ++ +diff --git a/src/bin/lua/lparser.c b/src/bin/lua/lparser.c +new file mode 100644 +index 0000000000..284ef1f0c4 +--- /dev/null ++++ b/src/bin/lua/lparser.c +@@ -0,0 +1,1956 @@ ++/* ++** $Id: lparser.c $ ++** Lua Parser ++** See Copyright Notice in lua.h ++*/ ++ ++#define lparser_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++ ++#include "lua.h" ++ ++#include "lcode.h" ++#include "ldebug.h" ++#include "ldo.h" ++#include "lfunc.h" ++#include "llex.h" ++#include "lmem.h" ++#include "lobject.h" ++#include "lopcodes.h" ++#include "lparser.h" ++#include "lstate.h" ++#include "lstring.h" ++#include "ltable.h" ++ ++ ++ ++/* maximum number of local variables per function (must be smaller ++ than 250, due to the bytecode format) */ ++#define MAXVARS 200 ++ ++ ++#define hasmultret(k) ((k) == VCALL || (k) == VVARARG) ++ ++ ++/* because all strings are unified by the scanner, the parser ++ can use pointer equality for string equality */ ++#define eqstr(a,b) ((a) == (b)) ++ ++ ++/* ++** nodes for block list (list of active blocks) ++*/ ++typedef struct BlockCnt { ++ struct BlockCnt *previous; /* chain */ ++ int firstlabel; /* index of first label in this block */ ++ int firstgoto; /* index of first pending goto in this block */ ++ lu_byte nactvar; /* # active locals outside the block */ ++ lu_byte upval; /* true if some variable in the block is an upvalue */ ++ lu_byte isloop; /* true if 'block' is a loop */ ++ lu_byte insidetbc; /* true if inside the scope of a to-be-closed var. */ ++} BlockCnt; ++ ++ ++ ++/* ++** prototypes for recursive non-terminal functions ++*/ ++static void statement (LexState *ls); ++static void expr (LexState *ls, expdesc *v); ++ ++ ++static l_noret error_expected (LexState *ls, int token) { ++ luaX_syntaxerror(ls, ++ luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token))); ++} ++ ++ ++static l_noret errorlimit (FuncState *fs, int limit, const char *what) { ++ lua_State *L = fs->ls->L; ++ const char *msg; ++ int line = fs->f->linedefined; ++ const char *where = (line == 0) ++ ? "main function" ++ : luaO_pushfstring(L, "function at line %d", line); ++ msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s", ++ what, limit, where); ++ luaX_syntaxerror(fs->ls, msg); ++} ++ ++ ++static void checklimit (FuncState *fs, int v, int l, const char *what) { ++ if (v > l) errorlimit(fs, l, what); ++} ++ ++ ++/* ++** Test whether next token is 'c'; if so, skip it. ++*/ ++static int testnext (LexState *ls, int c) { ++ if (ls->t.token == c) { ++ luaX_next(ls); ++ return 1; ++ } ++ else return 0; ++} ++ ++ ++/* ++** Check that next token is 'c'. ++*/ ++static void check (LexState *ls, int c) { ++ if (ls->t.token != c) ++ error_expected(ls, c); ++} ++ ++ ++/* ++** Check that next token is 'c' and skip it. ++*/ ++static void checknext (LexState *ls, int c) { ++ check(ls, c); ++ luaX_next(ls); ++} ++ ++ ++#define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); } ++ ++ ++/* ++** Check that next token is 'what' and skip it. In case of error, ++** raise an error that the expected 'what' should match a 'who' ++** in line 'where' (if that is not the current line). ++*/ ++static void check_match (LexState *ls, int what, int who, int where) { ++ if (l_unlikely(!testnext(ls, what))) { ++ if (where == ls->linenumber) /* all in the same line? */ ++ error_expected(ls, what); /* do not need a complex message */ ++ else { ++ luaX_syntaxerror(ls, luaO_pushfstring(ls->L, ++ "%s expected (to close %s at line %d)", ++ luaX_token2str(ls, what), luaX_token2str(ls, who), where)); ++ } ++ } ++} ++ ++ ++static TString *str_checkname (LexState *ls) { ++ TString *ts; ++ check(ls, TK_NAME); ++ ts = ls->t.seminfo.ts; ++ luaX_next(ls); ++ return ts; ++} ++ ++ ++static void init_exp (expdesc *e, expkind k, int i) { ++ e->f = e->t = NO_JUMP; ++ e->k = k; ++ e->u.info = i; ++} ++ ++ ++static void codestring (expdesc *e, TString *s) { ++ e->f = e->t = NO_JUMP; ++ e->k = VKSTR; ++ e->u.strval = s; ++} ++ ++ ++static void codename (LexState *ls, expdesc *e) { ++ codestring(e, str_checkname(ls)); ++} ++ ++ ++/* ++** Register a new local variable in the active 'Proto' (for debug ++** information). ++*/ ++static int registerlocalvar (LexState *ls, FuncState *fs, TString *varname) { ++ Proto *f = fs->f; ++ int oldsize = f->sizelocvars; ++ luaM_growvector(ls->L, f->locvars, fs->ndebugvars, f->sizelocvars, ++ LocVar, SHRT_MAX, "local variables"); ++ while (oldsize < f->sizelocvars) ++ f->locvars[oldsize++].varname = NULL; ++ f->locvars[fs->ndebugvars].varname = varname; ++ f->locvars[fs->ndebugvars].startpc = fs->pc; ++ luaC_objbarrier(ls->L, f, varname); ++ return fs->ndebugvars++; ++} ++ ++ ++/* ++** Create a new local variable with the given 'name'. Return its index ++** in the function. ++*/ ++static int new_localvar (LexState *ls, TString *name) { ++ lua_State *L = ls->L; ++ FuncState *fs = ls->fs; ++ Dyndata *dyd = ls->dyd; ++ Vardesc *var; ++ checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal, ++ MAXVARS, "local variables"); ++ luaM_growvector(L, dyd->actvar.arr, dyd->actvar.n + 1, ++ dyd->actvar.size, Vardesc, USHRT_MAX, "local variables"); ++ var = &dyd->actvar.arr[dyd->actvar.n++]; ++ var->vd.kind = VDKREG; /* default */ ++ var->vd.name = name; ++ return dyd->actvar.n - 1 - fs->firstlocal; ++} ++ ++#define new_localvarliteral(ls,v) \ ++ new_localvar(ls, \ ++ luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char)) - 1)); ++ ++ ++ ++/* ++** Return the "variable description" (Vardesc) of a given variable. ++** (Unless noted otherwise, all variables are referred to by their ++** compiler indices.) ++*/ ++static Vardesc *getlocalvardesc (FuncState *fs, int vidx) { ++ return &fs->ls->dyd->actvar.arr[fs->firstlocal + vidx]; ++} ++ ++ ++/* ++** Convert 'nvar', a compiler index level, to its corresponding ++** register. For that, search for the highest variable below that level ++** that is in a register and uses its register index ('ridx') plus one. ++*/ ++static int reglevel (FuncState *fs, int nvar) { ++ while (nvar-- > 0) { ++ Vardesc *vd = getlocalvardesc(fs, nvar); /* get previous variable */ ++ if (vd->vd.kind != RDKCTC) /* is in a register? */ ++ return vd->vd.ridx + 1; ++ } ++ return 0; /* no variables in registers */ ++} ++ ++ ++/* ++** Return the number of variables in the register stack for the given ++** function. ++*/ ++int luaY_nvarstack (FuncState *fs) { ++ return reglevel(fs, fs->nactvar); ++} ++ ++ ++/* ++** Get the debug-information entry for current variable 'vidx'. ++*/ ++static LocVar *localdebuginfo (FuncState *fs, int vidx) { ++ Vardesc *vd = getlocalvardesc(fs, vidx); ++ if (vd->vd.kind == RDKCTC) ++ return NULL; /* no debug info. for constants */ ++ else { ++ int idx = vd->vd.pidx; ++ lua_assert(idx < fs->ndebugvars); ++ return &fs->f->locvars[idx]; ++ } ++} ++ ++ ++/* ++** Create an expression representing variable 'vidx' ++*/ ++static void init_var (FuncState *fs, expdesc *e, int vidx) { ++ e->f = e->t = NO_JUMP; ++ e->k = VLOCAL; ++ e->u.var.vidx = vidx; ++ e->u.var.ridx = getlocalvardesc(fs, vidx)->vd.ridx; ++} ++ ++ ++/* ++** Raises an error if variable described by 'e' is read only ++*/ ++static void check_readonly (LexState *ls, expdesc *e) { ++ FuncState *fs = ls->fs; ++ TString *varname = NULL; /* to be set if variable is const */ ++ switch (e->k) { ++ case VCONST: { ++ varname = ls->dyd->actvar.arr[e->u.info].vd.name; ++ break; ++ } ++ case VLOCAL: { ++ Vardesc *vardesc = getlocalvardesc(fs, e->u.var.vidx); ++ if (vardesc->vd.kind != VDKREG) /* not a regular variable? */ ++ varname = vardesc->vd.name; ++ break; ++ } ++ case VUPVAL: { ++ Upvaldesc *up = &fs->f->upvalues[e->u.info]; ++ if (up->kind != VDKREG) ++ varname = up->name; ++ break; ++ } ++ default: ++ return; /* other cases cannot be read-only */ ++ } ++ if (varname) { ++ const char *msg = luaO_pushfstring(ls->L, ++ "attempt to assign to const variable '%s'", getstr(varname)); ++ luaK_semerror(ls, msg); /* error */ ++ } ++} ++ ++ ++/* ++** Start the scope for the last 'nvars' created variables. ++*/ ++static void adjustlocalvars (LexState *ls, int nvars) { ++ FuncState *fs = ls->fs; ++ int reglevel = luaY_nvarstack(fs); ++ int i; ++ for (i = 0; i < nvars; i++) { ++ int vidx = fs->nactvar++; ++ Vardesc *var = getlocalvardesc(fs, vidx); ++ var->vd.ridx = reglevel++; ++ var->vd.pidx = registerlocalvar(ls, fs, var->vd.name); ++ } ++} ++ ++ ++/* ++** Close the scope for all variables up to level 'tolevel'. ++** (debug info.) ++*/ ++static void removevars (FuncState *fs, int tolevel) { ++ fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel); ++ while (fs->nactvar > tolevel) { ++ LocVar *var = localdebuginfo(fs, --fs->nactvar); ++ if (var) /* does it have debug information? */ ++ var->endpc = fs->pc; ++ } ++} ++ ++ ++/* ++** Search the upvalues of the function 'fs' for one ++** with the given 'name'. ++*/ ++static int searchupvalue (FuncState *fs, TString *name) { ++ int i; ++ Upvaldesc *up = fs->f->upvalues; ++ for (i = 0; i < fs->nups; i++) { ++ if (eqstr(up[i].name, name)) return i; ++ } ++ return -1; /* not found */ ++} ++ ++ ++static Upvaldesc *allocupvalue (FuncState *fs) { ++ Proto *f = fs->f; ++ int oldsize = f->sizeupvalues; ++ checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues"); ++ luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues, ++ Upvaldesc, MAXUPVAL, "upvalues"); ++ while (oldsize < f->sizeupvalues) ++ f->upvalues[oldsize++].name = NULL; ++ return &f->upvalues[fs->nups++]; ++} ++ ++ ++static int newupvalue (FuncState *fs, TString *name, expdesc *v) { ++ Upvaldesc *up = allocupvalue(fs); ++ FuncState *prev = fs->prev; ++ if (v->k == VLOCAL) { ++ up->instack = 1; ++ up->idx = v->u.var.ridx; ++ up->kind = getlocalvardesc(prev, v->u.var.vidx)->vd.kind; ++ lua_assert(eqstr(name, getlocalvardesc(prev, v->u.var.vidx)->vd.name)); ++ } ++ else { ++ up->instack = 0; ++ up->idx = cast_byte(v->u.info); ++ up->kind = prev->f->upvalues[v->u.info].kind; ++ lua_assert(eqstr(name, prev->f->upvalues[v->u.info].name)); ++ } ++ up->name = name; ++ luaC_objbarrier(fs->ls->L, fs->f, name); ++ return fs->nups - 1; ++} ++ ++ ++/* ++** Look for an active local variable with the name 'n' in the ++** function 'fs'. If found, initialize 'var' with it and return ++** its expression kind; otherwise return -1. ++*/ ++static int searchvar (FuncState *fs, TString *n, expdesc *var) { ++ int i; ++ for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) { ++ Vardesc *vd = getlocalvardesc(fs, i); ++ if (eqstr(n, vd->vd.name)) { /* found? */ ++ if (vd->vd.kind == RDKCTC) /* compile-time constant? */ ++ init_exp(var, VCONST, fs->firstlocal + i); ++ else /* real variable */ ++ init_var(fs, var, i); ++ return var->k; ++ } ++ } ++ return -1; /* not found */ ++} ++ ++ ++/* ++** Mark block where variable at given level was defined ++** (to emit close instructions later). ++*/ ++static void markupval (FuncState *fs, int level) { ++ BlockCnt *bl = fs->bl; ++ while (bl->nactvar > level) ++ bl = bl->previous; ++ bl->upval = 1; ++ fs->needclose = 1; ++} ++ ++ ++/* ++** Find a variable with the given name 'n'. If it is an upvalue, add ++** this upvalue into all intermediate functions. If it is a global, set ++** 'var' as 'void' as a flag. ++*/ ++static void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) { ++ if (fs == NULL) /* no more levels? */ ++ init_exp(var, VVOID, 0); /* default is global */ ++ else { ++ int v = searchvar(fs, n, var); /* look up locals at current level */ ++ if (v >= 0) { /* found? */ ++ if (v == VLOCAL && !base) ++ markupval(fs, var->u.var.vidx); /* local will be used as an upval */ ++ } ++ else { /* not found as local at current level; try upvalues */ ++ int idx = searchupvalue(fs, n); /* try existing upvalues */ ++ if (idx < 0) { /* not found? */ ++ singlevaraux(fs->prev, n, var, 0); /* try upper levels */ ++ if (var->k == VLOCAL || var->k == VUPVAL) /* local or upvalue? */ ++ idx = newupvalue(fs, n, var); /* will be a new upvalue */ ++ else /* it is a global or a constant */ ++ return; /* don't need to do anything at this level */ ++ } ++ init_exp(var, VUPVAL, idx); /* new or old upvalue */ ++ } ++ } ++} ++ ++ ++/* ++** Find a variable with the given name 'n', handling global variables ++** too. ++*/ ++static void singlevar (LexState *ls, expdesc *var) { ++ TString *varname = str_checkname(ls); ++ FuncState *fs = ls->fs; ++ singlevaraux(fs, varname, var, 1); ++ if (var->k == VVOID) { /* global name? */ ++ expdesc key; ++ singlevaraux(fs, ls->envn, var, 1); /* get environment variable */ ++ lua_assert(var->k != VVOID); /* this one must exist */ ++ codestring(&key, varname); /* key is variable name */ ++ luaK_indexed(fs, var, &key); /* env[varname] */ ++ } ++} ++ ++ ++/* ++** Adjust the number of results from an expression list 'e' with 'nexps' ++** expressions to 'nvars' values. ++*/ ++static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) { ++ FuncState *fs = ls->fs; ++ int needed = nvars - nexps; /* extra values needed */ ++ if (hasmultret(e->k)) { /* last expression has multiple returns? */ ++ int extra = needed + 1; /* discount last expression itself */ ++ if (extra < 0) ++ extra = 0; ++ luaK_setreturns(fs, e, extra); /* last exp. provides the difference */ ++ } ++ else { ++ if (e->k != VVOID) /* at least one expression? */ ++ luaK_exp2nextreg(fs, e); /* close last expression */ ++ if (needed > 0) /* missing values? */ ++ luaK_nil(fs, fs->freereg, needed); /* complete with nils */ ++ } ++ if (needed > 0) ++ luaK_reserveregs(fs, needed); /* registers for extra values */ ++ else /* adding 'needed' is actually a subtraction */ ++ fs->freereg += needed; /* remove extra values */ ++} ++ ++ ++#define enterlevel(ls) luaE_incCstack(ls->L) ++ ++ ++#define leavelevel(ls) ((ls)->L->nCcalls--) ++ ++ ++/* ++** Generates an error that a goto jumps into the scope of some ++** local variable. ++*/ ++static l_noret jumpscopeerror (LexState *ls, Labeldesc *gt) { ++ const char *varname = getstr(getlocalvardesc(ls->fs, gt->nactvar)->vd.name); ++ const char *msg = " at line %d jumps into the scope of local '%s'"; ++ msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line, varname); ++ luaK_semerror(ls, msg); /* raise the error */ ++} ++ ++ ++/* ++** Solves the goto at index 'g' to given 'label' and removes it ++** from the list of pending goto's. ++** If it jumps into the scope of some variable, raises an error. ++*/ ++static void solvegoto (LexState *ls, int g, Labeldesc *label) { ++ int i; ++ Labellist *gl = &ls->dyd->gt; /* list of goto's */ ++ Labeldesc *gt = &gl->arr[g]; /* goto to be resolved */ ++ lua_assert(eqstr(gt->name, label->name)); ++ if (l_unlikely(gt->nactvar < label->nactvar)) /* enter some scope? */ ++ jumpscopeerror(ls, gt); ++ luaK_patchlist(ls->fs, gt->pc, label->pc); ++ for (i = g; i < gl->n - 1; i++) /* remove goto from pending list */ ++ gl->arr[i] = gl->arr[i + 1]; ++ gl->n--; ++} ++ ++ ++/* ++** Search for an active label with the given name. ++*/ ++static Labeldesc *findlabel (LexState *ls, TString *name) { ++ int i; ++ Dyndata *dyd = ls->dyd; ++ /* check labels in current function for a match */ ++ for (i = ls->fs->firstlabel; i < dyd->label.n; i++) { ++ Labeldesc *lb = &dyd->label.arr[i]; ++ if (eqstr(lb->name, name)) /* correct label? */ ++ return lb; ++ } ++ return NULL; /* label not found */ ++} ++ ++ ++/* ++** Adds a new label/goto in the corresponding list. ++*/ ++static int newlabelentry (LexState *ls, Labellist *l, TString *name, ++ int line, int pc) { ++ int n = l->n; ++ luaM_growvector(ls->L, l->arr, n, l->size, ++ Labeldesc, SHRT_MAX, "labels/gotos"); ++ l->arr[n].name = name; ++ l->arr[n].line = line; ++ l->arr[n].nactvar = ls->fs->nactvar; ++ l->arr[n].close = 0; ++ l->arr[n].pc = pc; ++ l->n = n + 1; ++ return n; ++} ++ ++ ++static int newgotoentry (LexState *ls, TString *name, int line, int pc) { ++ return newlabelentry(ls, &ls->dyd->gt, name, line, pc); ++} ++ ++ ++/* ++** Solves forward jumps. Check whether new label 'lb' matches any ++** pending gotos in current block and solves them. Return true ++** if any of the goto's need to close upvalues. ++*/ ++static int solvegotos (LexState *ls, Labeldesc *lb) { ++ Labellist *gl = &ls->dyd->gt; ++ int i = ls->fs->bl->firstgoto; ++ int needsclose = 0; ++ while (i < gl->n) { ++ if (eqstr(gl->arr[i].name, lb->name)) { ++ needsclose |= gl->arr[i].close; ++ solvegoto(ls, i, lb); /* will remove 'i' from the list */ ++ } ++ else ++ i++; ++ } ++ return needsclose; ++} ++ ++ ++/* ++** Create a new label with the given 'name' at the given 'line'. ++** 'last' tells whether label is the last non-op statement in its ++** block. Solves all pending goto's to this new label and adds ++** a close instruction if necessary. ++** Returns true iff it added a close instruction. ++*/ ++static int createlabel (LexState *ls, TString *name, int line, ++ int last) { ++ FuncState *fs = ls->fs; ++ Labellist *ll = &ls->dyd->label; ++ int l = newlabelentry(ls, ll, name, line, luaK_getlabel(fs)); ++ if (last) { /* label is last no-op statement in the block? */ ++ /* assume that locals are already out of scope */ ++ ll->arr[l].nactvar = fs->bl->nactvar; ++ } ++ if (solvegotos(ls, &ll->arr[l])) { /* need close? */ ++ luaK_codeABC(fs, OP_CLOSE, luaY_nvarstack(fs), 0, 0); ++ return 1; ++ } ++ return 0; ++} ++ ++ ++/* ++** Adjust pending gotos to outer level of a block. ++*/ ++static void movegotosout (FuncState *fs, BlockCnt *bl) { ++ int i; ++ Labellist *gl = &fs->ls->dyd->gt; ++ /* correct pending gotos to current block */ ++ for (i = bl->firstgoto; i < gl->n; i++) { /* for each pending goto */ ++ Labeldesc *gt = &gl->arr[i]; ++ /* leaving a variable scope? */ ++ if (reglevel(fs, gt->nactvar) > reglevel(fs, bl->nactvar)) ++ gt->close |= bl->upval; /* jump may need a close */ ++ gt->nactvar = bl->nactvar; /* update goto level */ ++ } ++} ++ ++ ++static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) { ++ bl->isloop = isloop; ++ bl->nactvar = fs->nactvar; ++ bl->firstlabel = fs->ls->dyd->label.n; ++ bl->firstgoto = fs->ls->dyd->gt.n; ++ bl->upval = 0; ++ bl->insidetbc = (fs->bl != NULL && fs->bl->insidetbc); ++ bl->previous = fs->bl; ++ fs->bl = bl; ++ lua_assert(fs->freereg == luaY_nvarstack(fs)); ++} ++ ++ ++/* ++** generates an error for an undefined 'goto'. ++*/ ++static l_noret undefgoto (LexState *ls, Labeldesc *gt) { ++ const char *msg; ++ if (eqstr(gt->name, luaS_newliteral(ls->L, "break"))) { ++ msg = "break outside loop at line %d"; ++ msg = luaO_pushfstring(ls->L, msg, gt->line); ++ } ++ else { ++ msg = "no visible label '%s' for at line %d"; ++ msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line); ++ } ++ luaK_semerror(ls, msg); ++} ++ ++ ++static void leaveblock (FuncState *fs) { ++ BlockCnt *bl = fs->bl; ++ LexState *ls = fs->ls; ++ int hasclose = 0; ++ int stklevel = reglevel(fs, bl->nactvar); /* level outside the block */ ++ if (bl->isloop) /* fix pending breaks? */ ++ hasclose = createlabel(ls, luaS_newliteral(ls->L, "break"), 0, 0); ++ if (!hasclose && bl->previous && bl->upval) ++ luaK_codeABC(fs, OP_CLOSE, stklevel, 0, 0); ++ fs->bl = bl->previous; ++ removevars(fs, bl->nactvar); ++ lua_assert(bl->nactvar == fs->nactvar); ++ fs->freereg = stklevel; /* free registers */ ++ ls->dyd->label.n = bl->firstlabel; /* remove local labels */ ++ if (bl->previous) /* inner block? */ ++ movegotosout(fs, bl); /* update pending gotos to outer block */ ++ else { ++ if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */ ++ undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */ ++ } ++} ++ ++ ++/* ++** adds a new prototype into list of prototypes ++*/ ++static Proto *addprototype (LexState *ls) { ++ Proto *clp; ++ lua_State *L = ls->L; ++ FuncState *fs = ls->fs; ++ Proto *f = fs->f; /* prototype of current function */ ++ if (fs->np >= f->sizep) { ++ int oldsize = f->sizep; ++ luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions"); ++ while (oldsize < f->sizep) ++ f->p[oldsize++] = NULL; ++ } ++ f->p[fs->np++] = clp = luaF_newproto(L); ++ luaC_objbarrier(L, f, clp); ++ return clp; ++} ++ ++ ++/* ++** codes instruction to create new closure in parent function. ++** The OP_CLOSURE instruction uses the last available register, ++** so that, if it invokes the GC, the GC knows which registers ++** are in use at that time. ++ ++*/ ++static void codeclosure (LexState *ls, expdesc *v) { ++ FuncState *fs = ls->fs->prev; ++ init_exp(v, VRELOC, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1)); ++ luaK_exp2nextreg(fs, v); /* fix it at the last register */ ++} ++ ++ ++static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) { ++ Proto *f = fs->f; ++ fs->prev = ls->fs; /* linked list of funcstates */ ++ fs->ls = ls; ++ ls->fs = fs; ++ fs->pc = 0; ++ fs->previousline = f->linedefined; ++ fs->iwthabs = 0; ++ fs->lasttarget = 0; ++ fs->freereg = 0; ++ fs->nk = 0; ++ fs->nabslineinfo = 0; ++ fs->np = 0; ++ fs->nups = 0; ++ fs->ndebugvars = 0; ++ fs->nactvar = 0; ++ fs->needclose = 0; ++ fs->firstlocal = ls->dyd->actvar.n; ++ fs->firstlabel = ls->dyd->label.n; ++ fs->bl = NULL; ++ f->source = ls->source; ++ luaC_objbarrier(ls->L, f, f->source); ++ f->maxstacksize = 2; /* registers 0/1 are always valid */ ++ enterblock(fs, bl, 0); ++} ++ ++ ++static void close_func (LexState *ls) { ++ lua_State *L = ls->L; ++ FuncState *fs = ls->fs; ++ Proto *f = fs->f; ++ luaK_ret(fs, luaY_nvarstack(fs), 0); /* final return */ ++ leaveblock(fs); ++ lua_assert(fs->bl == NULL); ++ luaK_finish(fs); ++ luaM_shrinkvector(L, f->code, f->sizecode, fs->pc, Instruction); ++ luaM_shrinkvector(L, f->lineinfo, f->sizelineinfo, fs->pc, ls_byte); ++ luaM_shrinkvector(L, f->abslineinfo, f->sizeabslineinfo, ++ fs->nabslineinfo, AbsLineInfo); ++ luaM_shrinkvector(L, f->k, f->sizek, fs->nk, TValue); ++ luaM_shrinkvector(L, f->p, f->sizep, fs->np, Proto *); ++ luaM_shrinkvector(L, f->locvars, f->sizelocvars, fs->ndebugvars, LocVar); ++ luaM_shrinkvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc); ++ ls->fs = fs->prev; ++ luaC_checkGC(L); ++} ++ ++ ++ ++/*============================================================*/ ++/* GRAMMAR RULES */ ++/*============================================================*/ ++ ++ ++/* ++** check whether current token is in the follow set of a block. ++** 'until' closes syntactical blocks, but do not close scope, ++** so it is handled in separate. ++*/ ++static int block_follow (LexState *ls, int withuntil) { ++ switch (ls->t.token) { ++ case TK_ELSE: case TK_ELSEIF: ++ case TK_END: case TK_EOS: ++ return 1; ++ case TK_UNTIL: return withuntil; ++ default: return 0; ++ } ++} ++ ++ ++static void statlist (LexState *ls) { ++ /* statlist -> { stat [';'] } */ ++ while (!block_follow(ls, 1)) { ++ if (ls->t.token == TK_RETURN) { ++ statement(ls); ++ return; /* 'return' must be last statement */ ++ } ++ statement(ls); ++ } ++} ++ ++ ++static void fieldsel (LexState *ls, expdesc *v) { ++ /* fieldsel -> ['.' | ':'] NAME */ ++ FuncState *fs = ls->fs; ++ expdesc key; ++ luaK_exp2anyregup(fs, v); ++ luaX_next(ls); /* skip the dot or colon */ ++ codename(ls, &key); ++ luaK_indexed(fs, v, &key); ++} ++ ++ ++static void yindex (LexState *ls, expdesc *v) { ++ /* index -> '[' expr ']' */ ++ luaX_next(ls); /* skip the '[' */ ++ expr(ls, v); ++ luaK_exp2val(ls->fs, v); ++ checknext(ls, ']'); ++} ++ ++ ++/* ++** {====================================================================== ++** Rules for Constructors ++** ======================================================================= ++*/ ++ ++ ++typedef struct ConsControl { ++ expdesc v; /* last list item read */ ++ expdesc *t; /* table descriptor */ ++ int nh; /* total number of 'record' elements */ ++ int na; /* number of array elements already stored */ ++ int tostore; /* number of array elements pending to be stored */ ++} ConsControl; ++ ++ ++static void recfield (LexState *ls, ConsControl *cc) { ++ /* recfield -> (NAME | '['exp']') = exp */ ++ FuncState *fs = ls->fs; ++ int reg = ls->fs->freereg; ++ expdesc tab, key, val; ++ if (ls->t.token == TK_NAME) { ++ checklimit(fs, cc->nh, MAX_INT, "items in a constructor"); ++ codename(ls, &key); ++ } ++ else /* ls->t.token == '[' */ ++ yindex(ls, &key); ++ cc->nh++; ++ checknext(ls, '='); ++ tab = *cc->t; ++ luaK_indexed(fs, &tab, &key); ++ expr(ls, &val); ++ luaK_storevar(fs, &tab, &val); ++ fs->freereg = reg; /* free registers */ ++} ++ ++ ++static void closelistfield (FuncState *fs, ConsControl *cc) { ++ if (cc->v.k == VVOID) return; /* there is no list item */ ++ luaK_exp2nextreg(fs, &cc->v); ++ cc->v.k = VVOID; ++ if (cc->tostore == LFIELDS_PER_FLUSH) { ++ luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */ ++ cc->na += cc->tostore; ++ cc->tostore = 0; /* no more items pending */ ++ } ++} ++ ++ ++static void lastlistfield (FuncState *fs, ConsControl *cc) { ++ if (cc->tostore == 0) return; ++ if (hasmultret(cc->v.k)) { ++ luaK_setmultret(fs, &cc->v); ++ luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET); ++ cc->na--; /* do not count last expression (unknown number of elements) */ ++ } ++ else { ++ if (cc->v.k != VVOID) ++ luaK_exp2nextreg(fs, &cc->v); ++ luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); ++ } ++ cc->na += cc->tostore; ++} ++ ++ ++static void listfield (LexState *ls, ConsControl *cc) { ++ /* listfield -> exp */ ++ expr(ls, &cc->v); ++ cc->tostore++; ++} ++ ++ ++static void field (LexState *ls, ConsControl *cc) { ++ /* field -> listfield | recfield */ ++ switch(ls->t.token) { ++ case TK_NAME: { /* may be 'listfield' or 'recfield' */ ++ if (luaX_lookahead(ls) != '=') /* expression? */ ++ listfield(ls, cc); ++ else ++ recfield(ls, cc); ++ break; ++ } ++ case '[': { ++ recfield(ls, cc); ++ break; ++ } ++ default: { ++ listfield(ls, cc); ++ break; ++ } ++ } ++} ++ ++ ++static void constructor (LexState *ls, expdesc *t) { ++ /* constructor -> '{' [ field { sep field } [sep] ] '}' ++ sep -> ',' | ';' */ ++ FuncState *fs = ls->fs; ++ int line = ls->linenumber; ++ int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0); ++ ConsControl cc; ++ luaK_code(fs, 0); /* space for extra arg. */ ++ cc.na = cc.nh = cc.tostore = 0; ++ cc.t = t; ++ init_exp(t, VNONRELOC, fs->freereg); /* table will be at stack top */ ++ luaK_reserveregs(fs, 1); ++ init_exp(&cc.v, VVOID, 0); /* no value (yet) */ ++ checknext(ls, '{'); ++ do { ++ lua_assert(cc.v.k == VVOID || cc.tostore > 0); ++ if (ls->t.token == '}') break; ++ closelistfield(fs, &cc); ++ field(ls, &cc); ++ } while (testnext(ls, ',') || testnext(ls, ';')); ++ check_match(ls, '}', '{', line); ++ lastlistfield(fs, &cc); ++ luaK_settablesize(fs, pc, t->u.info, cc.na, cc.nh); ++} ++ ++/* }====================================================================== */ ++ ++ ++static void setvararg (FuncState *fs, int nparams) { ++ fs->f->is_vararg = 1; ++ luaK_codeABC(fs, OP_VARARGPREP, nparams, 0, 0); ++} ++ ++ ++static void parlist (LexState *ls) { ++ /* parlist -> [ {NAME ','} (NAME | '...') ] */ ++ FuncState *fs = ls->fs; ++ Proto *f = fs->f; ++ int nparams = 0; ++ int isvararg = 0; ++ if (ls->t.token != ')') { /* is 'parlist' not empty? */ ++ do { ++ switch (ls->t.token) { ++ case TK_NAME: { ++ new_localvar(ls, str_checkname(ls)); ++ nparams++; ++ break; ++ } ++ case TK_DOTS: { ++ luaX_next(ls); ++ isvararg = 1; ++ break; ++ } ++ default: luaX_syntaxerror(ls, " or '...' expected"); ++ } ++ } while (!isvararg && testnext(ls, ',')); ++ } ++ adjustlocalvars(ls, nparams); ++ f->numparams = cast_byte(fs->nactvar); ++ if (isvararg) ++ setvararg(fs, f->numparams); /* declared vararg */ ++ luaK_reserveregs(fs, fs->nactvar); /* reserve registers for parameters */ ++} ++ ++ ++static void body (LexState *ls, expdesc *e, int ismethod, int line) { ++ /* body -> '(' parlist ')' block END */ ++ FuncState new_fs; ++ BlockCnt bl; ++ new_fs.f = addprototype(ls); ++ new_fs.f->linedefined = line; ++ open_func(ls, &new_fs, &bl); ++ checknext(ls, '('); ++ if (ismethod) { ++ new_localvarliteral(ls, "self"); /* create 'self' parameter */ ++ adjustlocalvars(ls, 1); ++ } ++ parlist(ls); ++ checknext(ls, ')'); ++ statlist(ls); ++ new_fs.f->lastlinedefined = ls->linenumber; ++ check_match(ls, TK_END, TK_FUNCTION, line); ++ codeclosure(ls, e); ++ close_func(ls); ++} ++ ++ ++static int explist (LexState *ls, expdesc *v) { ++ /* explist -> expr { ',' expr } */ ++ int n = 1; /* at least one expression */ ++ expr(ls, v); ++ while (testnext(ls, ',')) { ++ luaK_exp2nextreg(ls->fs, v); ++ expr(ls, v); ++ n++; ++ } ++ return n; ++} ++ ++ ++static void funcargs (LexState *ls, expdesc *f, int line) { ++ FuncState *fs = ls->fs; ++ expdesc args; ++ int base, nparams; ++ switch (ls->t.token) { ++ case '(': { /* funcargs -> '(' [ explist ] ')' */ ++ luaX_next(ls); ++ if (ls->t.token == ')') /* arg list is empty? */ ++ args.k = VVOID; ++ else { ++ explist(ls, &args); ++ if (hasmultret(args.k)) ++ luaK_setmultret(fs, &args); ++ } ++ check_match(ls, ')', '(', line); ++ break; ++ } ++ case '{': { /* funcargs -> constructor */ ++ constructor(ls, &args); ++ break; ++ } ++ case TK_STRING: { /* funcargs -> STRING */ ++ codestring(&args, ls->t.seminfo.ts); ++ luaX_next(ls); /* must use 'seminfo' before 'next' */ ++ break; ++ } ++ default: { ++ luaX_syntaxerror(ls, "function arguments expected"); ++ } ++ } ++ lua_assert(f->k == VNONRELOC); ++ base = f->u.info; /* base register for call */ ++ if (hasmultret(args.k)) ++ nparams = LUA_MULTRET; /* open call */ ++ else { ++ if (args.k != VVOID) ++ luaK_exp2nextreg(fs, &args); /* close last argument */ ++ nparams = fs->freereg - (base+1); ++ } ++ init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2)); ++ luaK_fixline(fs, line); ++ fs->freereg = base+1; /* call remove function and arguments and leaves ++ (unless changed) one result */ ++} ++ ++ ++ ++ ++/* ++** {====================================================================== ++** Expression parsing ++** ======================================================================= ++*/ ++ ++ ++static void primaryexp (LexState *ls, expdesc *v) { ++ /* primaryexp -> NAME | '(' expr ')' */ ++ switch (ls->t.token) { ++ case '(': { ++ int line = ls->linenumber; ++ luaX_next(ls); ++ expr(ls, v); ++ check_match(ls, ')', '(', line); ++ luaK_dischargevars(ls->fs, v); ++ return; ++ } ++ case TK_NAME: { ++ singlevar(ls, v); ++ return; ++ } ++ default: { ++ luaX_syntaxerror(ls, "unexpected symbol"); ++ } ++ } ++} ++ ++ ++static void suffixedexp (LexState *ls, expdesc *v) { ++ /* suffixedexp -> ++ primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */ ++ FuncState *fs = ls->fs; ++ int line = ls->linenumber; ++ primaryexp(ls, v); ++ for (;;) { ++ switch (ls->t.token) { ++ case '.': { /* fieldsel */ ++ fieldsel(ls, v); ++ break; ++ } ++ case '[': { /* '[' exp ']' */ ++ expdesc key; ++ luaK_exp2anyregup(fs, v); ++ yindex(ls, &key); ++ luaK_indexed(fs, v, &key); ++ break; ++ } ++ case ':': { /* ':' NAME funcargs */ ++ expdesc key; ++ luaX_next(ls); ++ codename(ls, &key); ++ luaK_self(fs, v, &key); ++ funcargs(ls, v, line); ++ break; ++ } ++ case '(': case TK_STRING: case '{': { /* funcargs */ ++ luaK_exp2nextreg(fs, v); ++ funcargs(ls, v, line); ++ break; ++ } ++ default: return; ++ } ++ } ++} ++ ++ ++static void simpleexp (LexState *ls, expdesc *v) { ++ /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... | ++ constructor | FUNCTION body | suffixedexp */ ++ switch (ls->t.token) { ++ case TK_FLT: { ++ init_exp(v, VKFLT, 0); ++ v->u.nval = ls->t.seminfo.r; ++ break; ++ } ++ case TK_INT: { ++ init_exp(v, VKINT, 0); ++ v->u.ival = ls->t.seminfo.i; ++ break; ++ } ++ case TK_STRING: { ++ codestring(v, ls->t.seminfo.ts); ++ break; ++ } ++ case TK_NIL: { ++ init_exp(v, VNIL, 0); ++ break; ++ } ++ case TK_TRUE: { ++ init_exp(v, VTRUE, 0); ++ break; ++ } ++ case TK_FALSE: { ++ init_exp(v, VFALSE, 0); ++ break; ++ } ++ case TK_DOTS: { /* vararg */ ++ FuncState *fs = ls->fs; ++ check_condition(ls, fs->f->is_vararg, ++ "cannot use '...' outside a vararg function"); ++ init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 0, 1)); ++ break; ++ } ++ case '{': { /* constructor */ ++ constructor(ls, v); ++ return; ++ } ++ case TK_FUNCTION: { ++ luaX_next(ls); ++ body(ls, v, 0, ls->linenumber); ++ return; ++ } ++ default: { ++ suffixedexp(ls, v); ++ return; ++ } ++ } ++ luaX_next(ls); ++} ++ ++ ++static UnOpr getunopr (int op) { ++ switch (op) { ++ case TK_NOT: return OPR_NOT; ++ case '-': return OPR_MINUS; ++ case '~': return OPR_BNOT; ++ case '#': return OPR_LEN; ++ default: return OPR_NOUNOPR; ++ } ++} ++ ++ ++static BinOpr getbinopr (int op) { ++ switch (op) { ++ case '+': return OPR_ADD; ++ case '-': return OPR_SUB; ++ case '*': return OPR_MUL; ++ case '%': return OPR_MOD; ++ case '^': return OPR_POW; ++ case '/': return OPR_DIV; ++ case TK_IDIV: return OPR_IDIV; ++ case '&': return OPR_BAND; ++ case '|': return OPR_BOR; ++ case '~': return OPR_BXOR; ++ case TK_SHL: return OPR_SHL; ++ case TK_SHR: return OPR_SHR; ++ case TK_CONCAT: return OPR_CONCAT; ++ case TK_NE: return OPR_NE; ++ case TK_EQ: return OPR_EQ; ++ case '<': return OPR_LT; ++ case TK_LE: return OPR_LE; ++ case '>': return OPR_GT; ++ case TK_GE: return OPR_GE; ++ case TK_AND: return OPR_AND; ++ case TK_OR: return OPR_OR; ++ default: return OPR_NOBINOPR; ++ } ++} ++ ++ ++/* ++** Priority table for binary operators. ++*/ ++static const struct { ++ lu_byte left; /* left priority for each binary operator */ ++ lu_byte right; /* right priority */ ++} priority[] = { /* ORDER OPR */ ++ {10, 10}, {10, 10}, /* '+' '-' */ ++ {11, 11}, {11, 11}, /* '*' '%' */ ++ {14, 13}, /* '^' (right associative) */ ++ {11, 11}, {11, 11}, /* '/' '//' */ ++ {6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */ ++ {7, 7}, {7, 7}, /* '<<' '>>' */ ++ {9, 8}, /* '..' (right associative) */ ++ {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */ ++ {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */ ++ {2, 2}, {1, 1} /* and, or */ ++}; ++ ++#define UNARY_PRIORITY 12 /* priority for unary operators */ ++ ++ ++/* ++** subexpr -> (simpleexp | unop subexpr) { binop subexpr } ++** where 'binop' is any binary operator with a priority higher than 'limit' ++*/ ++static BinOpr subexpr (LexState *ls, expdesc *v, int limit) { ++ BinOpr op; ++ UnOpr uop; ++ enterlevel(ls); ++ uop = getunopr(ls->t.token); ++ if (uop != OPR_NOUNOPR) { /* prefix (unary) operator? */ ++ int line = ls->linenumber; ++ luaX_next(ls); /* skip operator */ ++ subexpr(ls, v, UNARY_PRIORITY); ++ luaK_prefix(ls->fs, uop, v, line); ++ } ++ else simpleexp(ls, v); ++ /* expand while operators have priorities higher than 'limit' */ ++ op = getbinopr(ls->t.token); ++ while (op != OPR_NOBINOPR && priority[op].left > limit) { ++ expdesc v2; ++ BinOpr nextop; ++ int line = ls->linenumber; ++ luaX_next(ls); /* skip operator */ ++ luaK_infix(ls->fs, op, v); ++ /* read sub-expression with higher priority */ ++ nextop = subexpr(ls, &v2, priority[op].right); ++ luaK_posfix(ls->fs, op, v, &v2, line); ++ op = nextop; ++ } ++ leavelevel(ls); ++ return op; /* return first untreated operator */ ++} ++ ++ ++static void expr (LexState *ls, expdesc *v) { ++ subexpr(ls, v, 0); ++} ++ ++/* }==================================================================== */ ++ ++ ++ ++/* ++** {====================================================================== ++** Rules for Statements ++** ======================================================================= ++*/ ++ ++ ++static void block (LexState *ls) { ++ /* block -> statlist */ ++ FuncState *fs = ls->fs; ++ BlockCnt bl; ++ enterblock(fs, &bl, 0); ++ statlist(ls); ++ leaveblock(fs); ++} ++ ++ ++/* ++** structure to chain all variables in the left-hand side of an ++** assignment ++*/ ++struct LHS_assign { ++ struct LHS_assign *prev; ++ expdesc v; /* variable (global, local, upvalue, or indexed) */ ++}; ++ ++ ++/* ++** check whether, in an assignment to an upvalue/local variable, the ++** upvalue/local variable is begin used in a previous assignment to a ++** table. If so, save original upvalue/local value in a safe place and ++** use this safe copy in the previous assignment. ++*/ ++static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) { ++ FuncState *fs = ls->fs; ++ int extra = fs->freereg; /* eventual position to save local variable */ ++ int conflict = 0; ++ for (; lh; lh = lh->prev) { /* check all previous assignments */ ++ if (vkisindexed(lh->v.k)) { /* assignment to table field? */ ++ if (lh->v.k == VINDEXUP) { /* is table an upvalue? */ ++ if (v->k == VUPVAL && lh->v.u.ind.t == v->u.info) { ++ conflict = 1; /* table is the upvalue being assigned now */ ++ lh->v.k = VINDEXSTR; ++ lh->v.u.ind.t = extra; /* assignment will use safe copy */ ++ } ++ } ++ else { /* table is a register */ ++ if (v->k == VLOCAL && lh->v.u.ind.t == v->u.var.ridx) { ++ conflict = 1; /* table is the local being assigned now */ ++ lh->v.u.ind.t = extra; /* assignment will use safe copy */ ++ } ++ /* is index the local being assigned? */ ++ if (lh->v.k == VINDEXED && v->k == VLOCAL && ++ lh->v.u.ind.idx == v->u.var.ridx) { ++ conflict = 1; ++ lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */ ++ } ++ } ++ } ++ } ++ if (conflict) { ++ /* copy upvalue/local value to a temporary (in position 'extra') */ ++ if (v->k == VLOCAL) ++ luaK_codeABC(fs, OP_MOVE, extra, v->u.var.ridx, 0); ++ else ++ luaK_codeABC(fs, OP_GETUPVAL, extra, v->u.info, 0); ++ luaK_reserveregs(fs, 1); ++ } ++} ++ ++/* ++** Parse and compile a multiple assignment. The first "variable" ++** (a 'suffixedexp') was already read by the caller. ++** ++** assignment -> suffixedexp restassign ++** restassign -> ',' suffixedexp restassign | '=' explist ++*/ ++static void restassign (LexState *ls, struct LHS_assign *lh, int nvars) { ++ expdesc e; ++ check_condition(ls, vkisvar(lh->v.k), "syntax error"); ++ check_readonly(ls, &lh->v); ++ if (testnext(ls, ',')) { /* restassign -> ',' suffixedexp restassign */ ++ struct LHS_assign nv; ++ nv.prev = lh; ++ suffixedexp(ls, &nv.v); ++ if (!vkisindexed(nv.v.k)) ++ check_conflict(ls, lh, &nv.v); ++ enterlevel(ls); /* control recursion depth */ ++ restassign(ls, &nv, nvars+1); ++ leavelevel(ls); ++ } ++ else { /* restassign -> '=' explist */ ++ int nexps; ++ checknext(ls, '='); ++ nexps = explist(ls, &e); ++ if (nexps != nvars) ++ adjust_assign(ls, nvars, nexps, &e); ++ else { ++ luaK_setoneret(ls->fs, &e); /* close last expression */ ++ luaK_storevar(ls->fs, &lh->v, &e); ++ return; /* avoid default */ ++ } ++ } ++ init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */ ++ luaK_storevar(ls->fs, &lh->v, &e); ++} ++ ++ ++static int cond (LexState *ls) { ++ /* cond -> exp */ ++ expdesc v; ++ expr(ls, &v); /* read condition */ ++ if (v.k == VNIL) v.k = VFALSE; /* 'falses' are all equal here */ ++ luaK_goiftrue(ls->fs, &v); ++ return v.f; ++} ++ ++ ++static void gotostat (LexState *ls) { ++ FuncState *fs = ls->fs; ++ int line = ls->linenumber; ++ TString *name = str_checkname(ls); /* label's name */ ++ Labeldesc *lb = findlabel(ls, name); ++ if (lb == NULL) /* no label? */ ++ /* forward jump; will be resolved when the label is declared */ ++ newgotoentry(ls, name, line, luaK_jump(fs)); ++ else { /* found a label */ ++ /* backward jump; will be resolved here */ ++ int lblevel = reglevel(fs, lb->nactvar); /* label level */ ++ if (luaY_nvarstack(fs) > lblevel) /* leaving the scope of a variable? */ ++ luaK_codeABC(fs, OP_CLOSE, lblevel, 0, 0); ++ /* create jump and link it to the label */ ++ luaK_patchlist(fs, luaK_jump(fs), lb->pc); ++ } ++} ++ ++ ++/* ++** Break statement. Semantically equivalent to "goto break". ++*/ ++static void breakstat (LexState *ls) { ++ int line = ls->linenumber; ++ luaX_next(ls); /* skip break */ ++ newgotoentry(ls, luaS_newliteral(ls->L, "break"), line, luaK_jump(ls->fs)); ++} ++ ++ ++/* ++** Check whether there is already a label with the given 'name'. ++*/ ++static void checkrepeated (LexState *ls, TString *name) { ++ Labeldesc *lb = findlabel(ls, name); ++ if (l_unlikely(lb != NULL)) { /* already defined? */ ++ const char *msg = "label '%s' already defined on line %d"; ++ msg = luaO_pushfstring(ls->L, msg, getstr(name), lb->line); ++ luaK_semerror(ls, msg); /* error */ ++ } ++} ++ ++ ++static void labelstat (LexState *ls, TString *name, int line) { ++ /* label -> '::' NAME '::' */ ++ checknext(ls, TK_DBCOLON); /* skip double colon */ ++ while (ls->t.token == ';' || ls->t.token == TK_DBCOLON) ++ statement(ls); /* skip other no-op statements */ ++ checkrepeated(ls, name); /* check for repeated labels */ ++ createlabel(ls, name, line, block_follow(ls, 0)); ++} ++ ++ ++static void whilestat (LexState *ls, int line) { ++ /* whilestat -> WHILE cond DO block END */ ++ FuncState *fs = ls->fs; ++ int whileinit; ++ int condexit; ++ BlockCnt bl; ++ luaX_next(ls); /* skip WHILE */ ++ whileinit = luaK_getlabel(fs); ++ condexit = cond(ls); ++ enterblock(fs, &bl, 1); ++ checknext(ls, TK_DO); ++ block(ls); ++ luaK_jumpto(fs, whileinit); ++ check_match(ls, TK_END, TK_WHILE, line); ++ leaveblock(fs); ++ luaK_patchtohere(fs, condexit); /* false conditions finish the loop */ ++} ++ ++ ++static void repeatstat (LexState *ls, int line) { ++ /* repeatstat -> REPEAT block UNTIL cond */ ++ int condexit; ++ FuncState *fs = ls->fs; ++ int repeat_init = luaK_getlabel(fs); ++ BlockCnt bl1, bl2; ++ enterblock(fs, &bl1, 1); /* loop block */ ++ enterblock(fs, &bl2, 0); /* scope block */ ++ luaX_next(ls); /* skip REPEAT */ ++ statlist(ls); ++ check_match(ls, TK_UNTIL, TK_REPEAT, line); ++ condexit = cond(ls); /* read condition (inside scope block) */ ++ leaveblock(fs); /* finish scope */ ++ if (bl2.upval) { /* upvalues? */ ++ int exit = luaK_jump(fs); /* normal exit must jump over fix */ ++ luaK_patchtohere(fs, condexit); /* repetition must close upvalues */ ++ luaK_codeABC(fs, OP_CLOSE, reglevel(fs, bl2.nactvar), 0, 0); ++ condexit = luaK_jump(fs); /* repeat after closing upvalues */ ++ luaK_patchtohere(fs, exit); /* normal exit comes to here */ ++ } ++ luaK_patchlist(fs, condexit, repeat_init); /* close the loop */ ++ leaveblock(fs); /* finish loop */ ++} ++ ++ ++/* ++** Read an expression and generate code to put its results in next ++** stack slot. ++** ++*/ ++static void exp1 (LexState *ls) { ++ expdesc e; ++ expr(ls, &e); ++ luaK_exp2nextreg(ls->fs, &e); ++ lua_assert(e.k == VNONRELOC); ++} ++ ++ ++/* ++** Fix for instruction at position 'pc' to jump to 'dest'. ++** (Jump addresses are relative in Lua). 'back' true means ++** a back jump. ++*/ ++static void fixforjump (FuncState *fs, int pc, int dest, int back) { ++ Instruction *jmp = &fs->f->code[pc]; ++ int offset = dest - (pc + 1); ++ if (back) ++ offset = -offset; ++ if (l_unlikely(offset > MAXARG_Bx)) ++ luaX_syntaxerror(fs->ls, "control structure too long"); ++ SETARG_Bx(*jmp, offset); ++} ++ ++ ++/* ++** Generate code for a 'for' loop. ++*/ ++static void forbody (LexState *ls, int base, int line, int nvars, int isgen) { ++ /* forbody -> DO block */ ++ static const OpCode forprep[2] = {OP_FORPREP, OP_TFORPREP}; ++ static const OpCode forloop[2] = {OP_FORLOOP, OP_TFORLOOP}; ++ BlockCnt bl; ++ FuncState *fs = ls->fs; ++ int prep, endfor; ++ checknext(ls, TK_DO); ++ prep = luaK_codeABx(fs, forprep[isgen], base, 0); ++ enterblock(fs, &bl, 0); /* scope for declared variables */ ++ adjustlocalvars(ls, nvars); ++ luaK_reserveregs(fs, nvars); ++ block(ls); ++ leaveblock(fs); /* end of scope for declared variables */ ++ fixforjump(fs, prep, luaK_getlabel(fs), 0); ++ if (isgen) { /* generic for? */ ++ luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars); ++ luaK_fixline(fs, line); ++ } ++ endfor = luaK_codeABx(fs, forloop[isgen], base, 0); ++ fixforjump(fs, endfor, prep + 1, 1); ++ luaK_fixline(fs, line); ++} ++ ++ ++static void fornum (LexState *ls, TString *varname, int line) { ++ /* fornum -> NAME = exp,exp[,exp] forbody */ ++ FuncState *fs = ls->fs; ++ int base = fs->freereg; ++ new_localvarliteral(ls, "(for state)"); ++ new_localvarliteral(ls, "(for state)"); ++ new_localvarliteral(ls, "(for state)"); ++ new_localvar(ls, varname); ++ checknext(ls, '='); ++ exp1(ls); /* initial value */ ++ checknext(ls, ','); ++ exp1(ls); /* limit */ ++ if (testnext(ls, ',')) ++ exp1(ls); /* optional step */ ++ else { /* default step = 1 */ ++ luaK_int(fs, fs->freereg, 1); ++ luaK_reserveregs(fs, 1); ++ } ++ adjustlocalvars(ls, 3); /* control variables */ ++ forbody(ls, base, line, 1, 0); ++} ++ ++ ++static void forlist (LexState *ls, TString *indexname) { ++ /* forlist -> NAME {,NAME} IN explist forbody */ ++ FuncState *fs = ls->fs; ++ expdesc e; ++ int nvars = 5; /* gen, state, control, toclose, 'indexname' */ ++ int line; ++ int base = fs->freereg; ++ /* create control variables */ ++ new_localvarliteral(ls, "(for state)"); ++ new_localvarliteral(ls, "(for state)"); ++ new_localvarliteral(ls, "(for state)"); ++ new_localvarliteral(ls, "(for state)"); ++ /* create declared variables */ ++ new_localvar(ls, indexname); ++ while (testnext(ls, ',')) { ++ new_localvar(ls, str_checkname(ls)); ++ nvars++; ++ } ++ checknext(ls, TK_IN); ++ line = ls->linenumber; ++ adjust_assign(ls, 4, explist(ls, &e), &e); ++ adjustlocalvars(ls, 4); /* control variables */ ++ markupval(fs, fs->nactvar); /* last control var. must be closed */ ++ luaK_checkstack(fs, 3); /* extra space to call generator */ ++ forbody(ls, base, line, nvars - 4, 1); ++} ++ ++ ++static void forstat (LexState *ls, int line) { ++ /* forstat -> FOR (fornum | forlist) END */ ++ FuncState *fs = ls->fs; ++ TString *varname; ++ BlockCnt bl; ++ enterblock(fs, &bl, 1); /* scope for loop and control variables */ ++ luaX_next(ls); /* skip 'for' */ ++ varname = str_checkname(ls); /* first variable name */ ++ switch (ls->t.token) { ++ case '=': fornum(ls, varname, line); break; ++ case ',': case TK_IN: forlist(ls, varname); break; ++ default: luaX_syntaxerror(ls, "'=' or 'in' expected"); ++ } ++ check_match(ls, TK_END, TK_FOR, line); ++ leaveblock(fs); /* loop scope ('break' jumps to this point) */ ++} ++ ++ ++static void test_then_block (LexState *ls, int *escapelist) { ++ /* test_then_block -> [IF | ELSEIF] cond THEN block */ ++ BlockCnt bl; ++ FuncState *fs = ls->fs; ++ expdesc v; ++ int jf; /* instruction to skip 'then' code (if condition is false) */ ++ luaX_next(ls); /* skip IF or ELSEIF */ ++ expr(ls, &v); /* read condition */ ++ checknext(ls, TK_THEN); ++ if (ls->t.token == TK_BREAK) { /* 'if x then break' ? */ ++ int line = ls->linenumber; ++ luaK_goiffalse(ls->fs, &v); /* will jump if condition is true */ ++ luaX_next(ls); /* skip 'break' */ ++ enterblock(fs, &bl, 0); /* must enter block before 'goto' */ ++ newgotoentry(ls, luaS_newliteral(ls->L, "break"), line, v.t); ++ while (testnext(ls, ';')) {} /* skip semicolons */ ++ if (block_follow(ls, 0)) { /* jump is the entire block? */ ++ leaveblock(fs); ++ return; /* and that is it */ ++ } ++ else /* must skip over 'then' part if condition is false */ ++ jf = luaK_jump(fs); ++ } ++ else { /* regular case (not a break) */ ++ luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */ ++ enterblock(fs, &bl, 0); ++ jf = v.f; ++ } ++ statlist(ls); /* 'then' part */ ++ leaveblock(fs); ++ if (ls->t.token == TK_ELSE || ++ ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */ ++ luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */ ++ luaK_patchtohere(fs, jf); ++} ++ ++ ++static void ifstat (LexState *ls, int line) { ++ /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */ ++ FuncState *fs = ls->fs; ++ int escapelist = NO_JUMP; /* exit list for finished parts */ ++ test_then_block(ls, &escapelist); /* IF cond THEN block */ ++ while (ls->t.token == TK_ELSEIF) ++ test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */ ++ if (testnext(ls, TK_ELSE)) ++ block(ls); /* 'else' part */ ++ check_match(ls, TK_END, TK_IF, line); ++ luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */ ++} ++ ++ ++static void localfunc (LexState *ls) { ++ expdesc b; ++ FuncState *fs = ls->fs; ++ int fvar = fs->nactvar; /* function's variable index */ ++ new_localvar(ls, str_checkname(ls)); /* new local variable */ ++ adjustlocalvars(ls, 1); /* enter its scope */ ++ body(ls, &b, 0, ls->linenumber); /* function created in next register */ ++ /* debug information will only see the variable after this point! */ ++ localdebuginfo(fs, fvar)->startpc = fs->pc; ++} ++ ++ ++static int getlocalattribute (LexState *ls) { ++ /* ATTRIB -> ['<' Name '>'] */ ++ if (testnext(ls, '<')) { ++ const char *attr = getstr(str_checkname(ls)); ++ checknext(ls, '>'); ++ if (strcmp(attr, "const") == 0) ++ return RDKCONST; /* read-only variable */ ++ else if (strcmp(attr, "close") == 0) ++ return RDKTOCLOSE; /* to-be-closed variable */ ++ else ++ luaK_semerror(ls, ++ luaO_pushfstring(ls->L, "unknown attribute '%s'", attr)); ++ } ++ return VDKREG; /* regular variable */ ++} ++ ++ ++static void checktoclose (LexState *ls, int level) { ++ if (level != -1) { /* is there a to-be-closed variable? */ ++ FuncState *fs = ls->fs; ++ markupval(fs, level + 1); ++ fs->bl->insidetbc = 1; /* in the scope of a to-be-closed variable */ ++ luaK_codeABC(fs, OP_TBC, reglevel(fs, level), 0, 0); ++ } ++} ++ ++ ++static void localstat (LexState *ls) { ++ /* stat -> LOCAL NAME ATTRIB { ',' NAME ATTRIB } ['=' explist] */ ++ FuncState *fs = ls->fs; ++ int toclose = -1; /* index of to-be-closed variable (if any) */ ++ Vardesc *var; /* last variable */ ++ int vidx, kind; /* index and kind of last variable */ ++ int nvars = 0; ++ int nexps; ++ expdesc e; ++ do { ++ vidx = new_localvar(ls, str_checkname(ls)); ++ kind = getlocalattribute(ls); ++ getlocalvardesc(fs, vidx)->vd.kind = kind; ++ if (kind == RDKTOCLOSE) { /* to-be-closed? */ ++ if (toclose != -1) /* one already present? */ ++ luaK_semerror(ls, "multiple to-be-closed variables in local list"); ++ toclose = fs->nactvar + nvars; ++ } ++ nvars++; ++ } while (testnext(ls, ',')); ++ if (testnext(ls, '=')) ++ nexps = explist(ls, &e); ++ else { ++ e.k = VVOID; ++ nexps = 0; ++ } ++ var = getlocalvardesc(fs, vidx); /* get last variable */ ++ if (nvars == nexps && /* no adjustments? */ ++ var->vd.kind == RDKCONST && /* last variable is const? */ ++ luaK_exp2const(fs, &e, &var->k)) { /* compile-time constant? */ ++ var->vd.kind = RDKCTC; /* variable is a compile-time constant */ ++ adjustlocalvars(ls, nvars - 1); /* exclude last variable */ ++ fs->nactvar++; /* but count it */ ++ } ++ else { ++ adjust_assign(ls, nvars, nexps, &e); ++ adjustlocalvars(ls, nvars); ++ } ++ checktoclose(ls, toclose); ++} ++ ++ ++static int funcname (LexState *ls, expdesc *v) { ++ /* funcname -> NAME {fieldsel} [':' NAME] */ ++ int ismethod = 0; ++ singlevar(ls, v); ++ while (ls->t.token == '.') ++ fieldsel(ls, v); ++ if (ls->t.token == ':') { ++ ismethod = 1; ++ fieldsel(ls, v); ++ } ++ return ismethod; ++} ++ ++ ++static void funcstat (LexState *ls, int line) { ++ /* funcstat -> FUNCTION funcname body */ ++ int ismethod; ++ expdesc v, b; ++ luaX_next(ls); /* skip FUNCTION */ ++ ismethod = funcname(ls, &v); ++ body(ls, &b, ismethod, line); ++ luaK_storevar(ls->fs, &v, &b); ++ luaK_fixline(ls->fs, line); /* definition "happens" in the first line */ ++} ++ ++ ++static void exprstat (LexState *ls) { ++ /* stat -> func | assignment */ ++ FuncState *fs = ls->fs; ++ struct LHS_assign v; ++ suffixedexp(ls, &v.v); ++ if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */ ++ v.prev = NULL; ++ restassign(ls, &v, 1); ++ } ++ else { /* stat -> func */ ++ Instruction *inst; ++ check_condition(ls, v.v.k == VCALL, "syntax error"); ++ inst = &getinstruction(fs, &v.v); ++ SETARG_C(*inst, 1); /* call statement uses no results */ ++ } ++} ++ ++ ++static void retstat (LexState *ls) { ++ /* stat -> RETURN [explist] [';'] */ ++ FuncState *fs = ls->fs; ++ expdesc e; ++ int nret; /* number of values being returned */ ++ int first = luaY_nvarstack(fs); /* first slot to be returned */ ++ if (block_follow(ls, 1) || ls->t.token == ';') ++ nret = 0; /* return no values */ ++ else { ++ nret = explist(ls, &e); /* optional return values */ ++ if (hasmultret(e.k)) { ++ luaK_setmultret(fs, &e); ++ if (e.k == VCALL && nret == 1 && !fs->bl->insidetbc) { /* tail call? */ ++ SET_OPCODE(getinstruction(fs,&e), OP_TAILCALL); ++ lua_assert(GETARG_A(getinstruction(fs,&e)) == luaY_nvarstack(fs)); ++ } ++ nret = LUA_MULTRET; /* return all values */ ++ } ++ else { ++ if (nret == 1) /* only one single value? */ ++ first = luaK_exp2anyreg(fs, &e); /* can use original slot */ ++ else { /* values must go to the top of the stack */ ++ luaK_exp2nextreg(fs, &e); ++ lua_assert(nret == fs->freereg - first); ++ } ++ } ++ } ++ luaK_ret(fs, first, nret); ++ testnext(ls, ';'); /* skip optional semicolon */ ++} ++ ++ ++static void statement (LexState *ls) { ++ int line = ls->linenumber; /* may be needed for error messages */ ++ enterlevel(ls); ++ switch (ls->t.token) { ++ case ';': { /* stat -> ';' (empty statement) */ ++ luaX_next(ls); /* skip ';' */ ++ break; ++ } ++ case TK_IF: { /* stat -> ifstat */ ++ ifstat(ls, line); ++ break; ++ } ++ case TK_WHILE: { /* stat -> whilestat */ ++ whilestat(ls, line); ++ break; ++ } ++ case TK_DO: { /* stat -> DO block END */ ++ luaX_next(ls); /* skip DO */ ++ block(ls); ++ check_match(ls, TK_END, TK_DO, line); ++ break; ++ } ++ case TK_FOR: { /* stat -> forstat */ ++ forstat(ls, line); ++ break; ++ } ++ case TK_REPEAT: { /* stat -> repeatstat */ ++ repeatstat(ls, line); ++ break; ++ } ++ case TK_FUNCTION: { /* stat -> funcstat */ ++ funcstat(ls, line); ++ break; ++ } ++ case TK_LOCAL: { /* stat -> localstat */ ++ luaX_next(ls); /* skip LOCAL */ ++ if (testnext(ls, TK_FUNCTION)) /* local function? */ ++ localfunc(ls); ++ else ++ localstat(ls); ++ break; ++ } ++ case TK_DBCOLON: { /* stat -> label */ ++ luaX_next(ls); /* skip double colon */ ++ labelstat(ls, str_checkname(ls), line); ++ break; ++ } ++ case TK_RETURN: { /* stat -> retstat */ ++ luaX_next(ls); /* skip RETURN */ ++ retstat(ls); ++ break; ++ } ++ case TK_BREAK: { /* stat -> breakstat */ ++ breakstat(ls); ++ break; ++ } ++ case TK_GOTO: { /* stat -> 'goto' NAME */ ++ luaX_next(ls); /* skip 'goto' */ ++ gotostat(ls); ++ break; ++ } ++ default: { /* stat -> func | assignment */ ++ exprstat(ls); ++ break; ++ } ++ } ++ lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg && ++ ls->fs->freereg >= luaY_nvarstack(ls->fs)); ++ ls->fs->freereg = luaY_nvarstack(ls->fs); /* free registers */ ++ leavelevel(ls); ++} ++ ++/* }====================================================================== */ ++ ++ ++/* ++** compiles the main function, which is a regular vararg function with an ++** upvalue named LUA_ENV ++*/ ++static void mainfunc (LexState *ls, FuncState *fs) { ++ BlockCnt bl; ++ Upvaldesc *env; ++ open_func(ls, fs, &bl); ++ setvararg(fs, 0); /* main function is always declared vararg */ ++ env = allocupvalue(fs); /* ...set environment upvalue */ ++ env->instack = 1; ++ env->idx = 0; ++ env->kind = VDKREG; ++ env->name = ls->envn; ++ luaC_objbarrier(ls->L, fs->f, env->name); ++ luaX_next(ls); /* read first token */ ++ statlist(ls); /* parse main body */ ++ check(ls, TK_EOS); ++ close_func(ls); ++} ++ ++ ++LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, ++ Dyndata *dyd, const char *name, int firstchar) { ++ LexState lexstate; ++ FuncState funcstate; ++ LClosure *cl = luaF_newLclosure(L, 1); /* create main closure */ ++ setclLvalue2s(L, L->top, cl); /* anchor it (to avoid being collected) */ ++ luaD_inctop(L); ++ lexstate.h = luaH_new(L); /* create table for scanner */ ++ sethvalue2s(L, L->top, lexstate.h); /* anchor it */ ++ luaD_inctop(L); ++ funcstate.f = cl->p = luaF_newproto(L); ++ luaC_objbarrier(L, cl, cl->p); ++ funcstate.f->source = luaS_new(L, name); /* create and anchor TString */ ++ luaC_objbarrier(L, funcstate.f, funcstate.f->source); ++ lexstate.buff = buff; ++ lexstate.dyd = dyd; ++ dyd->actvar.n = dyd->gt.n = dyd->label.n = 0; ++ luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar); ++ mainfunc(&lexstate, &funcstate); ++ lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs); ++ /* all scopes should be correctly finished */ ++ lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0); ++ L->top--; /* remove scanner's table */ ++ return cl; /* closure is on the stack, too */ ++} ++ +diff --git a/src/bin/lua/lparser.h b/src/bin/lua/lparser.h +new file mode 100644 +index 0000000000..5e4500f181 +--- /dev/null ++++ b/src/bin/lua/lparser.h +@@ -0,0 +1,171 @@ ++/* ++** $Id: lparser.h $ ++** Lua Parser ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef lparser_h ++#define lparser_h ++ ++#include "llimits.h" ++#include "lobject.h" ++#include "lzio.h" ++ ++ ++/* ++** Expression and variable descriptor. ++** Code generation for variables and expressions can be delayed to allow ++** optimizations; An 'expdesc' structure describes a potentially-delayed ++** variable/expression. It has a description of its "main" value plus a ++** list of conditional jumps that can also produce its value (generated ++** by short-circuit operators 'and'/'or'). ++*/ ++ ++/* kinds of variables/expressions */ ++typedef enum { ++ VVOID, /* when 'expdesc' describes the last expression of a list, ++ this kind means an empty list (so, no expression) */ ++ VNIL, /* constant nil */ ++ VTRUE, /* constant true */ ++ VFALSE, /* constant false */ ++ VK, /* constant in 'k'; info = index of constant in 'k' */ ++ VKFLT, /* floating constant; nval = numerical float value */ ++ VKINT, /* integer constant; ival = numerical integer value */ ++ VKSTR, /* string constant; strval = TString address; ++ (string is fixed by the lexer) */ ++ VNONRELOC, /* expression has its value in a fixed register; ++ info = result register */ ++ VLOCAL, /* local variable; var.ridx = register index; ++ var.vidx = relative index in 'actvar.arr' */ ++ VUPVAL, /* upvalue variable; info = index of upvalue in 'upvalues' */ ++ VCONST, /* compile-time variable; ++ info = absolute index in 'actvar.arr' */ ++ VINDEXED, /* indexed variable; ++ ind.t = table register; ++ ind.idx = key's R index */ ++ VINDEXUP, /* indexed upvalue; ++ ind.t = table upvalue; ++ ind.idx = key's K index */ ++ VINDEXI, /* indexed variable with constant integer; ++ ind.t = table register; ++ ind.idx = key's value */ ++ VINDEXSTR, /* indexed variable with literal string; ++ ind.t = table register; ++ ind.idx = key's K index */ ++ VJMP, /* expression is a test/comparison; ++ info = pc of corresponding jump instruction */ ++ VRELOC, /* expression can put result in any register; ++ info = instruction pc */ ++ VCALL, /* expression is a function call; info = instruction pc */ ++ VVARARG /* vararg expression; info = instruction pc */ ++} expkind; ++ ++ ++#define vkisvar(k) (VLOCAL <= (k) && (k) <= VINDEXSTR) ++#define vkisindexed(k) (VINDEXED <= (k) && (k) <= VINDEXSTR) ++ ++ ++typedef struct expdesc { ++ expkind k; ++ union { ++ lua_Integer ival; /* for VKINT */ ++ lua_Number nval; /* for VKFLT */ ++ TString *strval; /* for VKSTR */ ++ int info; /* for generic use */ ++ struct { /* for indexed variables */ ++ short idx; /* index (R or "long" K) */ ++ lu_byte t; /* table (register or upvalue) */ ++ } ind; ++ struct { /* for local variables */ ++ lu_byte ridx; /* register holding the variable */ ++ unsigned short vidx; /* compiler index (in 'actvar.arr') */ ++ } var; ++ } u; ++ int t; /* patch list of 'exit when true' */ ++ int f; /* patch list of 'exit when false' */ ++} expdesc; ++ ++ ++/* kinds of variables */ ++#define VDKREG 0 /* regular */ ++#define RDKCONST 1 /* constant */ ++#define RDKTOCLOSE 2 /* to-be-closed */ ++#define RDKCTC 3 /* compile-time constant */ ++ ++/* description of an active local variable */ ++typedef union Vardesc { ++ struct { ++ TValuefields; /* constant value (if it is a compile-time constant) */ ++ lu_byte kind; ++ lu_byte ridx; /* register holding the variable */ ++ short pidx; /* index of the variable in the Proto's 'locvars' array */ ++ TString *name; /* variable name */ ++ } vd; ++ TValue k; /* constant value (if any) */ ++} Vardesc; ++ ++ ++ ++/* description of pending goto statements and label statements */ ++typedef struct Labeldesc { ++ TString *name; /* label identifier */ ++ int pc; /* position in code */ ++ int line; /* line where it appeared */ ++ lu_byte nactvar; /* number of active variables in that position */ ++ lu_byte close; /* goto that escapes upvalues */ ++} Labeldesc; ++ ++ ++/* list of labels or gotos */ ++typedef struct Labellist { ++ Labeldesc *arr; /* array */ ++ int n; /* number of entries in use */ ++ int size; /* array size */ ++} Labellist; ++ ++ ++/* dynamic structures used by the parser */ ++typedef struct Dyndata { ++ struct { /* list of all active local variables */ ++ Vardesc *arr; ++ int n; ++ int size; ++ } actvar; ++ Labellist gt; /* list of pending gotos */ ++ Labellist label; /* list of active labels */ ++} Dyndata; ++ ++ ++/* control of blocks */ ++struct BlockCnt; /* defined in lparser.c */ ++ ++ ++/* state needed to generate code for a given function */ ++typedef struct FuncState { ++ Proto *f; /* current function header */ ++ struct FuncState *prev; /* enclosing function */ ++ struct LexState *ls; /* lexical state */ ++ struct BlockCnt *bl; /* chain of current blocks */ ++ int pc; /* next position to code (equivalent to 'ncode') */ ++ int lasttarget; /* 'label' of last 'jump label' */ ++ int previousline; /* last line that was saved in 'lineinfo' */ ++ int nk; /* number of elements in 'k' */ ++ int np; /* number of elements in 'p' */ ++ int nabslineinfo; /* number of elements in 'abslineinfo' */ ++ int firstlocal; /* index of first local var (in Dyndata array) */ ++ int firstlabel; /* index of first label (in 'dyd->label->arr') */ ++ short ndebugvars; /* number of elements in 'f->locvars' */ ++ lu_byte nactvar; /* number of active local variables */ ++ lu_byte nups; /* number of upvalues */ ++ lu_byte freereg; /* first free register */ ++ lu_byte iwthabs; /* instructions issued since last absolute line info */ ++ lu_byte needclose; /* function needs to close upvalues when returning */ ++} FuncState; ++ ++ ++LUAI_FUNC int luaY_nvarstack (FuncState *fs); ++LUAI_FUNC LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, ++ Dyndata *dyd, const char *name, int firstchar); ++ ++ ++#endif +diff --git a/src/bin/lua/lprefix.h b/src/bin/lua/lprefix.h +new file mode 100644 +index 0000000000..484f2ad6fb +--- /dev/null ++++ b/src/bin/lua/lprefix.h +@@ -0,0 +1,45 @@ ++/* ++** $Id: lprefix.h $ ++** Definitions for Lua code that must come before any other header file ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef lprefix_h ++#define lprefix_h ++ ++ ++/* ++** Allows POSIX/XSI stuff ++*/ ++#if !defined(LUA_USE_C89) /* { */ ++ ++#if !defined(_XOPEN_SOURCE) ++#define _XOPEN_SOURCE 600 ++#elif _XOPEN_SOURCE == 0 ++#undef _XOPEN_SOURCE /* use -D_XOPEN_SOURCE=0 to undefine it */ ++#endif ++ ++/* ++** Allows manipulation of large files in gcc and some other compilers ++*/ ++#if !defined(LUA_32BITS) && !defined(_FILE_OFFSET_BITS) ++#define _LARGEFILE_SOURCE 1 ++#define _FILE_OFFSET_BITS 64 ++#endif ++ ++#endif /* } */ ++ ++ ++/* ++** Windows stuff ++*/ ++#if defined(_WIN32) /* { */ ++ ++#if !defined(_CRT_SECURE_NO_WARNINGS) ++#define _CRT_SECURE_NO_WARNINGS /* avoid warnings about ISO C functions */ ++#endif ++ ++#endif /* } */ ++ ++#endif ++ +diff --git a/src/bin/lua/lstate.c b/src/bin/lua/lstate.c +new file mode 100644 +index 0000000000..c5e3b437f1 +--- /dev/null ++++ b/src/bin/lua/lstate.c +@@ -0,0 +1,439 @@ ++/* ++** $Id: lstate.c $ ++** Global State ++** See Copyright Notice in lua.h ++*/ ++ ++#define lstate_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++ ++#include "lua.h" ++ ++#include "lapi.h" ++#include "ldebug.h" ++#include "ldo.h" ++#include "lfunc.h" ++#include "lgc.h" ++#include "llex.h" ++#include "lmem.h" ++#include "lstate.h" ++#include "lstring.h" ++#include "ltable.h" ++#include "ltm.h" ++ ++ ++ ++/* ++** thread state + extra space ++*/ ++typedef struct LX { ++ lu_byte extra_[LUA_EXTRASPACE]; ++ lua_State l; ++} LX; ++ ++ ++/* ++** Main thread combines a thread state and the global state ++*/ ++typedef struct LG { ++ LX l; ++ global_State g; ++} LG; ++ ++ ++ ++#define fromstate(L) (cast(LX *, cast(lu_byte *, (L)) - offsetof(LX, l))) ++ ++ ++/* ++** A macro to create a "random" seed when a state is created; ++** the seed is used to randomize string hashes. ++*/ ++#if !defined(luai_makeseed) ++ ++#include ++ ++/* ++** Compute an initial seed with some level of randomness. ++** Rely on Address Space Layout Randomization (if present) and ++** current time. ++*/ ++#define addbuff(b,p,e) \ ++ { size_t t = cast_sizet(e); \ ++ memcpy(b + p, &t, sizeof(t)); p += sizeof(t); } ++ ++static unsigned int luai_makeseed (lua_State *L) { ++ char buff[3 * sizeof(size_t)]; ++ unsigned int h = cast_uint(time(NULL)); ++ int p = 0; ++ addbuff(buff, p, L); /* heap variable */ ++ addbuff(buff, p, &h); /* local variable */ ++ addbuff(buff, p, &lua_newstate); /* public function */ ++ lua_assert(p == sizeof(buff)); ++ return luaS_hash(buff, p, h); ++} ++ ++#endif ++ ++ ++/* ++** set GCdebt to a new value keeping the value (totalbytes + GCdebt) ++** invariant (and avoiding underflows in 'totalbytes') ++*/ ++void luaE_setdebt (global_State *g, l_mem debt) { ++ l_mem tb = gettotalbytes(g); ++ lua_assert(tb > 0); ++ if (debt < tb - MAX_LMEM) ++ debt = tb - MAX_LMEM; /* will make 'totalbytes == MAX_LMEM' */ ++ g->totalbytes = tb - debt; ++ g->GCdebt = debt; ++} ++ ++ ++LUA_API int lua_setcstacklimit (lua_State *L, unsigned int limit) { ++ UNUSED(L); UNUSED(limit); ++ return LUAI_MAXCCALLS; /* warning?? */ ++} ++ ++ ++CallInfo *luaE_extendCI (lua_State *L) { ++ CallInfo *ci; ++ lua_assert(L->ci->next == NULL); ++ ci = luaM_new(L, CallInfo); ++ lua_assert(L->ci->next == NULL); ++ L->ci->next = ci; ++ ci->previous = L->ci; ++ ci->next = NULL; ++ ci->u.l.trap = 0; ++ L->nci++; ++ return ci; ++} ++ ++ ++/* ++** free all CallInfo structures not in use by a thread ++*/ ++void luaE_freeCI (lua_State *L) { ++ CallInfo *ci = L->ci; ++ CallInfo *next = ci->next; ++ ci->next = NULL; ++ while ((ci = next) != NULL) { ++ next = ci->next; ++ luaM_free(L, ci); ++ L->nci--; ++ } ++} ++ ++ ++/* ++** free half of the CallInfo structures not in use by a thread, ++** keeping the first one. ++*/ ++void luaE_shrinkCI (lua_State *L) { ++ CallInfo *ci = L->ci->next; /* first free CallInfo */ ++ CallInfo *next; ++ if (ci == NULL) ++ return; /* no extra elements */ ++ while ((next = ci->next) != NULL) { /* two extra elements? */ ++ CallInfo *next2 = next->next; /* next's next */ ++ ci->next = next2; /* remove next from the list */ ++ L->nci--; ++ luaM_free(L, next); /* free next */ ++ if (next2 == NULL) ++ break; /* no more elements */ ++ else { ++ next2->previous = ci; ++ ci = next2; /* continue */ ++ } ++ } ++} ++ ++ ++/* ++** Called when 'getCcalls(L)' larger or equal to LUAI_MAXCCALLS. ++** If equal, raises an overflow error. If value is larger than ++** LUAI_MAXCCALLS (which means it is handling an overflow) but ++** not much larger, does not report an error (to allow overflow ++** handling to work). ++*/ ++void luaE_checkcstack (lua_State *L) { ++ if (getCcalls(L) == LUAI_MAXCCALLS) ++ luaG_runerror(L, "C stack overflow"); ++ else if (getCcalls(L) >= (LUAI_MAXCCALLS / 10 * 11)) ++ luaD_throw(L, LUA_ERRERR); /* error while handing stack error */ ++} ++ ++ ++LUAI_FUNC void luaE_incCstack (lua_State *L) { ++ L->nCcalls++; ++ if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS)) ++ luaE_checkcstack(L); ++} ++ ++ ++static void stack_init (lua_State *L1, lua_State *L) { ++ int i; CallInfo *ci; ++ /* initialize stack array */ ++ L1->stack = luaM_newvector(L, BASIC_STACK_SIZE + EXTRA_STACK, StackValue); ++ L1->tbclist = L1->stack; ++ for (i = 0; i < BASIC_STACK_SIZE + EXTRA_STACK; i++) ++ setnilvalue(s2v(L1->stack + i)); /* erase new stack */ ++ L1->top = L1->stack; ++ L1->stack_last = L1->stack + BASIC_STACK_SIZE; ++ /* initialize first ci */ ++ ci = &L1->base_ci; ++ ci->next = ci->previous = NULL; ++ ci->callstatus = CIST_C; ++ ci->func = L1->top; ++ ci->u.c.k = NULL; ++ ci->nresults = 0; ++ setnilvalue(s2v(L1->top)); /* 'function' entry for this 'ci' */ ++ L1->top++; ++ ci->top = L1->top + LUA_MINSTACK; ++ L1->ci = ci; ++} ++ ++ ++static void freestack (lua_State *L) { ++ if (L->stack == NULL) ++ return; /* stack not completely built yet */ ++ L->ci = &L->base_ci; /* free the entire 'ci' list */ ++ luaE_freeCI(L); ++ lua_assert(L->nci == 0); ++ luaM_freearray(L, L->stack, stacksize(L) + EXTRA_STACK); /* free stack */ ++} ++ ++ ++/* ++** Create registry table and its predefined values ++*/ ++static void init_registry (lua_State *L, global_State *g) { ++ /* create registry */ ++ Table *registry = luaH_new(L); ++ sethvalue(L, &g->l_registry, registry); ++ luaH_resize(L, registry, LUA_RIDX_LAST, 0); ++ /* registry[LUA_RIDX_MAINTHREAD] = L */ ++ setthvalue(L, ®istry->array[LUA_RIDX_MAINTHREAD - 1], L); ++ /* registry[LUA_RIDX_GLOBALS] = new table (table of globals) */ ++ sethvalue(L, ®istry->array[LUA_RIDX_GLOBALS - 1], luaH_new(L)); ++} ++ ++ ++/* ++** open parts of the state that may cause memory-allocation errors. ++*/ ++static void f_luaopen (lua_State *L, void *ud) { ++ global_State *g = G(L); ++ UNUSED(ud); ++ stack_init(L, L); /* init stack */ ++ init_registry(L, g); ++ luaS_init(L); ++ luaT_init(L); ++ luaX_init(L); ++ g->gcrunning = 1; /* allow gc */ ++ setnilvalue(&g->nilvalue); /* now state is complete */ ++ luai_userstateopen(L); ++} ++ ++ ++/* ++** preinitialize a thread with consistent values without allocating ++** any memory (to avoid errors) ++*/ ++static void preinit_thread (lua_State *L, global_State *g) { ++ G(L) = g; ++ L->stack = NULL; ++ L->ci = NULL; ++ L->nci = 0; ++ L->twups = L; /* thread has no upvalues */ ++ L->nCcalls = 0; ++ L->errorJmp = NULL; ++ L->hook = NULL; ++ L->hookmask = 0; ++ L->basehookcount = 0; ++ L->allowhook = 1; ++ resethookcount(L); ++ L->openupval = NULL; ++ L->status = LUA_OK; ++ L->errfunc = 0; ++ L->oldpc = 0; ++} ++ ++ ++static void close_state (lua_State *L) { ++ global_State *g = G(L); ++ if (!completestate(g)) /* closing a partially built state? */ ++ luaC_freeallobjects(L); /* jucst collect its objects */ ++ else { /* closing a fully built state */ ++ luaD_closeprotected(L, 1, LUA_OK); /* close all upvalues */ ++ luaC_freeallobjects(L); /* collect all objects */ ++ luai_userstateclose(L); ++ } ++ luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size); ++ freestack(L); ++ lua_assert(gettotalbytes(g) == sizeof(LG)); ++ (*g->frealloc)(g->ud, fromstate(L), sizeof(LG), 0); /* free main block */ ++} ++ ++ ++LUA_API lua_State *lua_newthread (lua_State *L) { ++ global_State *g; ++ lua_State *L1; ++ lua_lock(L); ++ g = G(L); ++ luaC_checkGC(L); ++ /* create new thread */ ++ L1 = &cast(LX *, luaM_newobject(L, LUA_TTHREAD, sizeof(LX)))->l; ++ L1->marked = luaC_white(g); ++ L1->tt = LUA_VTHREAD; ++ /* link it on list 'allgc' */ ++ L1->next = g->allgc; ++ g->allgc = obj2gco(L1); ++ /* anchor it on L stack */ ++ setthvalue2s(L, L->top, L1); ++ api_incr_top(L); ++ preinit_thread(L1, g); ++ L1->hookmask = L->hookmask; ++ L1->basehookcount = L->basehookcount; ++ L1->hook = L->hook; ++ resethookcount(L1); ++ /* initialize L1 extra space */ ++ memcpy(lua_getextraspace(L1), lua_getextraspace(g->mainthread), ++ LUA_EXTRASPACE); ++ luai_userstatethread(L, L1); ++ stack_init(L1, L); /* init stack */ ++ lua_unlock(L); ++ return L1; ++} ++ ++ ++void luaE_freethread (lua_State *L, lua_State *L1) { ++ LX *l = fromstate(L1); ++ luaF_closeupval(L1, L1->stack); /* close all upvalues */ ++ lua_assert(L1->openupval == NULL); ++ luai_userstatefree(L, L1); ++ freestack(L1); ++ luaM_free(L, l); ++} ++ ++ ++int luaE_resetthread (lua_State *L, int status) { ++ CallInfo *ci = L->ci = &L->base_ci; /* unwind CallInfo list */ ++ setnilvalue(s2v(L->stack)); /* 'function' entry for basic 'ci' */ ++ ci->func = L->stack; ++ ci->callstatus = CIST_C; ++ if (status == LUA_YIELD) ++ status = LUA_OK; ++ status = luaD_closeprotected(L, 1, status); ++ if (status != LUA_OK) /* errors? */ ++ luaD_seterrorobj(L, status, L->stack + 1); ++ else ++ L->top = L->stack + 1; ++ ci->top = L->top + LUA_MINSTACK; ++ L->status = cast_byte(status); ++ luaD_reallocstack(L, cast_int(ci->top - L->stack), 0); ++ return status; ++} ++ ++ ++LUA_API int lua_resetthread (lua_State *L) { ++ int status; ++ lua_lock(L); ++ status = luaE_resetthread(L, L->status); ++ lua_unlock(L); ++ return status; ++} ++ ++ ++LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { ++ int i; ++ lua_State *L; ++ global_State *g; ++ LG *l = cast(LG *, (*f)(ud, NULL, LUA_TTHREAD, sizeof(LG))); ++ if (l == NULL) return NULL; ++ L = &l->l.l; ++ g = &l->g; ++ L->tt = LUA_VTHREAD; ++ g->currentwhite = bitmask(WHITE0BIT); ++ L->marked = luaC_white(g); ++ preinit_thread(L, g); ++ g->allgc = obj2gco(L); /* by now, only object is the main thread */ ++ L->next = NULL; ++ incnny(L); /* main thread is always non yieldable */ ++ g->frealloc = f; ++ g->ud = ud; ++ g->warnf = NULL; ++ g->ud_warn = NULL; ++ g->mainthread = L; ++ g->seed = luai_makeseed(L); ++ g->gcrunning = 0; /* no GC while building state */ ++ g->strt.size = g->strt.nuse = 0; ++ g->strt.hash = NULL; ++ setnilvalue(&g->l_registry); ++ g->panic = NULL; ++ g->gcstate = GCSpause; ++ g->gckind = KGC_INC; ++ g->gcstopem = 0; ++ g->gcemergency = 0; ++ g->finobj = g->tobefnz = g->fixedgc = NULL; ++ g->firstold1 = g->survival = g->old1 = g->reallyold = NULL; ++ g->finobjsur = g->finobjold1 = g->finobjrold = NULL; ++ g->sweepgc = NULL; ++ g->gray = g->grayagain = NULL; ++ g->weak = g->ephemeron = g->allweak = NULL; ++ g->twups = NULL; ++ g->totalbytes = sizeof(LG); ++ g->GCdebt = 0; ++ g->lastatomic = 0; ++ setivalue(&g->nilvalue, 0); /* to signal that state is not yet built */ ++ setgcparam(g->gcpause, LUAI_GCPAUSE); ++ setgcparam(g->gcstepmul, LUAI_GCMUL); ++ g->gcstepsize = LUAI_GCSTEPSIZE; ++ setgcparam(g->genmajormul, LUAI_GENMAJORMUL); ++ g->genminormul = LUAI_GENMINORMUL; ++ for (i=0; i < LUA_NUMTAGS; i++) g->mt[i] = NULL; ++ if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) { ++ /* memory allocation error: free partial state */ ++ close_state(L); ++ L = NULL; ++ } ++ return L; ++} ++ ++ ++LUA_API void lua_close (lua_State *L) { ++ lua_lock(L); ++ L = G(L)->mainthread; /* only the main thread can be closed */ ++ close_state(L); ++} ++ ++ ++void luaE_warning (lua_State *L, const char *msg, int tocont) { ++ lua_WarnFunction wf = G(L)->warnf; ++ if (wf != NULL) ++ wf(G(L)->ud_warn, msg, tocont); ++} ++ ++ ++/* ++** Generate a warning from an error message ++*/ ++void luaE_warnerror (lua_State *L, const char *where) { ++ TValue *errobj = s2v(L->top - 1); /* error object */ ++ const char *msg = (ttisstring(errobj)) ++ ? svalue(errobj) ++ : "error object is not a string"; ++ /* produce warning "error in %s (%s)" (where, msg) */ ++ luaE_warning(L, "error in ", 1); ++ luaE_warning(L, where, 1); ++ luaE_warning(L, " (", 1); ++ luaE_warning(L, msg, 1); ++ luaE_warning(L, ")", 0); ++} ++ +diff --git a/src/bin/lua/lstate.h b/src/bin/lua/lstate.h +new file mode 100644 +index 0000000000..c1283bb6b9 +--- /dev/null ++++ b/src/bin/lua/lstate.h +@@ -0,0 +1,404 @@ ++/* ++** $Id: lstate.h $ ++** Global State ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef lstate_h ++#define lstate_h ++ ++#include "lua.h" ++ ++#include "lobject.h" ++#include "ltm.h" ++#include "lzio.h" ++ ++ ++/* ++** Some notes about garbage-collected objects: All objects in Lua must ++** be kept somehow accessible until being freed, so all objects always ++** belong to one (and only one) of these lists, using field 'next' of ++** the 'CommonHeader' for the link: ++** ++** 'allgc': all objects not marked for finalization; ++** 'finobj': all objects marked for finalization; ++** 'tobefnz': all objects ready to be finalized; ++** 'fixedgc': all objects that are not to be collected (currently ++** only small strings, such as reserved words). ++** ++** For the generational collector, some of these lists have marks for ++** generations. Each mark points to the first element in the list for ++** that particular generation; that generation goes until the next mark. ++** ++** 'allgc' -> 'survival': new objects; ++** 'survival' -> 'old': objects that survived one collection; ++** 'old1' -> 'reallyold': objects that became old in last collection; ++** 'reallyold' -> NULL: objects old for more than one cycle. ++** ++** 'finobj' -> 'finobjsur': new objects marked for finalization; ++** 'finobjsur' -> 'finobjold1': survived """"; ++** 'finobjold1' -> 'finobjrold': just old """"; ++** 'finobjrold' -> NULL: really old """". ++** ++** All lists can contain elements older than their main ages, due ++** to 'luaC_checkfinalizer' and 'udata2finalize', which move ++** objects between the normal lists and the "marked for finalization" ++** lists. Moreover, barriers can age young objects in young lists as ++** OLD0, which then become OLD1. However, a list never contains ++** elements younger than their main ages. ++** ++** The generational collector also uses a pointer 'firstold1', which ++** points to the first OLD1 object in the list. It is used to optimize ++** 'markold'. (Potentially OLD1 objects can be anywhere between 'allgc' ++** and 'reallyold', but often the list has no OLD1 objects or they are ++** after 'old1'.) Note the difference between it and 'old1': ++** 'firstold1': no OLD1 objects before this point; there can be all ++** ages after it. ++** 'old1': no objects younger than OLD1 after this point. ++*/ ++ ++/* ++** Moreover, there is another set of lists that control gray objects. ++** These lists are linked by fields 'gclist'. (All objects that ++** can become gray have such a field. The field is not the same ++** in all objects, but it always has this name.) Any gray object ++** must belong to one of these lists, and all objects in these lists ++** must be gray (with two exceptions explained below): ++** ++** 'gray': regular gray objects, still waiting to be visited. ++** 'grayagain': objects that must be revisited at the atomic phase. ++** That includes ++** - black objects got in a write barrier; ++** - all kinds of weak tables during propagation phase; ++** - all threads. ++** 'weak': tables with weak values to be cleared; ++** 'ephemeron': ephemeron tables with white->white entries; ++** 'allweak': tables with weak keys and/or weak values to be cleared. ++** ++** The exceptions to that "gray rule" are: ++** - TOUCHED2 objects in generational mode stay in a gray list (because ++** they must be visited again at the end of the cycle), but they are ++** marked black because assignments to them must activate barriers (to ++** move them back to TOUCHED1). ++** - Open upvales are kept gray to avoid barriers, but they stay out ++** of gray lists. (They don't even have a 'gclist' field.) ++*/ ++ ++ ++ ++/* ++** About 'nCcalls': This count has two parts: the lower 16 bits counts ++** the number of recursive invocations in the C stack; the higher ++** 16 bits counts the number of non-yieldable calls in the stack. ++** (They are together so that we can change and save both with one ++** instruction.) ++*/ ++ ++ ++/* true if this thread does not have non-yieldable calls in the stack */ ++#define yieldable(L) (((L)->nCcalls & 0xffff0000) == 0) ++ ++/* real number of C calls */ ++#define getCcalls(L) ((L)->nCcalls & 0xffff) ++ ++ ++/* Increment the number of non-yieldable calls */ ++#define incnny(L) ((L)->nCcalls += 0x10000) ++ ++/* Decrement the number of non-yieldable calls */ ++#define decnny(L) ((L)->nCcalls -= 0x10000) ++ ++/* Non-yieldable call increment */ ++#define nyci (0x10000 | 1) ++ ++ ++ ++ ++struct lua_longjmp; /* defined in ldo.c */ ++ ++ ++/* ++** Atomic type (relative to signals) to better ensure that 'lua_sethook' ++** is thread safe ++*/ ++#if !defined(l_signalT) ++#include ++#define l_signalT sig_atomic_t ++#endif ++ ++ ++/* ++** Extra stack space to handle TM calls and some other extras. This ++** space is not included in 'stack_last'. It is used only to avoid stack ++** checks, either because the element will be promptly popped or because ++** there will be a stack check soon after the push. Function frames ++** never use this extra space, so it does not need to be kept clean. ++*/ ++#define EXTRA_STACK 5 ++ ++ ++#define BASIC_STACK_SIZE (2*LUA_MINSTACK) ++ ++#define stacksize(th) cast_int((th)->stack_last - (th)->stack) ++ ++ ++/* kinds of Garbage Collection */ ++#define KGC_INC 0 /* incremental gc */ ++#define KGC_GEN 1 /* generational gc */ ++ ++ ++typedef struct stringtable { ++ TString **hash; ++ int nuse; /* number of elements */ ++ int size; ++} stringtable; ++ ++ ++/* ++** Information about a call. ++** About union 'u': ++** - field 'l' is used only for Lua functions; ++** - field 'c' is used only for C functions. ++** About union 'u2': ++** - field 'funcidx' is used only by C functions while doing a ++** protected call; ++** - field 'nyield' is used only while a function is "doing" an ++** yield (from the yield until the next resume); ++** - field 'nres' is used only while closing tbc variables when ++** returning from a C function; ++** - field 'transferinfo' is used only during call/returnhooks, ++** before the function starts or after it ends. ++*/ ++typedef struct CallInfo { ++ StkId func; /* function index in the stack */ ++ StkId top; /* top for this function */ ++ struct CallInfo *previous, *next; /* dynamic call link */ ++ union { ++ struct { /* only for Lua functions */ ++ const Instruction *savedpc; ++ volatile l_signalT trap; ++ int nextraargs; /* # of extra arguments in vararg functions */ ++ } l; ++ struct { /* only for C functions */ ++ lua_KFunction k; /* continuation in case of yields */ ++ ptrdiff_t old_errfunc; ++ lua_KContext ctx; /* context info. in case of yields */ ++ } c; ++ } u; ++ union { ++ int funcidx; /* called-function index */ ++ int nyield; /* number of values yielded */ ++ int nres; /* number of values returned */ ++ struct { /* info about transferred values (for call/return hooks) */ ++ unsigned short ftransfer; /* offset of first value transferred */ ++ unsigned short ntransfer; /* number of values transferred */ ++ } transferinfo; ++ } u2; ++ short nresults; /* expected number of results from this function */ ++ unsigned short callstatus; ++} CallInfo; ++ ++ ++/* ++** Bits in CallInfo status ++*/ ++#define CIST_OAH (1<<0) /* original value of 'allowhook' */ ++#define CIST_C (1<<1) /* call is running a C function */ ++#define CIST_FRESH (1<<2) /* call is on a fresh "luaV_execute" frame */ ++#define CIST_HOOKED (1<<3) /* call is running a debug hook */ ++#define CIST_YPCALL (1<<4) /* doing a yieldable protected call */ ++#define CIST_TAIL (1<<5) /* call was tail called */ ++#define CIST_HOOKYIELD (1<<6) /* last hook called yielded */ ++#define CIST_FIN (1<<7) /* call is running a finalizer */ ++#define CIST_TRAN (1<<8) /* 'ci' has transfer information */ ++#define CIST_CLSRET (1<<9) /* function is closing tbc variables */ ++/* Bits 10-12 are used for CIST_RECST (see below) */ ++#define CIST_RECST 10 ++#if defined(LUA_COMPAT_LT_LE) ++#define CIST_LEQ (1<<13) /* using __lt for __le */ ++#endif ++ ++ ++/* ++** Field CIST_RECST stores the "recover status", used to keep the error ++** status while closing to-be-closed variables in coroutines, so that ++** Lua can correctly resume after an yield from a __close method called ++** because of an error. (Three bits are enough for error status.) ++*/ ++#define getcistrecst(ci) (((ci)->callstatus >> CIST_RECST) & 7) ++#define setcistrecst(ci,st) \ ++ check_exp(((st) & 7) == (st), /* status must fit in three bits */ \ ++ ((ci)->callstatus = ((ci)->callstatus & ~(7 << CIST_RECST)) \ ++ | ((st) << CIST_RECST))) ++ ++ ++/* active function is a Lua function */ ++#define isLua(ci) (!((ci)->callstatus & CIST_C)) ++ ++/* call is running Lua code (not a hook) */ ++#define isLuacode(ci) (!((ci)->callstatus & (CIST_C | CIST_HOOKED))) ++ ++/* assume that CIST_OAH has offset 0 and that 'v' is strictly 0/1 */ ++#define setoah(st,v) ((st) = ((st) & ~CIST_OAH) | (v)) ++#define getoah(st) ((st) & CIST_OAH) ++ ++ ++/* ++** 'global state', shared by all threads of this state ++*/ ++typedef struct global_State { ++ lua_Alloc frealloc; /* function to reallocate memory */ ++ void *ud; /* auxiliary data to 'frealloc' */ ++ l_mem totalbytes; /* number of bytes currently allocated - GCdebt */ ++ l_mem GCdebt; /* bytes allocated not yet compensated by the collector */ ++ lu_mem GCestimate; /* an estimate of the non-garbage memory in use */ ++ lu_mem lastatomic; /* see function 'genstep' in file 'lgc.c' */ ++ stringtable strt; /* hash table for strings */ ++ TValue l_registry; ++ TValue nilvalue; /* a nil value */ ++ unsigned int seed; /* randomized seed for hashes */ ++ lu_byte currentwhite; ++ lu_byte gcstate; /* state of garbage collector */ ++ lu_byte gckind; /* kind of GC running */ ++ lu_byte gcstopem; /* stops emergency collections */ ++ lu_byte genminormul; /* control for minor generational collections */ ++ lu_byte genmajormul; /* control for major generational collections */ ++ lu_byte gcrunning; /* true if GC is running */ ++ lu_byte gcemergency; /* true if this is an emergency collection */ ++ lu_byte gcpause; /* size of pause between successive GCs */ ++ lu_byte gcstepmul; /* GC "speed" */ ++ lu_byte gcstepsize; /* (log2 of) GC granularity */ ++ GCObject *allgc; /* list of all collectable objects */ ++ GCObject **sweepgc; /* current position of sweep in list */ ++ GCObject *finobj; /* list of collectable objects with finalizers */ ++ GCObject *gray; /* list of gray objects */ ++ GCObject *grayagain; /* list of objects to be traversed atomically */ ++ GCObject *weak; /* list of tables with weak values */ ++ GCObject *ephemeron; /* list of ephemeron tables (weak keys) */ ++ GCObject *allweak; /* list of all-weak tables */ ++ GCObject *tobefnz; /* list of userdata to be GC */ ++ GCObject *fixedgc; /* list of objects not to be collected */ ++ /* fields for generational collector */ ++ GCObject *survival; /* start of objects that survived one GC cycle */ ++ GCObject *old1; /* start of old1 objects */ ++ GCObject *reallyold; /* objects more than one cycle old ("really old") */ ++ GCObject *firstold1; /* first OLD1 object in the list (if any) */ ++ GCObject *finobjsur; /* list of survival objects with finalizers */ ++ GCObject *finobjold1; /* list of old1 objects with finalizers */ ++ GCObject *finobjrold; /* list of really old objects with finalizers */ ++ struct lua_State *twups; /* list of threads with open upvalues */ ++ lua_CFunction panic; /* to be called in unprotected errors */ ++ struct lua_State *mainthread; ++ TString *memerrmsg; /* message for memory-allocation errors */ ++ TString *tmname[TM_N]; /* array with tag-method names */ ++ struct Table *mt[LUA_NUMTAGS]; /* metatables for basic types */ ++ TString *strcache[STRCACHE_N][STRCACHE_M]; /* cache for strings in API */ ++ lua_WarnFunction warnf; /* warning function */ ++ void *ud_warn; /* auxiliary data to 'warnf' */ ++} global_State; ++ ++ ++/* ++** 'per thread' state ++*/ ++struct lua_State { ++ CommonHeader; ++ lu_byte status; ++ lu_byte allowhook; ++ unsigned short nci; /* number of items in 'ci' list */ ++ StkId top; /* first free slot in the stack */ ++ global_State *l_G; ++ CallInfo *ci; /* call info for current function */ ++ StkId stack_last; /* end of stack (last element + 1) */ ++ StkId stack; /* stack base */ ++ UpVal *openupval; /* list of open upvalues in this stack */ ++ StkId tbclist; /* list of to-be-closed variables */ ++ GCObject *gclist; ++ struct lua_State *twups; /* list of threads with open upvalues */ ++ struct lua_longjmp *errorJmp; /* current error recover point */ ++ CallInfo base_ci; /* CallInfo for first level (C calling Lua) */ ++ volatile lua_Hook hook; ++ ptrdiff_t errfunc; /* current error handling function (stack index) */ ++ l_uint32 nCcalls; /* number of nested (non-yieldable | C) calls */ ++ int oldpc; /* last pc traced */ ++ int basehookcount; ++ int hookcount; ++ volatile l_signalT hookmask; ++}; ++ ++ ++#define G(L) (L->l_G) ++ ++/* ++** 'g->nilvalue' being a nil value flags that the state was completely ++** build. ++*/ ++#define completestate(g) ttisnil(&g->nilvalue) ++ ++ ++/* ++** Union of all collectable objects (only for conversions) ++** ISO C99, 6.5.2.3 p.5: ++** "if a union contains several structures that share a common initial ++** sequence [...], and if the union object currently contains one ++** of these structures, it is permitted to inspect the common initial ++** part of any of them anywhere that a declaration of the complete type ++** of the union is visible." ++*/ ++union GCUnion { ++ GCObject gc; /* common header */ ++ struct TString ts; ++ struct Udata u; ++ union Closure cl; ++ struct Table h; ++ struct Proto p; ++ struct lua_State th; /* thread */ ++ struct UpVal upv; ++}; ++ ++ ++/* ++** ISO C99, 6.7.2.1 p.14: ++** "A pointer to a union object, suitably converted, points to each of ++** its members [...], and vice versa." ++*/ ++#define cast_u(o) cast(union GCUnion *, (o)) ++ ++/* macros to convert a GCObject into a specific value */ ++#define gco2ts(o) \ ++ check_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts)) ++#define gco2u(o) check_exp((o)->tt == LUA_VUSERDATA, &((cast_u(o))->u)) ++#define gco2lcl(o) check_exp((o)->tt == LUA_VLCL, &((cast_u(o))->cl.l)) ++#define gco2ccl(o) check_exp((o)->tt == LUA_VCCL, &((cast_u(o))->cl.c)) ++#define gco2cl(o) \ ++ check_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl)) ++#define gco2t(o) check_exp((o)->tt == LUA_VTABLE, &((cast_u(o))->h)) ++#define gco2p(o) check_exp((o)->tt == LUA_VPROTO, &((cast_u(o))->p)) ++#define gco2th(o) check_exp((o)->tt == LUA_VTHREAD, &((cast_u(o))->th)) ++#define gco2upv(o) check_exp((o)->tt == LUA_VUPVAL, &((cast_u(o))->upv)) ++ ++ ++/* ++** macro to convert a Lua object into a GCObject ++** (The access to 'tt' tries to ensure that 'v' is actually a Lua object.) ++*/ ++#define obj2gco(v) check_exp((v)->tt >= LUA_TSTRING, &(cast_u(v)->gc)) ++ ++ ++/* actual number of total bytes allocated */ ++#define gettotalbytes(g) cast(lu_mem, (g)->totalbytes + (g)->GCdebt) ++ ++LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt); ++LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1); ++LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L); ++LUAI_FUNC void luaE_freeCI (lua_State *L); ++LUAI_FUNC void luaE_shrinkCI (lua_State *L); ++LUAI_FUNC void luaE_checkcstack (lua_State *L); ++LUAI_FUNC void luaE_incCstack (lua_State *L); ++LUAI_FUNC void luaE_warning (lua_State *L, const char *msg, int tocont); ++LUAI_FUNC void luaE_warnerror (lua_State *L, const char *where); ++LUAI_FUNC int luaE_resetthread (lua_State *L, int status); ++ ++ ++#endif ++ +diff --git a/src/bin/lua/lstring.c b/src/bin/lua/lstring.c +new file mode 100644 +index 0000000000..13dcaf4259 +--- /dev/null ++++ b/src/bin/lua/lstring.c +@@ -0,0 +1,273 @@ ++/* ++** $Id: lstring.c $ ++** String table (keeps all strings handled by Lua) ++** See Copyright Notice in lua.h ++*/ ++ ++#define lstring_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++#include ++ ++#include "lua.h" ++ ++#include "ldebug.h" ++#include "ldo.h" ++#include "lmem.h" ++#include "lobject.h" ++#include "lstate.h" ++#include "lstring.h" ++ ++ ++/* ++** Maximum size for string table. ++*/ ++#define MAXSTRTB cast_int(luaM_limitN(MAX_INT, TString*)) ++ ++ ++/* ++** equality for long strings ++*/ ++int luaS_eqlngstr (TString *a, TString *b) { ++ size_t len = a->u.lnglen; ++ lua_assert(a->tt == LUA_VLNGSTR && b->tt == LUA_VLNGSTR); ++ return (a == b) || /* same instance or... */ ++ ((len == b->u.lnglen) && /* equal length and ... */ ++ (memcmp(getstr(a), getstr(b), len) == 0)); /* equal contents */ ++} ++ ++ ++unsigned int luaS_hash (const char *str, size_t l, unsigned int seed) { ++ unsigned int h = seed ^ cast_uint(l); ++ for (; l > 0; l--) ++ h ^= ((h<<5) + (h>>2) + cast_byte(str[l - 1])); ++ return h; ++} ++ ++ ++unsigned int luaS_hashlongstr (TString *ts) { ++ lua_assert(ts->tt == LUA_VLNGSTR); ++ if (ts->extra == 0) { /* no hash? */ ++ size_t len = ts->u.lnglen; ++ ts->hash = luaS_hash(getstr(ts), len, ts->hash); ++ ts->extra = 1; /* now it has its hash */ ++ } ++ return ts->hash; ++} ++ ++ ++static void tablerehash (TString **vect, int osize, int nsize) { ++ int i; ++ for (i = osize; i < nsize; i++) /* clear new elements */ ++ vect[i] = NULL; ++ for (i = 0; i < osize; i++) { /* rehash old part of the array */ ++ TString *p = vect[i]; ++ vect[i] = NULL; ++ while (p) { /* for each string in the list */ ++ TString *hnext = p->u.hnext; /* save next */ ++ unsigned int h = lmod(p->hash, nsize); /* new position */ ++ p->u.hnext = vect[h]; /* chain it into array */ ++ vect[h] = p; ++ p = hnext; ++ } ++ } ++} ++ ++ ++/* ++** Resize the string table. If allocation fails, keep the current size. ++** (This can degrade performance, but any non-zero size should work ++** correctly.) ++*/ ++void luaS_resize (lua_State *L, int nsize) { ++ stringtable *tb = &G(L)->strt; ++ int osize = tb->size; ++ TString **newvect; ++ if (nsize < osize) /* shrinking table? */ ++ tablerehash(tb->hash, osize, nsize); /* depopulate shrinking part */ ++ newvect = luaM_reallocvector(L, tb->hash, osize, nsize, TString*); ++ if (l_unlikely(newvect == NULL)) { /* reallocation failed? */ ++ if (nsize < osize) /* was it shrinking table? */ ++ tablerehash(tb->hash, nsize, osize); /* restore to original size */ ++ /* leave table as it was */ ++ } ++ else { /* allocation succeeded */ ++ tb->hash = newvect; ++ tb->size = nsize; ++ if (nsize > osize) ++ tablerehash(newvect, osize, nsize); /* rehash for new size */ ++ } ++} ++ ++ ++/* ++** Clear API string cache. (Entries cannot be empty, so fill them with ++** a non-collectable string.) ++*/ ++void luaS_clearcache (global_State *g) { ++ int i, j; ++ for (i = 0; i < STRCACHE_N; i++) ++ for (j = 0; j < STRCACHE_M; j++) { ++ if (iswhite(g->strcache[i][j])) /* will entry be collected? */ ++ g->strcache[i][j] = g->memerrmsg; /* replace it with something fixed */ ++ } ++} ++ ++ ++/* ++** Initialize the string table and the string cache ++*/ ++void luaS_init (lua_State *L) { ++ global_State *g = G(L); ++ int i, j; ++ stringtable *tb = &G(L)->strt; ++ tb->hash = luaM_newvector(L, MINSTRTABSIZE, TString*); ++ tablerehash(tb->hash, 0, MINSTRTABSIZE); /* clear array */ ++ tb->size = MINSTRTABSIZE; ++ /* pre-create memory-error message */ ++ g->memerrmsg = luaS_newliteral(L, MEMERRMSG); ++ luaC_fix(L, obj2gco(g->memerrmsg)); /* it should never be collected */ ++ for (i = 0; i < STRCACHE_N; i++) /* fill cache with valid strings */ ++ for (j = 0; j < STRCACHE_M; j++) ++ g->strcache[i][j] = g->memerrmsg; ++} ++ ++ ++ ++/* ++** creates a new string object ++*/ ++static TString *createstrobj (lua_State *L, size_t l, int tag, unsigned int h) { ++ TString *ts; ++ GCObject *o; ++ size_t totalsize; /* total size of TString object */ ++ totalsize = sizelstring(l); ++ o = luaC_newobj(L, tag, totalsize); ++ ts = gco2ts(o); ++ ts->hash = h; ++ ts->extra = 0; ++ getstr(ts)[l] = '\0'; /* ending 0 */ ++ return ts; ++} ++ ++ ++TString *luaS_createlngstrobj (lua_State *L, size_t l) { ++ TString *ts = createstrobj(L, l, LUA_VLNGSTR, G(L)->seed); ++ ts->u.lnglen = l; ++ return ts; ++} ++ ++ ++void luaS_remove (lua_State *L, TString *ts) { ++ stringtable *tb = &G(L)->strt; ++ TString **p = &tb->hash[lmod(ts->hash, tb->size)]; ++ while (*p != ts) /* find previous element */ ++ p = &(*p)->u.hnext; ++ *p = (*p)->u.hnext; /* remove element from its list */ ++ tb->nuse--; ++} ++ ++ ++static void growstrtab (lua_State *L, stringtable *tb) { ++ if (l_unlikely(tb->nuse == MAX_INT)) { /* too many strings? */ ++ luaC_fullgc(L, 1); /* try to free some... */ ++ if (tb->nuse == MAX_INT) /* still too many? */ ++ luaM_error(L); /* cannot even create a message... */ ++ } ++ if (tb->size <= MAXSTRTB / 2) /* can grow string table? */ ++ luaS_resize(L, tb->size * 2); ++} ++ ++ ++/* ++** Checks whether short string exists and reuses it or creates a new one. ++*/ ++static TString *internshrstr (lua_State *L, const char *str, size_t l) { ++ TString *ts; ++ global_State *g = G(L); ++ stringtable *tb = &g->strt; ++ unsigned int h = luaS_hash(str, l, g->seed); ++ TString **list = &tb->hash[lmod(h, tb->size)]; ++ lua_assert(str != NULL); /* otherwise 'memcmp'/'memcpy' are undefined */ ++ for (ts = *list; ts != NULL; ts = ts->u.hnext) { ++ if (l == ts->shrlen && (memcmp(str, getstr(ts), l * sizeof(char)) == 0)) { ++ /* found! */ ++ if (isdead(g, ts)) /* dead (but not collected yet)? */ ++ changewhite(ts); /* resurrect it */ ++ return ts; ++ } ++ } ++ /* else must create a new string */ ++ if (tb->nuse >= tb->size) { /* need to grow string table? */ ++ growstrtab(L, tb); ++ list = &tb->hash[lmod(h, tb->size)]; /* rehash with new size */ ++ } ++ ts = createstrobj(L, l, LUA_VSHRSTR, h); ++ memcpy(getstr(ts), str, l * sizeof(char)); ++ ts->shrlen = cast_byte(l); ++ ts->u.hnext = *list; ++ *list = ts; ++ tb->nuse++; ++ return ts; ++} ++ ++ ++/* ++** new string (with explicit length) ++*/ ++TString *luaS_newlstr (lua_State *L, const char *str, size_t l) { ++ if (l <= LUAI_MAXSHORTLEN) /* short string? */ ++ return internshrstr(L, str, l); ++ else { ++ TString *ts; ++ if (l_unlikely(l >= (MAX_SIZE - sizeof(TString))/sizeof(char))) ++ luaM_toobig(L); ++ ts = luaS_createlngstrobj(L, l); ++ memcpy(getstr(ts), str, l * sizeof(char)); ++ return ts; ++ } ++} ++ ++ ++/* ++** Create or reuse a zero-terminated string, first checking in the ++** cache (using the string address as a key). The cache can contain ++** only zero-terminated strings, so it is safe to use 'strcmp' to ++** check hits. ++*/ ++TString *luaS_new (lua_State *L, const char *str) { ++ unsigned int i = point2uint(str) % STRCACHE_N; /* hash */ ++ int j; ++ TString **p = G(L)->strcache[i]; ++ for (j = 0; j < STRCACHE_M; j++) { ++ if (strcmp(str, getstr(p[j])) == 0) /* hit? */ ++ return p[j]; /* that is it */ ++ } ++ /* normal route */ ++ for (j = STRCACHE_M - 1; j > 0; j--) ++ p[j] = p[j - 1]; /* move out last element */ ++ /* new element is first in the list */ ++ p[0] = luaS_newlstr(L, str, strlen(str)); ++ return p[0]; ++} ++ ++ ++Udata *luaS_newudata (lua_State *L, size_t s, int nuvalue) { ++ Udata *u; ++ int i; ++ GCObject *o; ++ if (l_unlikely(s > MAX_SIZE - udatamemoffset(nuvalue))) ++ luaM_toobig(L); ++ o = luaC_newobj(L, LUA_VUSERDATA, sizeudata(nuvalue, s)); ++ u = gco2u(o); ++ u->len = s; ++ u->nuvalue = nuvalue; ++ u->metatable = NULL; ++ for (i = 0; i < nuvalue; i++) ++ setnilvalue(&u->uv[i].uv); ++ return u; ++} ++ +diff --git a/src/bin/lua/lstring.h b/src/bin/lua/lstring.h +new file mode 100644 +index 0000000000..450c2390d1 +--- /dev/null ++++ b/src/bin/lua/lstring.h +@@ -0,0 +1,57 @@ ++/* ++** $Id: lstring.h $ ++** String table (keep all strings handled by Lua) ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef lstring_h ++#define lstring_h ++ ++#include "lgc.h" ++#include "lobject.h" ++#include "lstate.h" ++ ++ ++/* ++** Memory-allocation error message must be preallocated (it cannot ++** be created after memory is exhausted) ++*/ ++#define MEMERRMSG "not enough memory" ++ ++ ++/* ++** Size of a TString: Size of the header plus space for the string ++** itself (including final '\0'). ++*/ ++#define sizelstring(l) (offsetof(TString, contents) + ((l) + 1) * sizeof(char)) ++ ++#define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \ ++ (sizeof(s)/sizeof(char))-1)) ++ ++ ++/* ++** test whether a string is a reserved word ++*/ ++#define isreserved(s) ((s)->tt == LUA_VSHRSTR && (s)->extra > 0) ++ ++ ++/* ++** equality for short strings, which are always internalized ++*/ ++#define eqshrstr(a,b) check_exp((a)->tt == LUA_VSHRSTR, (a) == (b)) ++ ++ ++LUAI_FUNC unsigned int luaS_hash (const char *str, size_t l, unsigned int seed); ++LUAI_FUNC unsigned int luaS_hashlongstr (TString *ts); ++LUAI_FUNC int luaS_eqlngstr (TString *a, TString *b); ++LUAI_FUNC void luaS_resize (lua_State *L, int newsize); ++LUAI_FUNC void luaS_clearcache (global_State *g); ++LUAI_FUNC void luaS_init (lua_State *L); ++LUAI_FUNC void luaS_remove (lua_State *L, TString *ts); ++LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, int nuvalue); ++LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l); ++LUAI_FUNC TString *luaS_new (lua_State *L, const char *str); ++LUAI_FUNC TString *luaS_createlngstrobj (lua_State *L, size_t l); ++ ++ ++#endif +diff --git a/src/bin/lua/lstrlib.c b/src/bin/lua/lstrlib.c +new file mode 100644 +index 0000000000..47e5b27a6c +--- /dev/null ++++ b/src/bin/lua/lstrlib.c +@@ -0,0 +1,1817 @@ ++/* ++** $Id: lstrlib.c $ ++** Standard library for string operations and pattern-matching ++** See Copyright Notice in lua.h ++*/ ++ ++#define lstrlib_c ++#define LUA_LIB ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "lua.h" ++ ++#include "lauxlib.h" ++#include "lualib.h" ++ ++ ++/* ++** maximum number of captures that a pattern can do during ++** pattern-matching. This limit is arbitrary, but must fit in ++** an unsigned char. ++*/ ++#if !defined(LUA_MAXCAPTURES) ++#define LUA_MAXCAPTURES 32 ++#endif ++ ++ ++/* macro to 'unsign' a character */ ++#define uchar(c) ((unsigned char)(c)) ++ ++ ++/* ++** Some sizes are better limited to fit in 'int', but must also fit in ++** 'size_t'. (We assume that 'lua_Integer' cannot be smaller than 'int'.) ++*/ ++#define MAX_SIZET ((size_t)(~(size_t)0)) ++ ++#define MAXSIZE \ ++ (sizeof(size_t) < sizeof(int) ? MAX_SIZET : (size_t)(INT_MAX)) ++ ++ ++ ++ ++static int str_len (lua_State *L) { ++ size_t l; ++ luaL_checklstring(L, 1, &l); ++ lua_pushinteger(L, (lua_Integer)l); ++ return 1; ++} ++ ++ ++/* ++** translate a relative initial string position ++** (negative means back from end): clip result to [1, inf). ++** The length of any string in Lua must fit in a lua_Integer, ++** so there are no overflows in the casts. ++** The inverted comparison avoids a possible overflow ++** computing '-pos'. ++*/ ++static size_t posrelatI (lua_Integer pos, size_t len) { ++ if (pos > 0) ++ return (size_t)pos; ++ else if (pos == 0) ++ return 1; ++ else if (pos < -(lua_Integer)len) /* inverted comparison */ ++ return 1; /* clip to 1 */ ++ else return len + (size_t)pos + 1; ++} ++ ++ ++/* ++** Gets an optional ending string position from argument 'arg', ++** with default value 'def'. ++** Negative means back from end: clip result to [0, len] ++*/ ++static size_t getendpos (lua_State *L, int arg, lua_Integer def, ++ size_t len) { ++ lua_Integer pos = luaL_optinteger(L, arg, def); ++ if (pos > (lua_Integer)len) ++ return len; ++ else if (pos >= 0) ++ return (size_t)pos; ++ else if (pos < -(lua_Integer)len) ++ return 0; ++ else return len + (size_t)pos + 1; ++} ++ ++ ++static int str_sub (lua_State *L) { ++ size_t l; ++ const char *s = luaL_checklstring(L, 1, &l); ++ size_t start = posrelatI(luaL_checkinteger(L, 2), l); ++ size_t end = getendpos(L, 3, -1, l); ++ if (start <= end) ++ lua_pushlstring(L, s + start - 1, (end - start) + 1); ++ else lua_pushliteral(L, ""); ++ return 1; ++} ++ ++ ++static int str_reverse (lua_State *L) { ++ size_t l, i; ++ luaL_Buffer b; ++ const char *s = luaL_checklstring(L, 1, &l); ++ char *p = luaL_buffinitsize(L, &b, l); ++ for (i = 0; i < l; i++) ++ p[i] = s[l - i - 1]; ++ luaL_pushresultsize(&b, l); ++ return 1; ++} ++ ++ ++static int str_lower (lua_State *L) { ++ size_t l; ++ size_t i; ++ luaL_Buffer b; ++ const char *s = luaL_checklstring(L, 1, &l); ++ char *p = luaL_buffinitsize(L, &b, l); ++ for (i=0; i MAXSIZE / n)) ++ return luaL_error(L, "resulting string too large"); ++ else { ++ size_t totallen = (size_t)n * l + (size_t)(n - 1) * lsep; ++ luaL_Buffer b; ++ char *p = luaL_buffinitsize(L, &b, totallen); ++ while (n-- > 1) { /* first n-1 copies (followed by separator) */ ++ memcpy(p, s, l * sizeof(char)); p += l; ++ if (lsep > 0) { /* empty 'memcpy' is not that cheap */ ++ memcpy(p, sep, lsep * sizeof(char)); ++ p += lsep; ++ } ++ } ++ memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */ ++ luaL_pushresultsize(&b, totallen); ++ } ++ return 1; ++} ++ ++ ++static int str_byte (lua_State *L) { ++ size_t l; ++ const char *s = luaL_checklstring(L, 1, &l); ++ lua_Integer pi = luaL_optinteger(L, 2, 1); ++ size_t posi = posrelatI(pi, l); ++ size_t pose = getendpos(L, 3, pi, l); ++ int n, i; ++ if (posi > pose) return 0; /* empty interval; return no values */ ++ if (l_unlikely(pose - posi >= (size_t)INT_MAX)) /* arithmetic overflow? */ ++ return luaL_error(L, "string slice too long"); ++ n = (int)(pose - posi) + 1; ++ luaL_checkstack(L, n, "string slice too long"); ++ for (i=0; iinit) { ++ state->init = 1; ++ luaL_buffinit(L, &state->B); ++ } ++ luaL_addlstring(&state->B, (const char *)b, size); ++ return 0; ++} ++ ++ ++static int str_dump (lua_State *L) { ++ struct str_Writer state; ++ int strip = lua_toboolean(L, 2); ++ luaL_checktype(L, 1, LUA_TFUNCTION); ++ lua_settop(L, 1); /* ensure function is on the top of the stack */ ++ state.init = 0; ++ if (l_unlikely(lua_dump(L, writer, &state, strip) != 0)) ++ return luaL_error(L, "unable to dump given function"); ++ luaL_pushresult(&state.B); ++ return 1; ++} ++ ++ ++ ++/* ++** {====================================================== ++** METAMETHODS ++** ======================================================= ++*/ ++ ++#if defined(LUA_NOCVTS2N) /* { */ ++ ++/* no coercion from strings to numbers */ ++ ++static const luaL_Reg stringmetamethods[] = { ++ {"__index", NULL}, /* placeholder */ ++ {NULL, NULL} ++}; ++ ++#else /* }{ */ ++ ++static int tonum (lua_State *L, int arg) { ++ if (lua_type(L, arg) == LUA_TNUMBER) { /* already a number? */ ++ lua_pushvalue(L, arg); ++ return 1; ++ } ++ else { /* check whether it is a numerical string */ ++ size_t len; ++ const char *s = lua_tolstring(L, arg, &len); ++ return (s != NULL && lua_stringtonumber(L, s) == len + 1); ++ } ++} ++ ++ ++static void trymt (lua_State *L, const char *mtname) { ++ lua_settop(L, 2); /* back to the original arguments */ ++ if (l_unlikely(lua_type(L, 2) == LUA_TSTRING || ++ !luaL_getmetafield(L, 2, mtname))) ++ luaL_error(L, "attempt to %s a '%s' with a '%s'", mtname + 2, ++ luaL_typename(L, -2), luaL_typename(L, -1)); ++ lua_insert(L, -3); /* put metamethod before arguments */ ++ lua_call(L, 2, 1); /* call metamethod */ ++} ++ ++ ++static int arith (lua_State *L, int op, const char *mtname) { ++ if (tonum(L, 1) && tonum(L, 2)) ++ lua_arith(L, op); /* result will be on the top */ ++ else ++ trymt(L, mtname); ++ return 1; ++} ++ ++ ++static int arith_add (lua_State *L) { ++ return arith(L, LUA_OPADD, "__add"); ++} ++ ++static int arith_sub (lua_State *L) { ++ return arith(L, LUA_OPSUB, "__sub"); ++} ++ ++static int arith_mul (lua_State *L) { ++ return arith(L, LUA_OPMUL, "__mul"); ++} ++ ++static int arith_mod (lua_State *L) { ++ return arith(L, LUA_OPMOD, "__mod"); ++} ++ ++static int arith_pow (lua_State *L) { ++ return arith(L, LUA_OPPOW, "__pow"); ++} ++ ++static int arith_div (lua_State *L) { ++ return arith(L, LUA_OPDIV, "__div"); ++} ++ ++static int arith_idiv (lua_State *L) { ++ return arith(L, LUA_OPIDIV, "__idiv"); ++} ++ ++static int arith_unm (lua_State *L) { ++ return arith(L, LUA_OPUNM, "__unm"); ++} ++ ++ ++static const luaL_Reg stringmetamethods[] = { ++ {"__add", arith_add}, ++ {"__sub", arith_sub}, ++ {"__mul", arith_mul}, ++ {"__mod", arith_mod}, ++ {"__pow", arith_pow}, ++ {"__div", arith_div}, ++ {"__idiv", arith_idiv}, ++ {"__unm", arith_unm}, ++ {"__index", NULL}, /* placeholder */ ++ {NULL, NULL} ++}; ++ ++#endif /* } */ ++ ++/* }====================================================== */ ++ ++/* ++** {====================================================== ++** PATTERN MATCHING ++** ======================================================= ++*/ ++ ++ ++#define CAP_UNFINISHED (-1) ++#define CAP_POSITION (-2) ++ ++ ++typedef struct MatchState { ++ const char *src_init; /* init of source string */ ++ const char *src_end; /* end ('\0') of source string */ ++ const char *p_end; /* end ('\0') of pattern */ ++ lua_State *L; ++ int matchdepth; /* control for recursive depth (to avoid C stack overflow) */ ++ unsigned char level; /* total number of captures (finished or unfinished) */ ++ struct { ++ const char *init; ++ ptrdiff_t len; ++ } capture[LUA_MAXCAPTURES]; ++} MatchState; ++ ++ ++/* recursive function */ ++static const char *match (MatchState *ms, const char *s, const char *p); ++ ++ ++/* maximum recursion depth for 'match' */ ++#if !defined(MAXCCALLS) ++#define MAXCCALLS 200 ++#endif ++ ++ ++#define L_ESC '%' ++#define SPECIALS "^$*+?.([%-" ++ ++ ++static int check_capture (MatchState *ms, int l) { ++ l -= '1'; ++ if (l_unlikely(l < 0 || l >= ms->level || ++ ms->capture[l].len == CAP_UNFINISHED)) ++ return luaL_error(ms->L, "invalid capture index %%%d", l + 1); ++ return l; ++} ++ ++ ++static int capture_to_close (MatchState *ms) { ++ int level = ms->level; ++ for (level--; level>=0; level--) ++ if (ms->capture[level].len == CAP_UNFINISHED) return level; ++ return luaL_error(ms->L, "invalid pattern capture"); ++} ++ ++ ++static const char *classend (MatchState *ms, const char *p) { ++ switch (*p++) { ++ case L_ESC: { ++ if (l_unlikely(p == ms->p_end)) ++ luaL_error(ms->L, "malformed pattern (ends with '%%')"); ++ return p+1; ++ } ++ case '[': { ++ if (*p == '^') p++; ++ do { /* look for a ']' */ ++ if (l_unlikely(p == ms->p_end)) ++ luaL_error(ms->L, "malformed pattern (missing ']')"); ++ if (*(p++) == L_ESC && p < ms->p_end) ++ p++; /* skip escapes (e.g. '%]') */ ++ } while (*p != ']'); ++ return p+1; ++ } ++ default: { ++ return p; ++ } ++ } ++} ++ ++ ++static int match_class (int c, int cl) { ++ int res; ++ switch (tolower(cl)) { ++ case 'a' : res = isalpha(c); break; ++ case 'c' : res = iscntrl(c); break; ++ case 'd' : res = isdigit(c); break; ++ case 'g' : res = isgraph(c); break; ++ case 'l' : res = islower(c); break; ++ case 'p' : res = ispunct(c); break; ++ case 's' : res = isspace(c); break; ++ case 'u' : res = isupper(c); break; ++ case 'w' : res = isalnum(c); break; ++ case 'x' : res = isxdigit(c); break; ++ case 'z' : res = (c == 0); break; /* deprecated option */ ++ default: return (cl == c); ++ } ++ return (islower(cl) ? res : !res); ++} ++ ++ ++static int matchbracketclass (int c, const char *p, const char *ec) { ++ int sig = 1; ++ if (*(p+1) == '^') { ++ sig = 0; ++ p++; /* skip the '^' */ ++ } ++ while (++p < ec) { ++ if (*p == L_ESC) { ++ p++; ++ if (match_class(c, uchar(*p))) ++ return sig; ++ } ++ else if ((*(p+1) == '-') && (p+2 < ec)) { ++ p+=2; ++ if (uchar(*(p-2)) <= c && c <= uchar(*p)) ++ return sig; ++ } ++ else if (uchar(*p) == c) return sig; ++ } ++ return !sig; ++} ++ ++ ++static int singlematch (MatchState *ms, const char *s, const char *p, ++ const char *ep) { ++ if (s >= ms->src_end) ++ return 0; ++ else { ++ int c = uchar(*s); ++ switch (*p) { ++ case '.': return 1; /* matches any char */ ++ case L_ESC: return match_class(c, uchar(*(p+1))); ++ case '[': return matchbracketclass(c, p, ep-1); ++ default: return (uchar(*p) == c); ++ } ++ } ++} ++ ++ ++static const char *matchbalance (MatchState *ms, const char *s, ++ const char *p) { ++ if (l_unlikely(p >= ms->p_end - 1)) ++ luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')"); ++ if (*s != *p) return NULL; ++ else { ++ int b = *p; ++ int e = *(p+1); ++ int cont = 1; ++ while (++s < ms->src_end) { ++ if (*s == e) { ++ if (--cont == 0) return s+1; ++ } ++ else if (*s == b) cont++; ++ } ++ } ++ return NULL; /* string ends out of balance */ ++} ++ ++ ++static const char *max_expand (MatchState *ms, const char *s, ++ const char *p, const char *ep) { ++ ptrdiff_t i = 0; /* counts maximum expand for item */ ++ while (singlematch(ms, s + i, p, ep)) ++ i++; ++ /* keeps trying to match with the maximum repetitions */ ++ while (i>=0) { ++ const char *res = match(ms, (s+i), ep+1); ++ if (res) return res; ++ i--; /* else didn't match; reduce 1 repetition to try again */ ++ } ++ return NULL; ++} ++ ++ ++static const char *min_expand (MatchState *ms, const char *s, ++ const char *p, const char *ep) { ++ for (;;) { ++ const char *res = match(ms, s, ep+1); ++ if (res != NULL) ++ return res; ++ else if (singlematch(ms, s, p, ep)) ++ s++; /* try with one more repetition */ ++ else return NULL; ++ } ++} ++ ++ ++static const char *start_capture (MatchState *ms, const char *s, ++ const char *p, int what) { ++ const char *res; ++ int level = ms->level; ++ if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures"); ++ ms->capture[level].init = s; ++ ms->capture[level].len = what; ++ ms->level = level+1; ++ if ((res=match(ms, s, p)) == NULL) /* match failed? */ ++ ms->level--; /* undo capture */ ++ return res; ++} ++ ++ ++static const char *end_capture (MatchState *ms, const char *s, ++ const char *p) { ++ int l = capture_to_close(ms); ++ const char *res; ++ ms->capture[l].len = s - ms->capture[l].init; /* close capture */ ++ if ((res = match(ms, s, p)) == NULL) /* match failed? */ ++ ms->capture[l].len = CAP_UNFINISHED; /* undo capture */ ++ return res; ++} ++ ++ ++static const char *match_capture (MatchState *ms, const char *s, int l) { ++ size_t len; ++ l = check_capture(ms, l); ++ len = ms->capture[l].len; ++ if ((size_t)(ms->src_end-s) >= len && ++ memcmp(ms->capture[l].init, s, len) == 0) ++ return s+len; ++ else return NULL; ++} ++ ++ ++static const char *match (MatchState *ms, const char *s, const char *p) { ++ if (l_unlikely(ms->matchdepth-- == 0)) ++ luaL_error(ms->L, "pattern too complex"); ++ init: /* using goto's to optimize tail recursion */ ++ if (p != ms->p_end) { /* end of pattern? */ ++ switch (*p) { ++ case '(': { /* start capture */ ++ if (*(p + 1) == ')') /* position capture? */ ++ s = start_capture(ms, s, p + 2, CAP_POSITION); ++ else ++ s = start_capture(ms, s, p + 1, CAP_UNFINISHED); ++ break; ++ } ++ case ')': { /* end capture */ ++ s = end_capture(ms, s, p + 1); ++ break; ++ } ++ case '$': { ++ if ((p + 1) != ms->p_end) /* is the '$' the last char in pattern? */ ++ goto dflt; /* no; go to default */ ++ s = (s == ms->src_end) ? s : NULL; /* check end of string */ ++ break; ++ } ++ case L_ESC: { /* escaped sequences not in the format class[*+?-]? */ ++ switch (*(p + 1)) { ++ case 'b': { /* balanced string? */ ++ s = matchbalance(ms, s, p + 2); ++ if (s != NULL) { ++ p += 4; goto init; /* return match(ms, s, p + 4); */ ++ } /* else fail (s == NULL) */ ++ break; ++ } ++ case 'f': { /* frontier? */ ++ const char *ep; char previous; ++ p += 2; ++ if (l_unlikely(*p != '[')) ++ luaL_error(ms->L, "missing '[' after '%%f' in pattern"); ++ ep = classend(ms, p); /* points to what is next */ ++ previous = (s == ms->src_init) ? '\0' : *(s - 1); ++ if (!matchbracketclass(uchar(previous), p, ep - 1) && ++ matchbracketclass(uchar(*s), p, ep - 1)) { ++ p = ep; goto init; /* return match(ms, s, ep); */ ++ } ++ s = NULL; /* match failed */ ++ break; ++ } ++ case '0': case '1': case '2': case '3': ++ case '4': case '5': case '6': case '7': ++ case '8': case '9': { /* capture results (%0-%9)? */ ++ s = match_capture(ms, s, uchar(*(p + 1))); ++ if (s != NULL) { ++ p += 2; goto init; /* return match(ms, s, p + 2) */ ++ } ++ break; ++ } ++ default: goto dflt; ++ } ++ break; ++ } ++ default: dflt: { /* pattern class plus optional suffix */ ++ const char *ep = classend(ms, p); /* points to optional suffix */ ++ /* does not match at least once? */ ++ if (!singlematch(ms, s, p, ep)) { ++ if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */ ++ p = ep + 1; goto init; /* return match(ms, s, ep + 1); */ ++ } ++ else /* '+' or no suffix */ ++ s = NULL; /* fail */ ++ } ++ else { /* matched once */ ++ switch (*ep) { /* handle optional suffix */ ++ case '?': { /* optional */ ++ const char *res; ++ if ((res = match(ms, s + 1, ep + 1)) != NULL) ++ s = res; ++ else { ++ p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */ ++ } ++ break; ++ } ++ case '+': /* 1 or more repetitions */ ++ s++; /* 1 match already done */ ++ /* FALLTHROUGH */ ++ case '*': /* 0 or more repetitions */ ++ s = max_expand(ms, s, p, ep); ++ break; ++ case '-': /* 0 or more repetitions (minimum) */ ++ s = min_expand(ms, s, p, ep); ++ break; ++ default: /* no suffix */ ++ s++; p = ep; goto init; /* return match(ms, s + 1, ep); */ ++ } ++ } ++ break; ++ } ++ } ++ } ++ ms->matchdepth++; ++ return s; ++} ++ ++ ++ ++static const char *lmemfind (const char *s1, size_t l1, ++ const char *s2, size_t l2) { ++ if (l2 == 0) return s1; /* empty strings are everywhere */ ++ else if (l2 > l1) return NULL; /* avoids a negative 'l1' */ ++ else { ++ const char *init; /* to search for a '*s2' inside 's1' */ ++ l2--; /* 1st char will be checked by 'memchr' */ ++ l1 = l1-l2; /* 's2' cannot be found after that */ ++ while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) { ++ init++; /* 1st char is already checked */ ++ if (memcmp(init, s2+1, l2) == 0) ++ return init-1; ++ else { /* correct 'l1' and 's1' to try again */ ++ l1 -= init-s1; ++ s1 = init; ++ } ++ } ++ return NULL; /* not found */ ++ } ++} ++ ++ ++/* ++** get information about the i-th capture. If there are no captures ++** and 'i==0', return information about the whole match, which ++** is the range 's'..'e'. If the capture is a string, return ++** its length and put its address in '*cap'. If it is an integer ++** (a position), push it on the stack and return CAP_POSITION. ++*/ ++static size_t get_onecapture (MatchState *ms, int i, const char *s, ++ const char *e, const char **cap) { ++ if (i >= ms->level) { ++ if (l_unlikely(i != 0)) ++ luaL_error(ms->L, "invalid capture index %%%d", i + 1); ++ *cap = s; ++ return e - s; ++ } ++ else { ++ ptrdiff_t capl = ms->capture[i].len; ++ *cap = ms->capture[i].init; ++ if (l_unlikely(capl == CAP_UNFINISHED)) ++ luaL_error(ms->L, "unfinished capture"); ++ else if (capl == CAP_POSITION) ++ lua_pushinteger(ms->L, (ms->capture[i].init - ms->src_init) + 1); ++ return capl; ++ } ++} ++ ++ ++/* ++** Push the i-th capture on the stack. ++*/ ++static void push_onecapture (MatchState *ms, int i, const char *s, ++ const char *e) { ++ const char *cap; ++ ptrdiff_t l = get_onecapture(ms, i, s, e, &cap); ++ if (l != CAP_POSITION) ++ lua_pushlstring(ms->L, cap, l); ++ /* else position was already pushed */ ++} ++ ++ ++static int push_captures (MatchState *ms, const char *s, const char *e) { ++ int i; ++ int nlevels = (ms->level == 0 && s) ? 1 : ms->level; ++ luaL_checkstack(ms->L, nlevels, "too many captures"); ++ for (i = 0; i < nlevels; i++) ++ push_onecapture(ms, i, s, e); ++ return nlevels; /* number of strings pushed */ ++} ++ ++ ++/* check whether pattern has no special characters */ ++static int nospecials (const char *p, size_t l) { ++ size_t upto = 0; ++ do { ++ if (strpbrk(p + upto, SPECIALS)) ++ return 0; /* pattern has a special character */ ++ upto += strlen(p + upto) + 1; /* may have more after \0 */ ++ } while (upto <= l); ++ return 1; /* no special chars found */ ++} ++ ++ ++static void prepstate (MatchState *ms, lua_State *L, ++ const char *s, size_t ls, const char *p, size_t lp) { ++ ms->L = L; ++ ms->matchdepth = MAXCCALLS; ++ ms->src_init = s; ++ ms->src_end = s + ls; ++ ms->p_end = p + lp; ++} ++ ++ ++static void reprepstate (MatchState *ms) { ++ ms->level = 0; ++ lua_assert(ms->matchdepth == MAXCCALLS); ++} ++ ++ ++static int str_find_aux (lua_State *L, int find) { ++ size_t ls, lp; ++ const char *s = luaL_checklstring(L, 1, &ls); ++ const char *p = luaL_checklstring(L, 2, &lp); ++ size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1; ++ if (init > ls) { /* start after string's end? */ ++ luaL_pushfail(L); /* cannot find anything */ ++ return 1; ++ } ++ /* explicit request or no special characters? */ ++ if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) { ++ /* do a plain search */ ++ const char *s2 = lmemfind(s + init, ls - init, p, lp); ++ if (s2) { ++ lua_pushinteger(L, (s2 - s) + 1); ++ lua_pushinteger(L, (s2 - s) + lp); ++ return 2; ++ } ++ } ++ else { ++ MatchState ms; ++ const char *s1 = s + init; ++ int anchor = (*p == '^'); ++ if (anchor) { ++ p++; lp--; /* skip anchor character */ ++ } ++ prepstate(&ms, L, s, ls, p, lp); ++ do { ++ const char *res; ++ reprepstate(&ms); ++ if ((res=match(&ms, s1, p)) != NULL) { ++ if (find) { ++ lua_pushinteger(L, (s1 - s) + 1); /* start */ ++ lua_pushinteger(L, res - s); /* end */ ++ return push_captures(&ms, NULL, 0) + 2; ++ } ++ else ++ return push_captures(&ms, s1, res); ++ } ++ } while (s1++ < ms.src_end && !anchor); ++ } ++ luaL_pushfail(L); /* not found */ ++ return 1; ++} ++ ++ ++static int str_find (lua_State *L) { ++ return str_find_aux(L, 1); ++} ++ ++ ++static int str_match (lua_State *L) { ++ return str_find_aux(L, 0); ++} ++ ++ ++/* state for 'gmatch' */ ++typedef struct GMatchState { ++ const char *src; /* current position */ ++ const char *p; /* pattern */ ++ const char *lastmatch; /* end of last match */ ++ MatchState ms; /* match state */ ++} GMatchState; ++ ++ ++static int gmatch_aux (lua_State *L) { ++ GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3)); ++ const char *src; ++ gm->ms.L = L; ++ for (src = gm->src; src <= gm->ms.src_end; src++) { ++ const char *e; ++ reprepstate(&gm->ms); ++ if ((e = match(&gm->ms, src, gm->p)) != NULL && e != gm->lastmatch) { ++ gm->src = gm->lastmatch = e; ++ return push_captures(&gm->ms, src, e); ++ } ++ } ++ return 0; /* not found */ ++} ++ ++ ++static int gmatch (lua_State *L) { ++ size_t ls, lp; ++ const char *s = luaL_checklstring(L, 1, &ls); ++ const char *p = luaL_checklstring(L, 2, &lp); ++ size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1; ++ GMatchState *gm; ++ lua_settop(L, 2); /* keep strings on closure to avoid being collected */ ++ gm = (GMatchState *)lua_newuserdatauv(L, sizeof(GMatchState), 0); ++ if (init > ls) /* start after string's end? */ ++ init = ls + 1; /* avoid overflows in 's + init' */ ++ prepstate(&gm->ms, L, s, ls, p, lp); ++ gm->src = s + init; gm->p = p; gm->lastmatch = NULL; ++ lua_pushcclosure(L, gmatch_aux, 3); ++ return 1; ++} ++ ++ ++static void add_s (MatchState *ms, luaL_Buffer *b, const char *s, ++ const char *e) { ++ size_t l; ++ lua_State *L = ms->L; ++ const char *news = lua_tolstring(L, 3, &l); ++ const char *p; ++ while ((p = (char *)memchr(news, L_ESC, l)) != NULL) { ++ luaL_addlstring(b, news, p - news); ++ p++; /* skip ESC */ ++ if (*p == L_ESC) /* '%%' */ ++ luaL_addchar(b, *p); ++ else if (*p == '0') /* '%0' */ ++ luaL_addlstring(b, s, e - s); ++ else if (isdigit(uchar(*p))) { /* '%n' */ ++ const char *cap; ++ ptrdiff_t resl = get_onecapture(ms, *p - '1', s, e, &cap); ++ if (resl == CAP_POSITION) ++ luaL_addvalue(b); /* add position to accumulated result */ ++ else ++ luaL_addlstring(b, cap, resl); ++ } ++ else ++ luaL_error(L, "invalid use of '%c' in replacement string", L_ESC); ++ l -= p + 1 - news; ++ news = p + 1; ++ } ++ luaL_addlstring(b, news, l); ++} ++ ++ ++/* ++** Add the replacement value to the string buffer 'b'. ++** Return true if the original string was changed. (Function calls and ++** table indexing resulting in nil or false do not change the subject.) ++*/ ++static int add_value (MatchState *ms, luaL_Buffer *b, const char *s, ++ const char *e, int tr) { ++ lua_State *L = ms->L; ++ switch (tr) { ++ case LUA_TFUNCTION: { /* call the function */ ++ int n; ++ lua_pushvalue(L, 3); /* push the function */ ++ n = push_captures(ms, s, e); /* all captures as arguments */ ++ lua_call(L, n, 1); /* call it */ ++ break; ++ } ++ case LUA_TTABLE: { /* index the table */ ++ push_onecapture(ms, 0, s, e); /* first capture is the index */ ++ lua_gettable(L, 3); ++ break; ++ } ++ default: { /* LUA_TNUMBER or LUA_TSTRING */ ++ add_s(ms, b, s, e); /* add value to the buffer */ ++ return 1; /* something changed */ ++ } ++ } ++ if (!lua_toboolean(L, -1)) { /* nil or false? */ ++ lua_pop(L, 1); /* remove value */ ++ luaL_addlstring(b, s, e - s); /* keep original text */ ++ return 0; /* no changes */ ++ } ++ else if (l_unlikely(!lua_isstring(L, -1))) ++ return luaL_error(L, "invalid replacement value (a %s)", ++ luaL_typename(L, -1)); ++ else { ++ luaL_addvalue(b); /* add result to accumulator */ ++ return 1; /* something changed */ ++ } ++} ++ ++ ++static int str_gsub (lua_State *L) { ++ size_t srcl, lp; ++ const char *src = luaL_checklstring(L, 1, &srcl); /* subject */ ++ const char *p = luaL_checklstring(L, 2, &lp); /* pattern */ ++ const char *lastmatch = NULL; /* end of last match */ ++ int tr = lua_type(L, 3); /* replacement type */ ++ lua_Integer max_s = luaL_optinteger(L, 4, srcl + 1); /* max replacements */ ++ int anchor = (*p == '^'); ++ lua_Integer n = 0; /* replacement count */ ++ int changed = 0; /* change flag */ ++ MatchState ms; ++ luaL_Buffer b; ++ luaL_argexpected(L, tr == LUA_TNUMBER || tr == LUA_TSTRING || ++ tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3, ++ "string/function/table"); ++ luaL_buffinit(L, &b); ++ if (anchor) { ++ p++; lp--; /* skip anchor character */ ++ } ++ prepstate(&ms, L, src, srcl, p, lp); ++ while (n < max_s) { ++ const char *e; ++ reprepstate(&ms); /* (re)prepare state for new match */ ++ if ((e = match(&ms, src, p)) != NULL && e != lastmatch) { /* match? */ ++ n++; ++ changed = add_value(&ms, &b, src, e, tr) | changed; ++ src = lastmatch = e; ++ } ++ else if (src < ms.src_end) /* otherwise, skip one character */ ++ luaL_addchar(&b, *src++); ++ else break; /* end of subject */ ++ if (anchor) break; ++ } ++ if (!changed) /* no changes? */ ++ lua_pushvalue(L, 1); /* return original string */ ++ else { /* something changed */ ++ luaL_addlstring(&b, src, ms.src_end-src); ++ luaL_pushresult(&b); /* create and return new string */ ++ } ++ lua_pushinteger(L, n); /* number of substitutions */ ++ return 2; ++} ++ ++/* }====================================================== */ ++ ++ ++ ++/* ++** {====================================================== ++** STRING FORMAT ++** ======================================================= ++*/ ++ ++#if !defined(lua_number2strx) /* { */ ++ ++/* ++** Hexadecimal floating-point formatter ++*/ ++ ++#define SIZELENMOD (sizeof(LUA_NUMBER_FRMLEN)/sizeof(char)) ++ ++ ++/* ++** Number of bits that goes into the first digit. It can be any value ++** between 1 and 4; the following definition tries to align the number ++** to nibble boundaries by making what is left after that first digit a ++** multiple of 4. ++*/ ++#define L_NBFD ((l_floatatt(MANT_DIG) - 1)%4 + 1) ++ ++ ++/* ++** Add integer part of 'x' to buffer and return new 'x' ++*/ ++static lua_Number adddigit (char *buff, int n, lua_Number x) { ++ lua_Number dd = l_mathop(floor)(x); /* get integer part from 'x' */ ++ int d = (int)dd; ++ buff[n] = (d < 10 ? d + '0' : d - 10 + 'a'); /* add to buffer */ ++ return x - dd; /* return what is left */ ++} ++ ++ ++static int num2straux (char *buff, int sz, lua_Number x) { ++ /* if 'inf' or 'NaN', format it like '%g' */ ++ if (x != x || x == (lua_Number)HUGE_VAL || x == -(lua_Number)HUGE_VAL) ++ return l_sprintf(buff, sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)x); ++ else if (x == 0) { /* can be -0... */ ++ /* create "0" or "-0" followed by exponent */ ++ return l_sprintf(buff, sz, LUA_NUMBER_FMT "x0p+0", (LUAI_UACNUMBER)x); ++ } ++ else { ++ int e; ++ lua_Number m = l_mathop(frexp)(x, &e); /* 'x' fraction and exponent */ ++ int n = 0; /* character count */ ++ if (m < 0) { /* is number negative? */ ++ buff[n++] = '-'; /* add sign */ ++ m = -m; /* make it positive */ ++ } ++ buff[n++] = '0'; buff[n++] = 'x'; /* add "0x" */ ++ m = adddigit(buff, n++, m * (1 << L_NBFD)); /* add first digit */ ++ e -= L_NBFD; /* this digit goes before the radix point */ ++ if (m > 0) { /* more digits? */ ++ buff[n++] = lua_getlocaledecpoint(); /* add radix point */ ++ do { /* add as many digits as needed */ ++ m = adddigit(buff, n++, m * 16); ++ } while (m > 0); ++ } ++ n += l_sprintf(buff + n, sz - n, "p%+d", e); /* add exponent */ ++ lua_assert(n < sz); ++ return n; ++ } ++} ++ ++ ++static int lua_number2strx (lua_State *L, char *buff, int sz, ++ const char *fmt, lua_Number x) { ++ int n = num2straux(buff, sz, x); ++ if (fmt[SIZELENMOD] == 'A') { ++ int i; ++ for (i = 0; i < n; i++) ++ buff[i] = toupper(uchar(buff[i])); ++ } ++ else if (l_unlikely(fmt[SIZELENMOD] != 'a')) ++ return luaL_error(L, "modifiers for format '%%a'/'%%A' not implemented"); ++ return n; ++} ++ ++#endif /* } */ ++ ++ ++/* ++** Maximum size for items formatted with '%f'. This size is produced ++** by format('%.99f', -maxfloat), and is equal to 99 + 3 ('-', '.', ++** and '\0') + number of decimal digits to represent maxfloat (which ++** is maximum exponent + 1). (99+3+1, adding some extra, 110) ++*/ ++#define MAX_ITEMF (110 + l_floatatt(MAX_10_EXP)) ++ ++ ++/* ++** All formats except '%f' do not need that large limit. The other ++** float formats use exponents, so that they fit in the 99 limit for ++** significant digits; 's' for large strings and 'q' add items directly ++** to the buffer; all integer formats also fit in the 99 limit. The ++** worst case are floats: they may need 99 significant digits, plus ++** '0x', '-', '.', 'e+XXXX', and '\0'. Adding some extra, 120. ++*/ ++#define MAX_ITEM 120 ++ ++ ++/* valid flags in a format specification */ ++#if !defined(L_FMTFLAGS) ++#define L_FMTFLAGS "-+ #0" ++#endif ++ ++ ++/* ++** maximum size of each format specification (such as "%-099.99d") ++*/ ++#define MAX_FORMAT 32 ++ ++ ++static void addquoted (luaL_Buffer *b, const char *s, size_t len) { ++ luaL_addchar(b, '"'); ++ while (len--) { ++ if (*s == '"' || *s == '\\' || *s == '\n') { ++ luaL_addchar(b, '\\'); ++ luaL_addchar(b, *s); ++ } ++ else if (iscntrl(uchar(*s))) { ++ char buff[10]; ++ if (!isdigit(uchar(*(s+1)))) ++ l_sprintf(buff, sizeof(buff), "\\%d", (int)uchar(*s)); ++ else ++ l_sprintf(buff, sizeof(buff), "\\%03d", (int)uchar(*s)); ++ luaL_addstring(b, buff); ++ } ++ else ++ luaL_addchar(b, *s); ++ s++; ++ } ++ luaL_addchar(b, '"'); ++} ++ ++ ++/* ++** Serialize a floating-point number in such a way that it can be ++** scanned back by Lua. Use hexadecimal format for "common" numbers ++** (to preserve precision); inf, -inf, and NaN are handled separately. ++** (NaN cannot be expressed as a numeral, so we write '(0/0)' for it.) ++*/ ++static int quotefloat (lua_State *L, char *buff, lua_Number n) { ++ const char *s; /* for the fixed representations */ ++ if (n == (lua_Number)HUGE_VAL) /* inf? */ ++ s = "1e9999"; ++ else if (n == -(lua_Number)HUGE_VAL) /* -inf? */ ++ s = "-1e9999"; ++ else if (n != n) /* NaN? */ ++ s = "(0/0)"; ++ else { /* format number as hexadecimal */ ++ int nb = lua_number2strx(L, buff, MAX_ITEM, ++ "%" LUA_NUMBER_FRMLEN "a", n); ++ /* ensures that 'buff' string uses a dot as the radix character */ ++ if (memchr(buff, '.', nb) == NULL) { /* no dot? */ ++ char point = lua_getlocaledecpoint(); /* try locale point */ ++ char *ppoint = (char *)memchr(buff, point, nb); ++ if (ppoint) *ppoint = '.'; /* change it to a dot */ ++ } ++ return nb; ++ } ++ /* for the fixed representations */ ++ return l_sprintf(buff, MAX_ITEM, "%s", s); ++} ++ ++ ++static void addliteral (lua_State *L, luaL_Buffer *b, int arg) { ++ switch (lua_type(L, arg)) { ++ case LUA_TSTRING: { ++ size_t len; ++ const char *s = lua_tolstring(L, arg, &len); ++ addquoted(b, s, len); ++ break; ++ } ++ case LUA_TNUMBER: { ++ char *buff = luaL_prepbuffsize(b, MAX_ITEM); ++ int nb; ++ if (!lua_isinteger(L, arg)) /* float? */ ++ nb = quotefloat(L, buff, lua_tonumber(L, arg)); ++ else { /* integers */ ++ lua_Integer n = lua_tointeger(L, arg); ++ const char *format = (n == LUA_MININTEGER) /* corner case? */ ++ ? "0x%" LUA_INTEGER_FRMLEN "x" /* use hex */ ++ : LUA_INTEGER_FMT; /* else use default format */ ++ nb = l_sprintf(buff, MAX_ITEM, format, (LUAI_UACINT)n); ++ } ++ luaL_addsize(b, nb); ++ break; ++ } ++ case LUA_TNIL: case LUA_TBOOLEAN: { ++ luaL_tolstring(L, arg, NULL); ++ luaL_addvalue(b); ++ break; ++ } ++ default: { ++ luaL_argerror(L, arg, "value has no literal form"); ++ } ++ } ++} ++ ++ ++static const char *scanformat (lua_State *L, const char *strfrmt, char *form) { ++ const char *p = strfrmt; ++ while (*p != '\0' && strchr(L_FMTFLAGS, *p) != NULL) p++; /* skip flags */ ++ if ((size_t)(p - strfrmt) >= sizeof(L_FMTFLAGS)/sizeof(char)) ++ luaL_error(L, "invalid format (repeated flags)"); ++ if (isdigit(uchar(*p))) p++; /* skip width */ ++ if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ ++ if (*p == '.') { ++ p++; ++ if (isdigit(uchar(*p))) p++; /* skip precision */ ++ if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ ++ } ++ if (isdigit(uchar(*p))) ++ luaL_error(L, "invalid format (width or precision too long)"); ++ *(form++) = '%'; ++ memcpy(form, strfrmt, ((p - strfrmt) + 1) * sizeof(char)); ++ form += (p - strfrmt) + 1; ++ *form = '\0'; ++ return p; ++} ++ ++ ++/* ++** add length modifier into formats ++*/ ++static void addlenmod (char *form, const char *lenmod) { ++ size_t l = strlen(form); ++ size_t lm = strlen(lenmod); ++ char spec = form[l - 1]; ++ strcpy(form + l - 1, lenmod); ++ form[l + lm - 1] = spec; ++ form[l + lm] = '\0'; ++} ++ ++ ++static int str_format (lua_State *L) { ++ int top = lua_gettop(L); ++ int arg = 1; ++ size_t sfl; ++ const char *strfrmt = luaL_checklstring(L, arg, &sfl); ++ const char *strfrmt_end = strfrmt+sfl; ++ luaL_Buffer b; ++ luaL_buffinit(L, &b); ++ while (strfrmt < strfrmt_end) { ++ if (*strfrmt != L_ESC) ++ luaL_addchar(&b, *strfrmt++); ++ else if (*++strfrmt == L_ESC) ++ luaL_addchar(&b, *strfrmt++); /* %% */ ++ else { /* format item */ ++ char form[MAX_FORMAT]; /* to store the format ('%...') */ ++ int maxitem = MAX_ITEM; ++ char *buff = luaL_prepbuffsize(&b, maxitem); /* to put formatted item */ ++ int nb = 0; /* number of bytes in added item */ ++ if (++arg > top) ++ return luaL_argerror(L, arg, "no value"); ++ strfrmt = scanformat(L, strfrmt, form); ++ switch (*strfrmt++) { ++ case 'c': { ++ nb = l_sprintf(buff, maxitem, form, (int)luaL_checkinteger(L, arg)); ++ break; ++ } ++ case 'd': case 'i': ++ case 'o': case 'u': case 'x': case 'X': { ++ lua_Integer n = luaL_checkinteger(L, arg); ++ addlenmod(form, LUA_INTEGER_FRMLEN); ++ nb = l_sprintf(buff, maxitem, form, (LUAI_UACINT)n); ++ break; ++ } ++ case 'a': case 'A': ++ addlenmod(form, LUA_NUMBER_FRMLEN); ++ nb = lua_number2strx(L, buff, maxitem, form, ++ luaL_checknumber(L, arg)); ++ break; ++ case 'f': ++ maxitem = MAX_ITEMF; /* extra space for '%f' */ ++ buff = luaL_prepbuffsize(&b, maxitem); ++ /* FALLTHROUGH */ ++ case 'e': case 'E': case 'g': case 'G': { ++ lua_Number n = luaL_checknumber(L, arg); ++ addlenmod(form, LUA_NUMBER_FRMLEN); ++ nb = l_sprintf(buff, maxitem, form, (LUAI_UACNUMBER)n); ++ break; ++ } ++ case 'p': { ++ const void *p = lua_topointer(L, arg); ++ if (p == NULL) { /* avoid calling 'printf' with argument NULL */ ++ p = "(null)"; /* result */ ++ form[strlen(form) - 1] = 's'; /* format it as a string */ ++ } ++ nb = l_sprintf(buff, maxitem, form, p); ++ break; ++ } ++ case 'q': { ++ if (form[2] != '\0') /* modifiers? */ ++ return luaL_error(L, "specifier '%%q' cannot have modifiers"); ++ addliteral(L, &b, arg); ++ break; ++ } ++ case 's': { ++ size_t l; ++ const char *s = luaL_tolstring(L, arg, &l); ++ if (form[2] == '\0') /* no modifiers? */ ++ luaL_addvalue(&b); /* keep entire string */ ++ else { ++ luaL_argcheck(L, l == strlen(s), arg, "string contains zeros"); ++ if (!strchr(form, '.') && l >= 100) { ++ /* no precision and string is too long to be formatted */ ++ luaL_addvalue(&b); /* keep entire string */ ++ } ++ else { /* format the string into 'buff' */ ++ nb = l_sprintf(buff, maxitem, form, s); ++ lua_pop(L, 1); /* remove result from 'luaL_tolstring' */ ++ } ++ } ++ break; ++ } ++ default: { /* also treat cases 'pnLlh' */ ++ return luaL_error(L, "invalid conversion '%s' to 'format'", form); ++ } ++ } ++ lua_assert(nb < maxitem); ++ luaL_addsize(&b, nb); ++ } ++ } ++ luaL_pushresult(&b); ++ return 1; ++} ++ ++/* }====================================================== */ ++ ++ ++/* ++** {====================================================== ++** PACK/UNPACK ++** ======================================================= ++*/ ++ ++ ++/* value used for padding */ ++#if !defined(LUAL_PACKPADBYTE) ++#define LUAL_PACKPADBYTE 0x00 ++#endif ++ ++/* maximum size for the binary representation of an integer */ ++#define MAXINTSIZE 16 ++ ++/* number of bits in a character */ ++#define NB CHAR_BIT ++ ++/* mask for one character (NB 1's) */ ++#define MC ((1 << NB) - 1) ++ ++/* size of a lua_Integer */ ++#define SZINT ((int)sizeof(lua_Integer)) ++ ++ ++/* dummy union to get native endianness */ ++static const union { ++ int dummy; ++ char little; /* true iff machine is little endian */ ++} nativeendian = {1}; ++ ++ ++/* dummy structure to get native alignment requirements */ ++struct cD { ++ char c; ++ union { double d; void *p; lua_Integer i; lua_Number n; } u; ++}; ++ ++#define MAXALIGN (offsetof(struct cD, u)) ++ ++ ++/* ++** information to pack/unpack stuff ++*/ ++typedef struct Header { ++ lua_State *L; ++ int islittle; ++ int maxalign; ++} Header; ++ ++ ++/* ++** options for pack/unpack ++*/ ++typedef enum KOption { ++ Kint, /* signed integers */ ++ Kuint, /* unsigned integers */ ++ Kfloat, /* single-precision floating-point numbers */ ++ Knumber, /* Lua "native" floating-point numbers */ ++ Kdouble, /* double-precision floating-point numbers */ ++ Kchar, /* fixed-length strings */ ++ Kstring, /* strings with prefixed length */ ++ Kzstr, /* zero-terminated strings */ ++ Kpadding, /* padding */ ++ Kpaddalign, /* padding for alignment */ ++ Knop /* no-op (configuration or spaces) */ ++} KOption; ++ ++ ++/* ++** Read an integer numeral from string 'fmt' or return 'df' if ++** there is no numeral ++*/ ++static int digit (int c) { return '0' <= c && c <= '9'; } ++ ++static int getnum (const char **fmt, int df) { ++ if (!digit(**fmt)) /* no number? */ ++ return df; /* return default value */ ++ else { ++ int a = 0; ++ do { ++ a = a*10 + (*((*fmt)++) - '0'); ++ } while (digit(**fmt) && a <= ((int)MAXSIZE - 9)/10); ++ return a; ++ } ++} ++ ++ ++/* ++** Read an integer numeral and raises an error if it is larger ++** than the maximum size for integers. ++*/ ++static int getnumlimit (Header *h, const char **fmt, int df) { ++ int sz = getnum(fmt, df); ++ if (l_unlikely(sz > MAXINTSIZE || sz <= 0)) ++ return luaL_error(h->L, "integral size (%d) out of limits [1,%d]", ++ sz, MAXINTSIZE); ++ return sz; ++} ++ ++ ++/* ++** Initialize Header ++*/ ++static void initheader (lua_State *L, Header *h) { ++ h->L = L; ++ h->islittle = nativeendian.little; ++ h->maxalign = 1; ++} ++ ++ ++/* ++** Read and classify next option. 'size' is filled with option's size. ++*/ ++static KOption getoption (Header *h, const char **fmt, int *size) { ++ int opt = *((*fmt)++); ++ *size = 0; /* default */ ++ switch (opt) { ++ case 'b': *size = sizeof(char); return Kint; ++ case 'B': *size = sizeof(char); return Kuint; ++ case 'h': *size = sizeof(short); return Kint; ++ case 'H': *size = sizeof(short); return Kuint; ++ case 'l': *size = sizeof(long); return Kint; ++ case 'L': *size = sizeof(long); return Kuint; ++ case 'j': *size = sizeof(lua_Integer); return Kint; ++ case 'J': *size = sizeof(lua_Integer); return Kuint; ++ case 'T': *size = sizeof(size_t); return Kuint; ++ case 'f': *size = sizeof(float); return Kfloat; ++ case 'n': *size = sizeof(lua_Number); return Knumber; ++ case 'd': *size = sizeof(double); return Kdouble; ++ case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint; ++ case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint; ++ case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring; ++ case 'c': ++ *size = getnum(fmt, -1); ++ if (l_unlikely(*size == -1)) ++ luaL_error(h->L, "missing size for format option 'c'"); ++ return Kchar; ++ case 'z': return Kzstr; ++ case 'x': *size = 1; return Kpadding; ++ case 'X': return Kpaddalign; ++ case ' ': break; ++ case '<': h->islittle = 1; break; ++ case '>': h->islittle = 0; break; ++ case '=': h->islittle = nativeendian.little; break; ++ case '!': h->maxalign = getnumlimit(h, fmt, MAXALIGN); break; ++ default: luaL_error(h->L, "invalid format option '%c'", opt); ++ } ++ return Knop; ++} ++ ++ ++/* ++** Read, classify, and fill other details about the next option. ++** 'psize' is filled with option's size, 'notoalign' with its ++** alignment requirements. ++** Local variable 'size' gets the size to be aligned. (Kpadal option ++** always gets its full alignment, other options are limited by ++** the maximum alignment ('maxalign'). Kchar option needs no alignment ++** despite its size. ++*/ ++static KOption getdetails (Header *h, size_t totalsize, ++ const char **fmt, int *psize, int *ntoalign) { ++ KOption opt = getoption(h, fmt, psize); ++ int align = *psize; /* usually, alignment follows size */ ++ if (opt == Kpaddalign) { /* 'X' gets alignment from following option */ ++ if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0) ++ luaL_argerror(h->L, 1, "invalid next option for option 'X'"); ++ } ++ if (align <= 1 || opt == Kchar) /* need no alignment? */ ++ *ntoalign = 0; ++ else { ++ if (align > h->maxalign) /* enforce maximum alignment */ ++ align = h->maxalign; ++ if (l_unlikely((align & (align - 1)) != 0)) /* not a power of 2? */ ++ luaL_argerror(h->L, 1, "format asks for alignment not power of 2"); ++ *ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1); ++ } ++ return opt; ++} ++ ++ ++/* ++** Pack integer 'n' with 'size' bytes and 'islittle' endianness. ++** The final 'if' handles the case when 'size' is larger than ++** the size of a Lua integer, correcting the extra sign-extension ++** bytes if necessary (by default they would be zeros). ++*/ ++static void packint (luaL_Buffer *b, lua_Unsigned n, ++ int islittle, int size, int neg) { ++ char *buff = luaL_prepbuffsize(b, size); ++ int i; ++ buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */ ++ for (i = 1; i < size; i++) { ++ n >>= NB; ++ buff[islittle ? i : size - 1 - i] = (char)(n & MC); ++ } ++ if (neg && size > SZINT) { /* negative number need sign extension? */ ++ for (i = SZINT; i < size; i++) /* correct extra bytes */ ++ buff[islittle ? i : size - 1 - i] = (char)MC; ++ } ++ luaL_addsize(b, size); /* add result to buffer */ ++} ++ ++ ++/* ++** Copy 'size' bytes from 'src' to 'dest', correcting endianness if ++** given 'islittle' is different from native endianness. ++*/ ++static void copywithendian (char *dest, const char *src, ++ int size, int islittle) { ++ if (islittle == nativeendian.little) ++ memcpy(dest, src, size); ++ else { ++ dest += size - 1; ++ while (size-- != 0) ++ *(dest--) = *(src++); ++ } ++} ++ ++ ++static int str_pack (lua_State *L) { ++ luaL_Buffer b; ++ Header h; ++ const char *fmt = luaL_checkstring(L, 1); /* format string */ ++ int arg = 1; /* current argument to pack */ ++ size_t totalsize = 0; /* accumulate total size of result */ ++ initheader(L, &h); ++ lua_pushnil(L); /* mark to separate arguments from string buffer */ ++ luaL_buffinit(L, &b); ++ while (*fmt != '\0') { ++ int size, ntoalign; ++ KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); ++ totalsize += ntoalign + size; ++ while (ntoalign-- > 0) ++ luaL_addchar(&b, LUAL_PACKPADBYTE); /* fill alignment */ ++ arg++; ++ switch (opt) { ++ case Kint: { /* signed integers */ ++ lua_Integer n = luaL_checkinteger(L, arg); ++ if (size < SZINT) { /* need overflow check? */ ++ lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1); ++ luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow"); ++ } ++ packint(&b, (lua_Unsigned)n, h.islittle, size, (n < 0)); ++ break; ++ } ++ case Kuint: { /* unsigned integers */ ++ lua_Integer n = luaL_checkinteger(L, arg); ++ if (size < SZINT) /* need overflow check? */ ++ luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)), ++ arg, "unsigned overflow"); ++ packint(&b, (lua_Unsigned)n, h.islittle, size, 0); ++ break; ++ } ++ case Kfloat: { /* C float */ ++ float f = (float)luaL_checknumber(L, arg); /* get argument */ ++ char *buff = luaL_prepbuffsize(&b, sizeof(f)); ++ /* move 'f' to final result, correcting endianness if needed */ ++ copywithendian(buff, (char *)&f, sizeof(f), h.islittle); ++ luaL_addsize(&b, size); ++ break; ++ } ++ case Knumber: { /* Lua float */ ++ lua_Number f = luaL_checknumber(L, arg); /* get argument */ ++ char *buff = luaL_prepbuffsize(&b, sizeof(f)); ++ /* move 'f' to final result, correcting endianness if needed */ ++ copywithendian(buff, (char *)&f, sizeof(f), h.islittle); ++ luaL_addsize(&b, size); ++ break; ++ } ++ case Kdouble: { /* C double */ ++ double f = (double)luaL_checknumber(L, arg); /* get argument */ ++ char *buff = luaL_prepbuffsize(&b, sizeof(f)); ++ /* move 'f' to final result, correcting endianness if needed */ ++ copywithendian(buff, (char *)&f, sizeof(f), h.islittle); ++ luaL_addsize(&b, size); ++ break; ++ } ++ case Kchar: { /* fixed-size string */ ++ size_t len; ++ const char *s = luaL_checklstring(L, arg, &len); ++ luaL_argcheck(L, len <= (size_t)size, arg, ++ "string longer than given size"); ++ luaL_addlstring(&b, s, len); /* add string */ ++ while (len++ < (size_t)size) /* pad extra space */ ++ luaL_addchar(&b, LUAL_PACKPADBYTE); ++ break; ++ } ++ case Kstring: { /* strings with length count */ ++ size_t len; ++ const char *s = luaL_checklstring(L, arg, &len); ++ luaL_argcheck(L, size >= (int)sizeof(size_t) || ++ len < ((size_t)1 << (size * NB)), ++ arg, "string length does not fit in given size"); ++ packint(&b, (lua_Unsigned)len, h.islittle, size, 0); /* pack length */ ++ luaL_addlstring(&b, s, len); ++ totalsize += len; ++ break; ++ } ++ case Kzstr: { /* zero-terminated string */ ++ size_t len; ++ const char *s = luaL_checklstring(L, arg, &len); ++ luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros"); ++ luaL_addlstring(&b, s, len); ++ luaL_addchar(&b, '\0'); /* add zero at the end */ ++ totalsize += len + 1; ++ break; ++ } ++ case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE); /* FALLTHROUGH */ ++ case Kpaddalign: case Knop: ++ arg--; /* undo increment */ ++ break; ++ } ++ } ++ luaL_pushresult(&b); ++ return 1; ++} ++ ++ ++static int str_packsize (lua_State *L) { ++ Header h; ++ const char *fmt = luaL_checkstring(L, 1); /* format string */ ++ size_t totalsize = 0; /* accumulate total size of result */ ++ initheader(L, &h); ++ while (*fmt != '\0') { ++ int size, ntoalign; ++ KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); ++ luaL_argcheck(L, opt != Kstring && opt != Kzstr, 1, ++ "variable-length format"); ++ size += ntoalign; /* total space used by option */ ++ luaL_argcheck(L, totalsize <= MAXSIZE - size, 1, ++ "format result too large"); ++ totalsize += size; ++ } ++ lua_pushinteger(L, (lua_Integer)totalsize); ++ return 1; ++} ++ ++ ++/* ++** Unpack an integer with 'size' bytes and 'islittle' endianness. ++** If size is smaller than the size of a Lua integer and integer ++** is signed, must do sign extension (propagating the sign to the ++** higher bits); if size is larger than the size of a Lua integer, ++** it must check the unread bytes to see whether they do not cause an ++** overflow. ++*/ ++static lua_Integer unpackint (lua_State *L, const char *str, ++ int islittle, int size, int issigned) { ++ lua_Unsigned res = 0; ++ int i; ++ int limit = (size <= SZINT) ? size : SZINT; ++ for (i = limit - 1; i >= 0; i--) { ++ res <<= NB; ++ res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i]; ++ } ++ if (size < SZINT) { /* real size smaller than lua_Integer? */ ++ if (issigned) { /* needs sign extension? */ ++ lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1); ++ res = ((res ^ mask) - mask); /* do sign extension */ ++ } ++ } ++ else if (size > SZINT) { /* must check unread bytes */ ++ int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC; ++ for (i = limit; i < size; i++) { ++ if (l_unlikely((unsigned char)str[islittle ? i : size - 1 - i] != mask)) ++ luaL_error(L, "%d-byte integer does not fit into Lua Integer", size); ++ } ++ } ++ return (lua_Integer)res; ++} ++ ++ ++static int str_unpack (lua_State *L) { ++ Header h; ++ const char *fmt = luaL_checkstring(L, 1); ++ size_t ld; ++ const char *data = luaL_checklstring(L, 2, &ld); ++ size_t pos = posrelatI(luaL_optinteger(L, 3, 1), ld) - 1; ++ int n = 0; /* number of results */ ++ luaL_argcheck(L, pos <= ld, 3, "initial position out of string"); ++ initheader(L, &h); ++ while (*fmt != '\0') { ++ int size, ntoalign; ++ KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign); ++ luaL_argcheck(L, (size_t)ntoalign + size <= ld - pos, 2, ++ "data string too short"); ++ pos += ntoalign; /* skip alignment */ ++ /* stack space for item + next position */ ++ luaL_checkstack(L, 2, "too many results"); ++ n++; ++ switch (opt) { ++ case Kint: ++ case Kuint: { ++ lua_Integer res = unpackint(L, data + pos, h.islittle, size, ++ (opt == Kint)); ++ lua_pushinteger(L, res); ++ break; ++ } ++ case Kfloat: { ++ float f; ++ copywithendian((char *)&f, data + pos, sizeof(f), h.islittle); ++ lua_pushnumber(L, (lua_Number)f); ++ break; ++ } ++ case Knumber: { ++ lua_Number f; ++ copywithendian((char *)&f, data + pos, sizeof(f), h.islittle); ++ lua_pushnumber(L, f); ++ break; ++ } ++ case Kdouble: { ++ double f; ++ copywithendian((char *)&f, data + pos, sizeof(f), h.islittle); ++ lua_pushnumber(L, (lua_Number)f); ++ break; ++ } ++ case Kchar: { ++ lua_pushlstring(L, data + pos, size); ++ break; ++ } ++ case Kstring: { ++ size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0); ++ luaL_argcheck(L, len <= ld - pos - size, 2, "data string too short"); ++ lua_pushlstring(L, data + pos + size, len); ++ pos += len; /* skip string */ ++ break; ++ } ++ case Kzstr: { ++ size_t len = strlen(data + pos); ++ luaL_argcheck(L, pos + len < ld, 2, ++ "unfinished string for format 'z'"); ++ lua_pushlstring(L, data + pos, len); ++ pos += len + 1; /* skip string plus final '\0' */ ++ break; ++ } ++ case Kpaddalign: case Kpadding: case Knop: ++ n--; /* undo increment */ ++ break; ++ } ++ pos += size; ++ } ++ lua_pushinteger(L, pos + 1); /* next position */ ++ return n + 1; ++} ++ ++/* }====================================================== */ ++ ++ ++static const luaL_Reg strlib[] = { ++ {"byte", str_byte}, ++ {"char", str_char}, ++ {"dump", str_dump}, ++ {"find", str_find}, ++ {"format", str_format}, ++ {"gmatch", gmatch}, ++ {"gsub", str_gsub}, ++ {"len", str_len}, ++ {"lower", str_lower}, ++ {"match", str_match}, ++ {"rep", str_rep}, ++ {"reverse", str_reverse}, ++ {"sub", str_sub}, ++ {"upper", str_upper}, ++ {"pack", str_pack}, ++ {"packsize", str_packsize}, ++ {"unpack", str_unpack}, ++ {NULL, NULL} ++}; ++ ++ ++static void createmetatable (lua_State *L) { ++ /* table to be metatable for strings */ ++ luaL_newlibtable(L, stringmetamethods); ++ luaL_setfuncs(L, stringmetamethods, 0); ++ lua_pushliteral(L, ""); /* dummy string */ ++ lua_pushvalue(L, -2); /* copy table */ ++ lua_setmetatable(L, -2); /* set table as metatable for strings */ ++ lua_pop(L, 1); /* pop dummy string */ ++ lua_pushvalue(L, -2); /* get string library */ ++ lua_setfield(L, -2, "__index"); /* metatable.__index = string */ ++ lua_pop(L, 1); /* pop metatable */ ++} ++ ++ ++/* ++** Open string library ++*/ ++LUAMOD_API int luaopen_string (lua_State *L) { ++ luaL_newlib(L, strlib); ++ createmetatable(L); ++ return 1; ++} ++ +diff --git a/src/bin/lua/ltable.c b/src/bin/lua/ltable.c +new file mode 100644 +index 0000000000..33c1ab302e +--- /dev/null ++++ b/src/bin/lua/ltable.c +@@ -0,0 +1,971 @@ ++/* ++** $Id: ltable.c $ ++** Lua tables (hash) ++** See Copyright Notice in lua.h ++*/ ++ ++#define ltable_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++/* ++** Implementation of tables (aka arrays, objects, or hash tables). ++** Tables keep its elements in two parts: an array part and a hash part. ++** Non-negative integer keys are all candidates to be kept in the array ++** part. The actual size of the array is the largest 'n' such that ++** more than half the slots between 1 and n are in use. ++** Hash uses a mix of chained scatter table with Brent's variation. ++** A main invariant of these tables is that, if an element is not ++** in its main position (i.e. the 'original' position that its hash gives ++** to it), then the colliding element is in its own main position. ++** Hence even when the load factor reaches 100%, performance remains good. ++*/ ++ ++#include ++#include ++ ++#include "lua.h" ++ ++#include "ldebug.h" ++#include "ldo.h" ++#include "lgc.h" ++#include "lmem.h" ++#include "lobject.h" ++#include "lstate.h" ++#include "lstring.h" ++#include "ltable.h" ++#include "lvm.h" ++ ++ ++/* ++** MAXABITS is the largest integer such that MAXASIZE fits in an ++** unsigned int. ++*/ ++#define MAXABITS cast_int(sizeof(int) * CHAR_BIT - 1) ++ ++ ++/* ++** MAXASIZE is the maximum size of the array part. It is the minimum ++** between 2^MAXABITS and the maximum size that, measured in bytes, ++** fits in a 'size_t'. ++*/ ++#define MAXASIZE luaM_limitN(1u << MAXABITS, TValue) ++ ++/* ++** MAXHBITS is the largest integer such that 2^MAXHBITS fits in a ++** signed int. ++*/ ++#define MAXHBITS (MAXABITS - 1) ++ ++ ++/* ++** MAXHSIZE is the maximum size of the hash part. It is the minimum ++** between 2^MAXHBITS and the maximum size such that, measured in bytes, ++** it fits in a 'size_t'. ++*/ ++#define MAXHSIZE luaM_limitN(1u << MAXHBITS, Node) ++ ++ ++/* ++** When the original hash value is good, hashing by a power of 2 ++** avoids the cost of '%'. ++*/ ++#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t)))) ++ ++/* ++** for other types, it is better to avoid modulo by power of 2, as ++** they can have many 2 factors. ++*/ ++#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1)))) ++ ++ ++#define hashstr(t,str) hashpow2(t, (str)->hash) ++#define hashboolean(t,p) hashpow2(t, p) ++ ++#define hashint(t,i) hashpow2(t, i) ++ ++ ++#define hashpointer(t,p) hashmod(t, point2uint(p)) ++ ++ ++#define dummynode (&dummynode_) ++ ++static const Node dummynode_ = { ++ {{NULL}, LUA_VEMPTY, /* value's value and type */ ++ LUA_VNIL, 0, {NULL}} /* key type, next, and key value */ ++}; ++ ++ ++static const TValue absentkey = {ABSTKEYCONSTANT}; ++ ++ ++ ++/* ++** Hash for floating-point numbers. ++** The main computation should be just ++** n = frexp(n, &i); return (n * INT_MAX) + i ++** but there are some numerical subtleties. ++** In a two-complement representation, INT_MAX does not has an exact ++** representation as a float, but INT_MIN does; because the absolute ++** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the ++** absolute value of the product 'frexp * -INT_MIN' is smaller or equal ++** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when ++** adding 'i'; the use of '~u' (instead of '-u') avoids problems with ++** INT_MIN. ++*/ ++#if !defined(l_hashfloat) ++static int l_hashfloat (lua_Number n) { ++ int i; ++ lua_Integer ni; ++ n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN); ++ if (!lua_numbertointeger(n, &ni)) { /* is 'n' inf/-inf/NaN? */ ++ lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL)); ++ return 0; ++ } ++ else { /* normal case */ ++ unsigned int u = cast_uint(i) + cast_uint(ni); ++ return cast_int(u <= cast_uint(INT_MAX) ? u : ~u); ++ } ++} ++#endif ++ ++ ++/* ++** returns the 'main' position of an element in a table (that is, ++** the index of its hash value). The key comes broken (tag in 'ktt' ++** and value in 'vkl') so that we can call it on keys inserted into ++** nodes. ++*/ ++static Node *mainposition (const Table *t, int ktt, const Value *kvl) { ++ switch (withvariant(ktt)) { ++ case LUA_VNUMINT: { ++ lua_Integer key = ivalueraw(*kvl); ++ return hashint(t, key); ++ } ++ case LUA_VNUMFLT: { ++ lua_Number n = fltvalueraw(*kvl); ++ return hashmod(t, l_hashfloat(n)); ++ } ++ case LUA_VSHRSTR: { ++ TString *ts = tsvalueraw(*kvl); ++ return hashstr(t, ts); ++ } ++ case LUA_VLNGSTR: { ++ TString *ts = tsvalueraw(*kvl); ++ return hashpow2(t, luaS_hashlongstr(ts)); ++ } ++ case LUA_VFALSE: ++ return hashboolean(t, 0); ++ case LUA_VTRUE: ++ return hashboolean(t, 1); ++ case LUA_VLIGHTUSERDATA: { ++ void *p = pvalueraw(*kvl); ++ return hashpointer(t, p); ++ } ++ case LUA_VLCF: { ++ lua_CFunction f = fvalueraw(*kvl); ++ return hashpointer(t, f); ++ } ++ default: { ++ GCObject *o = gcvalueraw(*kvl); ++ return hashpointer(t, o); ++ } ++ } ++} ++ ++ ++/* ++** Returns the main position of an element given as a 'TValue' ++*/ ++static Node *mainpositionTV (const Table *t, const TValue *key) { ++ return mainposition(t, rawtt(key), valraw(key)); ++} ++ ++ ++/* ++** Check whether key 'k1' is equal to the key in node 'n2'. This ++** equality is raw, so there are no metamethods. Floats with integer ++** values have been normalized, so integers cannot be equal to ++** floats. It is assumed that 'eqshrstr' is simply pointer equality, so ++** that short strings are handled in the default case. ++** A true 'deadok' means to accept dead keys as equal to their original ++** values. All dead keys are compared in the default case, by pointer ++** identity. (Only collectable objects can produce dead keys.) Note that ++** dead long strings are also compared by identity. ++** Once a key is dead, its corresponding value may be collected, and ++** then another value can be created with the same address. If this ++** other value is given to 'next', 'equalkey' will signal a false ++** positive. In a regular traversal, this situation should never happen, ++** as all keys given to 'next' came from the table itself, and therefore ++** could not have been collected. Outside a regular traversal, we ++** have garbage in, garbage out. What is relevant is that this false ++** positive does not break anything. (In particular, 'next' will return ++** some other valid item on the table or nil.) ++*/ ++static int equalkey (const TValue *k1, const Node *n2, int deadok) { ++ if ((rawtt(k1) != keytt(n2)) && /* not the same variants? */ ++ !(deadok && keyisdead(n2) && iscollectable(k1))) ++ return 0; /* cannot be same key */ ++ switch (keytt(n2)) { ++ case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE: ++ return 1; ++ case LUA_VNUMINT: ++ return (ivalue(k1) == keyival(n2)); ++ case LUA_VNUMFLT: ++ return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2))); ++ case LUA_VLIGHTUSERDATA: ++ return pvalue(k1) == pvalueraw(keyval(n2)); ++ case LUA_VLCF: ++ return fvalue(k1) == fvalueraw(keyval(n2)); ++ case ctb(LUA_VLNGSTR): ++ return luaS_eqlngstr(tsvalue(k1), keystrval(n2)); ++ default: ++ return gcvalue(k1) == gcvalueraw(keyval(n2)); ++ } ++} ++ ++ ++/* ++** True if value of 'alimit' is equal to the real size of the array ++** part of table 't'. (Otherwise, the array part must be larger than ++** 'alimit'.) ++*/ ++#define limitequalsasize(t) (isrealasize(t) || ispow2((t)->alimit)) ++ ++ ++/* ++** Returns the real size of the 'array' array ++*/ ++LUAI_FUNC unsigned int luaH_realasize (const Table *t) { ++ if (limitequalsasize(t)) ++ return t->alimit; /* this is the size */ ++ else { ++ unsigned int size = t->alimit; ++ /* compute the smallest power of 2 not smaller than 'n' */ ++ size |= (size >> 1); ++ size |= (size >> 2); ++ size |= (size >> 4); ++ size |= (size >> 8); ++ size |= (size >> 16); ++#if (UINT_MAX >> 30) > 3 ++ size |= (size >> 32); /* unsigned int has more than 32 bits */ ++#endif ++ size++; ++ lua_assert(ispow2(size) && size/2 < t->alimit && t->alimit < size); ++ return size; ++ } ++} ++ ++ ++/* ++** Check whether real size of the array is a power of 2. ++** (If it is not, 'alimit' cannot be changed to any other value ++** without changing the real size.) ++*/ ++static int ispow2realasize (const Table *t) { ++ return (!isrealasize(t) || ispow2(t->alimit)); ++} ++ ++ ++static unsigned int setlimittosize (Table *t) { ++ t->alimit = luaH_realasize(t); ++ setrealasize(t); ++ return t->alimit; ++} ++ ++ ++#define limitasasize(t) check_exp(isrealasize(t), t->alimit) ++ ++ ++ ++/* ++** "Generic" get version. (Not that generic: not valid for integers, ++** which may be in array part, nor for floats with integral values.) ++** See explanation about 'deadok' in function 'equalkey'. ++*/ ++static const TValue *getgeneric (Table *t, const TValue *key, int deadok) { ++ Node *n = mainpositionTV(t, key); ++ for (;;) { /* check whether 'key' is somewhere in the chain */ ++ if (equalkey(key, n, deadok)) ++ return gval(n); /* that's it */ ++ else { ++ int nx = gnext(n); ++ if (nx == 0) ++ return &absentkey; /* not found */ ++ n += nx; ++ } ++ } ++} ++ ++ ++/* ++** returns the index for 'k' if 'k' is an appropriate key to live in ++** the array part of a table, 0 otherwise. ++*/ ++static unsigned int arrayindex (lua_Integer k) { ++ if (l_castS2U(k) - 1u < MAXASIZE) /* 'k' in [1, MAXASIZE]? */ ++ return cast_uint(k); /* 'key' is an appropriate array index */ ++ else ++ return 0; ++} ++ ++ ++/* ++** returns the index of a 'key' for table traversals. First goes all ++** elements in the array part, then elements in the hash part. The ++** beginning of a traversal is signaled by 0. ++*/ ++static unsigned int findindex (lua_State *L, Table *t, TValue *key, ++ unsigned int asize) { ++ unsigned int i; ++ if (ttisnil(key)) return 0; /* first iteration */ ++ i = ttisinteger(key) ? arrayindex(ivalue(key)) : 0; ++ if (i - 1u < asize) /* is 'key' inside array part? */ ++ return i; /* yes; that's the index */ ++ else { ++ const TValue *n = getgeneric(t, key, 1); ++ if (l_unlikely(isabstkey(n))) ++ luaG_runerror(L, "invalid key to 'next'"); /* key not found */ ++ i = cast_int(nodefromval(n) - gnode(t, 0)); /* key index in hash table */ ++ /* hash elements are numbered after array ones */ ++ return (i + 1) + asize; ++ } ++} ++ ++ ++int luaH_next (lua_State *L, Table *t, StkId key) { ++ unsigned int asize = luaH_realasize(t); ++ unsigned int i = findindex(L, t, s2v(key), asize); /* find original key */ ++ for (; i < asize; i++) { /* try first array part */ ++ if (!isempty(&t->array[i])) { /* a non-empty entry? */ ++ setivalue(s2v(key), i + 1); ++ setobj2s(L, key + 1, &t->array[i]); ++ return 1; ++ } ++ } ++ for (i -= asize; cast_int(i) < sizenode(t); i++) { /* hash part */ ++ if (!isempty(gval(gnode(t, i)))) { /* a non-empty entry? */ ++ Node *n = gnode(t, i); ++ getnodekey(L, s2v(key), n); ++ setobj2s(L, key + 1, gval(n)); ++ return 1; ++ } ++ } ++ return 0; /* no more elements */ ++} ++ ++ ++static void freehash (lua_State *L, Table *t) { ++ if (!isdummy(t)) ++ luaM_freearray(L, t->node, cast_sizet(sizenode(t))); ++} ++ ++ ++/* ++** {============================================================= ++** Rehash ++** ============================================================== ++*/ ++ ++/* ++** Compute the optimal size for the array part of table 't'. 'nums' is a ++** "count array" where 'nums[i]' is the number of integers in the table ++** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of ++** integer keys in the table and leaves with the number of keys that ++** will go to the array part; return the optimal size. (The condition ++** 'twotoi > 0' in the for loop stops the loop if 'twotoi' overflows.) ++*/ ++static unsigned int computesizes (unsigned int nums[], unsigned int *pna) { ++ int i; ++ unsigned int twotoi; /* 2^i (candidate for optimal size) */ ++ unsigned int a = 0; /* number of elements smaller than 2^i */ ++ unsigned int na = 0; /* number of elements to go to array part */ ++ unsigned int optimal = 0; /* optimal size for array part */ ++ /* loop while keys can fill more than half of total size */ ++ for (i = 0, twotoi = 1; ++ twotoi > 0 && *pna > twotoi / 2; ++ i++, twotoi *= 2) { ++ a += nums[i]; ++ if (a > twotoi/2) { /* more than half elements present? */ ++ optimal = twotoi; /* optimal size (till now) */ ++ na = a; /* all elements up to 'optimal' will go to array part */ ++ } ++ } ++ lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal); ++ *pna = na; ++ return optimal; ++} ++ ++ ++static int countint (lua_Integer key, unsigned int *nums) { ++ unsigned int k = arrayindex(key); ++ if (k != 0) { /* is 'key' an appropriate array index? */ ++ nums[luaO_ceillog2(k)]++; /* count as such */ ++ return 1; ++ } ++ else ++ return 0; ++} ++ ++ ++/* ++** Count keys in array part of table 't': Fill 'nums[i]' with ++** number of keys that will go into corresponding slice and return ++** total number of non-nil keys. ++*/ ++static unsigned int numusearray (const Table *t, unsigned int *nums) { ++ int lg; ++ unsigned int ttlg; /* 2^lg */ ++ unsigned int ause = 0; /* summation of 'nums' */ ++ unsigned int i = 1; /* count to traverse all array keys */ ++ unsigned int asize = limitasasize(t); /* real array size */ ++ /* traverse each slice */ ++ for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) { ++ unsigned int lc = 0; /* counter */ ++ unsigned int lim = ttlg; ++ if (lim > asize) { ++ lim = asize; /* adjust upper limit */ ++ if (i > lim) ++ break; /* no more elements to count */ ++ } ++ /* count elements in range (2^(lg - 1), 2^lg] */ ++ for (; i <= lim; i++) { ++ if (!isempty(&t->array[i-1])) ++ lc++; ++ } ++ nums[lg] += lc; ++ ause += lc; ++ } ++ return ause; ++} ++ ++ ++static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) { ++ int totaluse = 0; /* total number of elements */ ++ int ause = 0; /* elements added to 'nums' (can go to array part) */ ++ int i = sizenode(t); ++ while (i--) { ++ Node *n = &t->node[i]; ++ if (!isempty(gval(n))) { ++ if (keyisinteger(n)) ++ ause += countint(keyival(n), nums); ++ totaluse++; ++ } ++ } ++ *pna += ause; ++ return totaluse; ++} ++ ++ ++/* ++** Creates an array for the hash part of a table with the given ++** size, or reuses the dummy node if size is zero. ++** The computation for size overflow is in two steps: the first ++** comparison ensures that the shift in the second one does not ++** overflow. ++*/ ++static void setnodevector (lua_State *L, Table *t, unsigned int size) { ++ if (size == 0) { /* no elements to hash part? */ ++ t->node = cast(Node *, dummynode); /* use common 'dummynode' */ ++ t->lsizenode = 0; ++ t->lastfree = NULL; /* signal that it is using dummy node */ ++ } ++ else { ++ int i; ++ int lsize = luaO_ceillog2(size); ++ if (lsize > MAXHBITS || (1u << lsize) > MAXHSIZE) ++ luaG_runerror(L, "table overflow"); ++ size = twoto(lsize); ++ t->node = luaM_newvector(L, size, Node); ++ for (i = 0; i < (int)size; i++) { ++ Node *n = gnode(t, i); ++ gnext(n) = 0; ++ setnilkey(n); ++ setempty(gval(n)); ++ } ++ t->lsizenode = cast_byte(lsize); ++ t->lastfree = gnode(t, size); /* all positions are free */ ++ } ++} ++ ++ ++/* ++** (Re)insert all elements from the hash part of 'ot' into table 't'. ++*/ ++static void reinsert (lua_State *L, Table *ot, Table *t) { ++ int j; ++ int size = sizenode(ot); ++ for (j = 0; j < size; j++) { ++ Node *old = gnode(ot, j); ++ if (!isempty(gval(old))) { ++ /* doesn't need barrier/invalidate cache, as entry was ++ already present in the table */ ++ TValue k; ++ getnodekey(L, &k, old); ++ luaH_set(L, t, &k, gval(old)); ++ } ++ } ++} ++ ++ ++/* ++** Exchange the hash part of 't1' and 't2'. ++*/ ++static void exchangehashpart (Table *t1, Table *t2) { ++ lu_byte lsizenode = t1->lsizenode; ++ Node *node = t1->node; ++ Node *lastfree = t1->lastfree; ++ t1->lsizenode = t2->lsizenode; ++ t1->node = t2->node; ++ t1->lastfree = t2->lastfree; ++ t2->lsizenode = lsizenode; ++ t2->node = node; ++ t2->lastfree = lastfree; ++} ++ ++ ++/* ++** Resize table 't' for the new given sizes. Both allocations (for ++** the hash part and for the array part) can fail, which creates some ++** subtleties. If the first allocation, for the hash part, fails, an ++** error is raised and that is it. Otherwise, it copies the elements from ++** the shrinking part of the array (if it is shrinking) into the new ++** hash. Then it reallocates the array part. If that fails, the table ++** is in its original state; the function frees the new hash part and then ++** raises the allocation error. Otherwise, it sets the new hash part ++** into the table, initializes the new part of the array (if any) with ++** nils and reinserts the elements of the old hash back into the new ++** parts of the table. ++*/ ++void luaH_resize (lua_State *L, Table *t, unsigned int newasize, ++ unsigned int nhsize) { ++ unsigned int i; ++ Table newt; /* to keep the new hash part */ ++ unsigned int oldasize = setlimittosize(t); ++ TValue *newarray; ++ /* create new hash part with appropriate size into 'newt' */ ++ setnodevector(L, &newt, nhsize); ++ if (newasize < oldasize) { /* will array shrink? */ ++ t->alimit = newasize; /* pretend array has new size... */ ++ exchangehashpart(t, &newt); /* and new hash */ ++ /* re-insert into the new hash the elements from vanishing slice */ ++ for (i = newasize; i < oldasize; i++) { ++ if (!isempty(&t->array[i])) ++ luaH_setint(L, t, i + 1, &t->array[i]); ++ } ++ t->alimit = oldasize; /* restore current size... */ ++ exchangehashpart(t, &newt); /* and hash (in case of errors) */ ++ } ++ /* allocate new array */ ++ newarray = luaM_reallocvector(L, t->array, oldasize, newasize, TValue); ++ if (l_unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */ ++ freehash(L, &newt); /* release new hash part */ ++ luaM_error(L); /* raise error (with array unchanged) */ ++ } ++ /* allocation ok; initialize new part of the array */ ++ exchangehashpart(t, &newt); /* 't' has the new hash ('newt' has the old) */ ++ t->array = newarray; /* set new array part */ ++ t->alimit = newasize; ++ for (i = oldasize; i < newasize; i++) /* clear new slice of the array */ ++ setempty(&t->array[i]); ++ /* re-insert elements from old hash part into new parts */ ++ reinsert(L, &newt, t); /* 'newt' now has the old hash */ ++ freehash(L, &newt); /* free old hash part */ ++} ++ ++ ++void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) { ++ int nsize = allocsizenode(t); ++ luaH_resize(L, t, nasize, nsize); ++} ++ ++/* ++** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i ++*/ ++static void rehash (lua_State *L, Table *t, const TValue *ek) { ++ unsigned int asize; /* optimal size for array part */ ++ unsigned int na; /* number of keys in the array part */ ++ unsigned int nums[MAXABITS + 1]; ++ int i; ++ int totaluse; ++ for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */ ++ setlimittosize(t); ++ na = numusearray(t, nums); /* count keys in array part */ ++ totaluse = na; /* all those keys are integer keys */ ++ totaluse += numusehash(t, nums, &na); /* count keys in hash part */ ++ /* count extra key */ ++ if (ttisinteger(ek)) ++ na += countint(ivalue(ek), nums); ++ totaluse++; ++ /* compute new size for array part */ ++ asize = computesizes(nums, &na); ++ /* resize the table to new computed sizes */ ++ luaH_resize(L, t, asize, totaluse - na); ++} ++ ++ ++ ++/* ++** }============================================================= ++*/ ++ ++ ++Table *luaH_new (lua_State *L) { ++ GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table)); ++ Table *t = gco2t(o); ++ t->metatable = NULL; ++ t->flags = cast_byte(maskflags); /* table has no metamethod fields */ ++ t->array = NULL; ++ t->alimit = 0; ++ setnodevector(L, t, 0); ++ return t; ++} ++ ++ ++void luaH_free (lua_State *L, Table *t) { ++ freehash(L, t); ++ luaM_freearray(L, t->array, luaH_realasize(t)); ++ luaM_free(L, t); ++} ++ ++ ++static Node *getfreepos (Table *t) { ++ if (!isdummy(t)) { ++ while (t->lastfree > t->node) { ++ t->lastfree--; ++ if (keyisnil(t->lastfree)) ++ return t->lastfree; ++ } ++ } ++ return NULL; /* could not find a free place */ ++} ++ ++ ++ ++/* ++** inserts a new key into a hash table; first, check whether key's main ++** position is free. If not, check whether colliding node is in its main ++** position or not: if it is not, move colliding node to an empty place and ++** put new key in its main position; otherwise (colliding node is in its main ++** position), new key goes to an empty position. ++*/ ++void luaH_newkey (lua_State *L, Table *t, const TValue *key, TValue *value) { ++ Node *mp; ++ TValue aux; ++ if (l_unlikely(ttisnil(key))) ++ luaG_runerror(L, "table index is nil"); ++ else if (ttisfloat(key)) { ++ lua_Number f = fltvalue(key); ++ lua_Integer k; ++ if (luaV_flttointeger(f, &k, F2Ieq)) { /* does key fit in an integer? */ ++ setivalue(&aux, k); ++ key = &aux; /* insert it as an integer */ ++ } ++ else if (l_unlikely(luai_numisnan(f))) ++ luaG_runerror(L, "table index is NaN"); ++ } ++ if (ttisnil(value)) ++ return; /* do not insert nil values */ ++ mp = mainpositionTV(t, key); ++ if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */ ++ Node *othern; ++ Node *f = getfreepos(t); /* get a free place */ ++ if (f == NULL) { /* cannot find a free place? */ ++ rehash(L, t, key); /* grow table */ ++ /* whatever called 'newkey' takes care of TM cache */ ++ luaH_set(L, t, key, value); /* insert key into grown table */ ++ return; ++ } ++ lua_assert(!isdummy(t)); ++ othern = mainposition(t, keytt(mp), &keyval(mp)); ++ if (othern != mp) { /* is colliding node out of its main position? */ ++ /* yes; move colliding node into free position */ ++ while (othern + gnext(othern) != mp) /* find previous */ ++ othern += gnext(othern); ++ gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */ ++ *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */ ++ if (gnext(mp) != 0) { ++ gnext(f) += cast_int(mp - f); /* correct 'next' */ ++ gnext(mp) = 0; /* now 'mp' is free */ ++ } ++ setempty(gval(mp)); ++ } ++ else { /* colliding node is in its own main position */ ++ /* new node will go into free position */ ++ if (gnext(mp) != 0) ++ gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */ ++ else lua_assert(gnext(f) == 0); ++ gnext(mp) = cast_int(f - mp); ++ mp = f; ++ } ++ } ++ setnodekey(L, mp, key); ++ luaC_barrierback(L, obj2gco(t), key); ++ lua_assert(isempty(gval(mp))); ++ setobj2t(L, gval(mp), value); ++} ++ ++ ++/* ++** Search function for integers. If integer is inside 'alimit', get it ++** directly from the array part. Otherwise, if 'alimit' is not equal to ++** the real size of the array, key still can be in the array part. In ++** this case, try to avoid a call to 'luaH_realasize' when key is just ++** one more than the limit (so that it can be incremented without ++** changing the real size of the array). ++*/ ++const TValue *luaH_getint (Table *t, lua_Integer key) { ++ if (l_castS2U(key) - 1u < t->alimit) /* 'key' in [1, t->alimit]? */ ++ return &t->array[key - 1]; ++ else if (!limitequalsasize(t) && /* key still may be in the array part? */ ++ (l_castS2U(key) == t->alimit + 1 || ++ l_castS2U(key) - 1u < luaH_realasize(t))) { ++ t->alimit = cast_uint(key); /* probably '#t' is here now */ ++ return &t->array[key - 1]; ++ } ++ else { ++ Node *n = hashint(t, key); ++ for (;;) { /* check whether 'key' is somewhere in the chain */ ++ if (keyisinteger(n) && keyival(n) == key) ++ return gval(n); /* that's it */ ++ else { ++ int nx = gnext(n); ++ if (nx == 0) break; ++ n += nx; ++ } ++ } ++ return &absentkey; ++ } ++} ++ ++ ++/* ++** search function for short strings ++*/ ++const TValue *luaH_getshortstr (Table *t, TString *key) { ++ Node *n = hashstr(t, key); ++ lua_assert(key->tt == LUA_VSHRSTR); ++ for (;;) { /* check whether 'key' is somewhere in the chain */ ++ if (keyisshrstr(n) && eqshrstr(keystrval(n), key)) ++ return gval(n); /* that's it */ ++ else { ++ int nx = gnext(n); ++ if (nx == 0) ++ return &absentkey; /* not found */ ++ n += nx; ++ } ++ } ++} ++ ++ ++const TValue *luaH_getstr (Table *t, TString *key) { ++ if (key->tt == LUA_VSHRSTR) ++ return luaH_getshortstr(t, key); ++ else { /* for long strings, use generic case */ ++ TValue ko; ++ setsvalue(cast(lua_State *, NULL), &ko, key); ++ return getgeneric(t, &ko, 0); ++ } ++} ++ ++ ++/* ++** main search function ++*/ ++const TValue *luaH_get (Table *t, const TValue *key) { ++ switch (ttypetag(key)) { ++ case LUA_VSHRSTR: return luaH_getshortstr(t, tsvalue(key)); ++ case LUA_VNUMINT: return luaH_getint(t, ivalue(key)); ++ case LUA_VNIL: return &absentkey; ++ case LUA_VNUMFLT: { ++ lua_Integer k; ++ if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */ ++ return luaH_getint(t, k); /* use specialized version */ ++ /* else... */ ++ } /* FALLTHROUGH */ ++ default: ++ return getgeneric(t, key, 0); ++ } ++} ++ ++ ++/* ++** Finish a raw "set table" operation, where 'slot' is where the value ++** should have been (the result of a previous "get table"). ++** Beware: when using this function you probably need to check a GC ++** barrier and invalidate the TM cache. ++*/ ++void luaH_finishset (lua_State *L, Table *t, const TValue *key, ++ const TValue *slot, TValue *value) { ++ if (isabstkey(slot)) ++ luaH_newkey(L, t, key, value); ++ else ++ setobj2t(L, cast(TValue *, slot), value); ++} ++ ++ ++/* ++** beware: when using this function you probably need to check a GC ++** barrier and invalidate the TM cache. ++*/ ++void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) { ++ const TValue *slot = luaH_get(t, key); ++ luaH_finishset(L, t, key, slot, value); ++} ++ ++ ++void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) { ++ const TValue *p = luaH_getint(t, key); ++ if (isabstkey(p)) { ++ TValue k; ++ setivalue(&k, key); ++ luaH_newkey(L, t, &k, value); ++ } ++ else ++ setobj2t(L, cast(TValue *, p), value); ++} ++ ++ ++/* ++** Try to find a boundary in the hash part of table 't'. From the ++** caller, we know that 'j' is zero or present and that 'j + 1' is ++** present. We want to find a larger key that is absent from the ++** table, so that we can do a binary search between the two keys to ++** find a boundary. We keep doubling 'j' until we get an absent index. ++** If the doubling would overflow, we try LUA_MAXINTEGER. If it is ++** absent, we are ready for the binary search. ('j', being max integer, ++** is larger or equal to 'i', but it cannot be equal because it is ++** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a ++** boundary. ('j + 1' cannot be a present integer key because it is ++** not a valid integer in Lua.) ++*/ ++static lua_Unsigned hash_search (Table *t, lua_Unsigned j) { ++ lua_Unsigned i; ++ if (j == 0) j++; /* the caller ensures 'j + 1' is present */ ++ do { ++ i = j; /* 'i' is a present index */ ++ if (j <= l_castS2U(LUA_MAXINTEGER) / 2) ++ j *= 2; ++ else { ++ j = LUA_MAXINTEGER; ++ if (isempty(luaH_getint(t, j))) /* t[j] not present? */ ++ break; /* 'j' now is an absent index */ ++ else /* weird case */ ++ return j; /* well, max integer is a boundary... */ ++ } ++ } while (!isempty(luaH_getint(t, j))); /* repeat until an absent t[j] */ ++ /* i < j && t[i] present && t[j] absent */ ++ while (j - i > 1u) { /* do a binary search between them */ ++ lua_Unsigned m = (i + j) / 2; ++ if (isempty(luaH_getint(t, m))) j = m; ++ else i = m; ++ } ++ return i; ++} ++ ++ ++static unsigned int binsearch (const TValue *array, unsigned int i, ++ unsigned int j) { ++ while (j - i > 1u) { /* binary search */ ++ unsigned int m = (i + j) / 2; ++ if (isempty(&array[m - 1])) j = m; ++ else i = m; ++ } ++ return i; ++} ++ ++ ++/* ++** Try to find a boundary in table 't'. (A 'boundary' is an integer index ++** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent ++** and 'maxinteger' if t[maxinteger] is present.) ++** (In the next explanation, we use Lua indices, that is, with base 1. ++** The code itself uses base 0 when indexing the array part of the table.) ++** The code starts with 'limit = t->alimit', a position in the array ++** part that may be a boundary. ++** ++** (1) If 't[limit]' is empty, there must be a boundary before it. ++** As a common case (e.g., after 't[#t]=nil'), check whether 'limit-1' ++** is present. If so, it is a boundary. Otherwise, do a binary search ++** between 0 and limit to find a boundary. In both cases, try to ++** use this boundary as the new 'alimit', as a hint for the next call. ++** ++** (2) If 't[limit]' is not empty and the array has more elements ++** after 'limit', try to find a boundary there. Again, try first ++** the special case (which should be quite frequent) where 'limit+1' ++** is empty, so that 'limit' is a boundary. Otherwise, check the ++** last element of the array part. If it is empty, there must be a ++** boundary between the old limit (present) and the last element ++** (absent), which is found with a binary search. (This boundary always ++** can be a new limit.) ++** ++** (3) The last case is when there are no elements in the array part ++** (limit == 0) or its last element (the new limit) is present. ++** In this case, must check the hash part. If there is no hash part ++** or 'limit+1' is absent, 'limit' is a boundary. Otherwise, call ++** 'hash_search' to find a boundary in the hash part of the table. ++** (In those cases, the boundary is not inside the array part, and ++** therefore cannot be used as a new limit.) ++*/ ++lua_Unsigned luaH_getn (Table *t) { ++ unsigned int limit = t->alimit; ++ if (limit > 0 && isempty(&t->array[limit - 1])) { /* (1)? */ ++ /* there must be a boundary before 'limit' */ ++ if (limit >= 2 && !isempty(&t->array[limit - 2])) { ++ /* 'limit - 1' is a boundary; can it be a new limit? */ ++ if (ispow2realasize(t) && !ispow2(limit - 1)) { ++ t->alimit = limit - 1; ++ setnorealasize(t); /* now 'alimit' is not the real size */ ++ } ++ return limit - 1; ++ } ++ else { /* must search for a boundary in [0, limit] */ ++ unsigned int boundary = binsearch(t->array, 0, limit); ++ /* can this boundary represent the real size of the array? */ ++ if (ispow2realasize(t) && boundary > luaH_realasize(t) / 2) { ++ t->alimit = boundary; /* use it as the new limit */ ++ setnorealasize(t); ++ } ++ return boundary; ++ } ++ } ++ /* 'limit' is zero or present in table */ ++ if (!limitequalsasize(t)) { /* (2)? */ ++ /* 'limit' > 0 and array has more elements after 'limit' */ ++ if (isempty(&t->array[limit])) /* 'limit + 1' is empty? */ ++ return limit; /* this is the boundary */ ++ /* else, try last element in the array */ ++ limit = luaH_realasize(t); ++ if (isempty(&t->array[limit - 1])) { /* empty? */ ++ /* there must be a boundary in the array after old limit, ++ and it must be a valid new limit */ ++ unsigned int boundary = binsearch(t->array, t->alimit, limit); ++ t->alimit = boundary; ++ return boundary; ++ } ++ /* else, new limit is present in the table; check the hash part */ ++ } ++ /* (3) 'limit' is the last element and either is zero or present in table */ ++ lua_assert(limit == luaH_realasize(t) && ++ (limit == 0 || !isempty(&t->array[limit - 1]))); ++ if (isdummy(t) || isempty(luaH_getint(t, cast(lua_Integer, limit + 1)))) ++ return limit; /* 'limit + 1' is absent */ ++ else /* 'limit + 1' is also present */ ++ return hash_search(t, limit); ++} ++ ++ ++ ++#if defined(LUA_DEBUG) ++ ++/* export these functions for the test library */ ++ ++Node *luaH_mainposition (const Table *t, const TValue *key) { ++ return mainpositionTV(t, key); ++} ++ ++int luaH_isdummy (const Table *t) { return isdummy(t); } ++ ++#endif +diff --git a/src/bin/lua/ltable.h b/src/bin/lua/ltable.h +new file mode 100644 +index 0000000000..7bbbcb213f +--- /dev/null ++++ b/src/bin/lua/ltable.h +@@ -0,0 +1,66 @@ ++/* ++** $Id: ltable.h $ ++** Lua tables (hash) ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef ltable_h ++#define ltable_h ++ ++#include "lobject.h" ++ ++ ++#define gnode(t,i) (&(t)->node[i]) ++#define gval(n) (&(n)->i_val) ++#define gnext(n) ((n)->u.next) ++ ++ ++/* ++** Clear all bits of fast-access metamethods, which means that the table ++** may have any of these metamethods. (First access that fails after the ++** clearing will set the bit again.) ++*/ ++#define invalidateTMcache(t) ((t)->flags &= ~maskflags) ++ ++ ++/* true when 't' is using 'dummynode' as its hash part */ ++#define isdummy(t) ((t)->lastfree == NULL) ++ ++ ++/* allocated size for hash nodes */ ++#define allocsizenode(t) (isdummy(t) ? 0 : sizenode(t)) ++ ++ ++/* returns the Node, given the value of a table entry */ ++#define nodefromval(v) cast(Node *, (v)) ++ ++ ++LUAI_FUNC const TValue *luaH_getint (Table *t, lua_Integer key); ++LUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key, ++ TValue *value); ++LUAI_FUNC const TValue *luaH_getshortstr (Table *t, TString *key); ++LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key); ++LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key); ++LUAI_FUNC void luaH_newkey (lua_State *L, Table *t, const TValue *key, ++ TValue *value); ++LUAI_FUNC void luaH_set (lua_State *L, Table *t, const TValue *key, ++ TValue *value); ++LUAI_FUNC void luaH_finishset (lua_State *L, Table *t, const TValue *key, ++ const TValue *slot, TValue *value); ++LUAI_FUNC Table *luaH_new (lua_State *L); ++LUAI_FUNC void luaH_resize (lua_State *L, Table *t, unsigned int nasize, ++ unsigned int nhsize); ++LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize); ++LUAI_FUNC void luaH_free (lua_State *L, Table *t); ++LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key); ++LUAI_FUNC lua_Unsigned luaH_getn (Table *t); ++LUAI_FUNC unsigned int luaH_realasize (const Table *t); ++ ++ ++#if defined(LUA_DEBUG) ++LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key); ++LUAI_FUNC int luaH_isdummy (const Table *t); ++#endif ++ ++ ++#endif +diff --git a/src/bin/lua/ltablib.c b/src/bin/lua/ltablib.c +new file mode 100644 +index 0000000000..d80eb80154 +--- /dev/null ++++ b/src/bin/lua/ltablib.c +@@ -0,0 +1,429 @@ ++/* ++** $Id: ltablib.c $ ++** Library for Table Manipulation ++** See Copyright Notice in lua.h ++*/ ++ ++#define ltablib_c ++#define LUA_LIB ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++#include ++ ++#include "lua.h" ++ ++#include "lauxlib.h" ++#include "lualib.h" ++ ++ ++/* ++** Operations that an object must define to mimic a table ++** (some functions only need some of them) ++*/ ++#define TAB_R 1 /* read */ ++#define TAB_W 2 /* write */ ++#define TAB_L 4 /* length */ ++#define TAB_RW (TAB_R | TAB_W) /* read/write */ ++ ++ ++#define aux_getn(L,n,w) (checktab(L, n, (w) | TAB_L), luaL_len(L, n)) ++ ++ ++static int checkfield (lua_State *L, const char *key, int n) { ++ lua_pushstring(L, key); ++ return (lua_rawget(L, -n) != LUA_TNIL); ++} ++ ++ ++/* ++** Check that 'arg' either is a table or can behave like one (that is, ++** has a metatable with the required metamethods) ++*/ ++static void checktab (lua_State *L, int arg, int what) { ++ if (lua_type(L, arg) != LUA_TTABLE) { /* is it not a table? */ ++ int n = 1; /* number of elements to pop */ ++ if (lua_getmetatable(L, arg) && /* must have metatable */ ++ (!(what & TAB_R) || checkfield(L, "__index", ++n)) && ++ (!(what & TAB_W) || checkfield(L, "__newindex", ++n)) && ++ (!(what & TAB_L) || checkfield(L, "__len", ++n))) { ++ lua_pop(L, n); /* pop metatable and tested metamethods */ ++ } ++ else ++ luaL_checktype(L, arg, LUA_TTABLE); /* force an error */ ++ } ++} ++ ++ ++static int tinsert (lua_State *L) { ++ lua_Integer e = aux_getn(L, 1, TAB_RW) + 1; /* first empty element */ ++ lua_Integer pos; /* where to insert new element */ ++ switch (lua_gettop(L)) { ++ case 2: { /* called with only 2 arguments */ ++ pos = e; /* insert new element at the end */ ++ break; ++ } ++ case 3: { ++ lua_Integer i; ++ pos = luaL_checkinteger(L, 2); /* 2nd argument is the position */ ++ /* check whether 'pos' is in [1, e] */ ++ luaL_argcheck(L, (lua_Unsigned)pos - 1u < (lua_Unsigned)e, 2, ++ "position out of bounds"); ++ for (i = e; i > pos; i--) { /* move up elements */ ++ lua_geti(L, 1, i - 1); ++ lua_seti(L, 1, i); /* t[i] = t[i - 1] */ ++ } ++ break; ++ } ++ default: { ++ return luaL_error(L, "wrong number of arguments to 'insert'"); ++ } ++ } ++ lua_seti(L, 1, pos); /* t[pos] = v */ ++ return 0; ++} ++ ++ ++static int tremove (lua_State *L) { ++ lua_Integer size = aux_getn(L, 1, TAB_RW); ++ lua_Integer pos = luaL_optinteger(L, 2, size); ++ if (pos != size) /* validate 'pos' if given */ ++ /* check whether 'pos' is in [1, size + 1] */ ++ luaL_argcheck(L, (lua_Unsigned)pos - 1u <= (lua_Unsigned)size, 1, ++ "position out of bounds"); ++ lua_geti(L, 1, pos); /* result = t[pos] */ ++ for ( ; pos < size; pos++) { ++ lua_geti(L, 1, pos + 1); ++ lua_seti(L, 1, pos); /* t[pos] = t[pos + 1] */ ++ } ++ lua_pushnil(L); ++ lua_seti(L, 1, pos); /* remove entry t[pos] */ ++ return 1; ++} ++ ++ ++/* ++** Copy elements (1[f], ..., 1[e]) into (tt[t], tt[t+1], ...). Whenever ++** possible, copy in increasing order, which is better for rehashing. ++** "possible" means destination after original range, or smaller ++** than origin, or copying to another table. ++*/ ++static int tmove (lua_State *L) { ++ lua_Integer f = luaL_checkinteger(L, 2); ++ lua_Integer e = luaL_checkinteger(L, 3); ++ lua_Integer t = luaL_checkinteger(L, 4); ++ int tt = !lua_isnoneornil(L, 5) ? 5 : 1; /* destination table */ ++ checktab(L, 1, TAB_R); ++ checktab(L, tt, TAB_W); ++ if (e >= f) { /* otherwise, nothing to move */ ++ lua_Integer n, i; ++ luaL_argcheck(L, f > 0 || e < LUA_MAXINTEGER + f, 3, ++ "too many elements to move"); ++ n = e - f + 1; /* number of elements to move */ ++ luaL_argcheck(L, t <= LUA_MAXINTEGER - n + 1, 4, ++ "destination wrap around"); ++ if (t > e || t <= f || (tt != 1 && !lua_compare(L, 1, tt, LUA_OPEQ))) { ++ for (i = 0; i < n; i++) { ++ lua_geti(L, 1, f + i); ++ lua_seti(L, tt, t + i); ++ } ++ } ++ else { ++ for (i = n - 1; i >= 0; i--) { ++ lua_geti(L, 1, f + i); ++ lua_seti(L, tt, t + i); ++ } ++ } ++ } ++ lua_pushvalue(L, tt); /* return destination table */ ++ return 1; ++} ++ ++ ++static void addfield (lua_State *L, luaL_Buffer *b, lua_Integer i) { ++ lua_geti(L, 1, i); ++ if (l_unlikely(!lua_isstring(L, -1))) ++ luaL_error(L, "invalid value (%s) at index %I in table for 'concat'", ++ luaL_typename(L, -1), i); ++ luaL_addvalue(b); ++} ++ ++ ++static int tconcat (lua_State *L) { ++ luaL_Buffer b; ++ lua_Integer last = aux_getn(L, 1, TAB_R); ++ size_t lsep; ++ const char *sep = luaL_optlstring(L, 2, "", &lsep); ++ lua_Integer i = luaL_optinteger(L, 3, 1); ++ last = luaL_optinteger(L, 4, last); ++ luaL_buffinit(L, &b); ++ for (; i < last; i++) { ++ addfield(L, &b, i); ++ luaL_addlstring(&b, sep, lsep); ++ } ++ if (i == last) /* add last value (if interval was not empty) */ ++ addfield(L, &b, i); ++ luaL_pushresult(&b); ++ return 1; ++} ++ ++ ++/* ++** {====================================================== ++** Pack/unpack ++** ======================================================= ++*/ ++ ++static int tpack (lua_State *L) { ++ int i; ++ int n = lua_gettop(L); /* number of elements to pack */ ++ lua_createtable(L, n, 1); /* create result table */ ++ lua_insert(L, 1); /* put it at index 1 */ ++ for (i = n; i >= 1; i--) /* assign elements */ ++ lua_seti(L, 1, i); ++ lua_pushinteger(L, n); ++ lua_setfield(L, 1, "n"); /* t.n = number of elements */ ++ return 1; /* return table */ ++} ++ ++ ++static int tunpack (lua_State *L) { ++ lua_Unsigned n; ++ lua_Integer i = luaL_optinteger(L, 2, 1); ++ lua_Integer e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1)); ++ if (i > e) return 0; /* empty range */ ++ n = (lua_Unsigned)e - i; /* number of elements minus 1 (avoid overflows) */ ++ if (l_unlikely(n >= (unsigned int)INT_MAX || ++ !lua_checkstack(L, (int)(++n)))) ++ return luaL_error(L, "too many results to unpack"); ++ for (; i < e; i++) { /* push arg[i..e - 1] (to avoid overflows) */ ++ lua_geti(L, 1, i); ++ } ++ lua_geti(L, 1, e); /* push last element */ ++ return (int)n; ++} ++ ++/* }====================================================== */ ++ ++ ++ ++/* ++** {====================================================== ++** Quicksort ++** (based on 'Algorithms in MODULA-3', Robert Sedgewick; ++** Addison-Wesley, 1993.) ++** ======================================================= ++*/ ++ ++ ++/* type for array indices */ ++typedef unsigned int IdxT; ++ ++ ++/* ++** Produce a "random" 'unsigned int' to randomize pivot choice. This ++** macro is used only when 'sort' detects a big imbalance in the result ++** of a partition. (If you don't want/need this "randomness", ~0 is a ++** good choice.) ++*/ ++#if !defined(l_randomizePivot) /* { */ ++ ++#include ++ ++/* size of 'e' measured in number of 'unsigned int's */ ++#define sof(e) (sizeof(e) / sizeof(unsigned int)) ++ ++/* ++** Use 'time' and 'clock' as sources of "randomness". Because we don't ++** know the types 'clock_t' and 'time_t', we cannot cast them to ++** anything without risking overflows. A safe way to use their values ++** is to copy them to an array of a known type and use the array values. ++*/ ++static unsigned int l_randomizePivot (void) { ++ clock_t c = clock(); ++ time_t t = time(NULL); ++ unsigned int buff[sof(c) + sof(t)]; ++ unsigned int i, rnd = 0; ++ memcpy(buff, &c, sof(c) * sizeof(unsigned int)); ++ memcpy(buff + sof(c), &t, sof(t) * sizeof(unsigned int)); ++ for (i = 0; i < sof(buff); i++) ++ rnd += buff[i]; ++ return rnd; ++} ++ ++#endif /* } */ ++ ++ ++/* arrays larger than 'RANLIMIT' may use randomized pivots */ ++#define RANLIMIT 100u ++ ++ ++static void set2 (lua_State *L, IdxT i, IdxT j) { ++ lua_seti(L, 1, i); ++ lua_seti(L, 1, j); ++} ++ ++ ++/* ++** Return true iff value at stack index 'a' is less than the value at ++** index 'b' (according to the order of the sort). ++*/ ++static int sort_comp (lua_State *L, int a, int b) { ++ if (lua_isnil(L, 2)) /* no function? */ ++ return lua_compare(L, a, b, LUA_OPLT); /* a < b */ ++ else { /* function */ ++ int res; ++ lua_pushvalue(L, 2); /* push function */ ++ lua_pushvalue(L, a-1); /* -1 to compensate function */ ++ lua_pushvalue(L, b-2); /* -2 to compensate function and 'a' */ ++ lua_call(L, 2, 1); /* call function */ ++ res = lua_toboolean(L, -1); /* get result */ ++ lua_pop(L, 1); /* pop result */ ++ return res; ++ } ++} ++ ++ ++/* ++** Does the partition: Pivot P is at the top of the stack. ++** precondition: a[lo] <= P == a[up-1] <= a[up], ++** so it only needs to do the partition from lo + 1 to up - 2. ++** Pos-condition: a[lo .. i - 1] <= a[i] == P <= a[i + 1 .. up] ++** returns 'i'. ++*/ ++static IdxT partition (lua_State *L, IdxT lo, IdxT up) { ++ IdxT i = lo; /* will be incremented before first use */ ++ IdxT j = up - 1; /* will be decremented before first use */ ++ /* loop invariant: a[lo .. i] <= P <= a[j .. up] */ ++ for (;;) { ++ /* next loop: repeat ++i while a[i] < P */ ++ while ((void)lua_geti(L, 1, ++i), sort_comp(L, -1, -2)) { ++ if (l_unlikely(i == up - 1)) /* a[i] < P but a[up - 1] == P ?? */ ++ luaL_error(L, "invalid order function for sorting"); ++ lua_pop(L, 1); /* remove a[i] */ ++ } ++ /* after the loop, a[i] >= P and a[lo .. i - 1] < P */ ++ /* next loop: repeat --j while P < a[j] */ ++ while ((void)lua_geti(L, 1, --j), sort_comp(L, -3, -1)) { ++ if (l_unlikely(j < i)) /* j < i but a[j] > P ?? */ ++ luaL_error(L, "invalid order function for sorting"); ++ lua_pop(L, 1); /* remove a[j] */ ++ } ++ /* after the loop, a[j] <= P and a[j + 1 .. up] >= P */ ++ if (j < i) { /* no elements out of place? */ ++ /* a[lo .. i - 1] <= P <= a[j + 1 .. i .. up] */ ++ lua_pop(L, 1); /* pop a[j] */ ++ /* swap pivot (a[up - 1]) with a[i] to satisfy pos-condition */ ++ set2(L, up - 1, i); ++ return i; ++ } ++ /* otherwise, swap a[i] - a[j] to restore invariant and repeat */ ++ set2(L, i, j); ++ } ++} ++ ++ ++/* ++** Choose an element in the middle (2nd-3th quarters) of [lo,up] ++** "randomized" by 'rnd' ++*/ ++static IdxT choosePivot (IdxT lo, IdxT up, unsigned int rnd) { ++ IdxT r4 = (up - lo) / 4; /* range/4 */ ++ IdxT p = rnd % (r4 * 2) + (lo + r4); ++ lua_assert(lo + r4 <= p && p <= up - r4); ++ return p; ++} ++ ++ ++/* ++** Quicksort algorithm (recursive function) ++*/ ++static void auxsort (lua_State *L, IdxT lo, IdxT up, ++ unsigned int rnd) { ++ while (lo < up) { /* loop for tail recursion */ ++ IdxT p; /* Pivot index */ ++ IdxT n; /* to be used later */ ++ /* sort elements 'lo', 'p', and 'up' */ ++ lua_geti(L, 1, lo); ++ lua_geti(L, 1, up); ++ if (sort_comp(L, -1, -2)) /* a[up] < a[lo]? */ ++ set2(L, lo, up); /* swap a[lo] - a[up] */ ++ else ++ lua_pop(L, 2); /* remove both values */ ++ if (up - lo == 1) /* only 2 elements? */ ++ return; /* already sorted */ ++ if (up - lo < RANLIMIT || rnd == 0) /* small interval or no randomize? */ ++ p = (lo + up)/2; /* middle element is a good pivot */ ++ else /* for larger intervals, it is worth a random pivot */ ++ p = choosePivot(lo, up, rnd); ++ lua_geti(L, 1, p); ++ lua_geti(L, 1, lo); ++ if (sort_comp(L, -2, -1)) /* a[p] < a[lo]? */ ++ set2(L, p, lo); /* swap a[p] - a[lo] */ ++ else { ++ lua_pop(L, 1); /* remove a[lo] */ ++ lua_geti(L, 1, up); ++ if (sort_comp(L, -1, -2)) /* a[up] < a[p]? */ ++ set2(L, p, up); /* swap a[up] - a[p] */ ++ else ++ lua_pop(L, 2); ++ } ++ if (up - lo == 2) /* only 3 elements? */ ++ return; /* already sorted */ ++ lua_geti(L, 1, p); /* get middle element (Pivot) */ ++ lua_pushvalue(L, -1); /* push Pivot */ ++ lua_geti(L, 1, up - 1); /* push a[up - 1] */ ++ set2(L, p, up - 1); /* swap Pivot (a[p]) with a[up - 1] */ ++ p = partition(L, lo, up); ++ /* a[lo .. p - 1] <= a[p] == P <= a[p + 1 .. up] */ ++ if (p - lo < up - p) { /* lower interval is smaller? */ ++ auxsort(L, lo, p - 1, rnd); /* call recursively for lower interval */ ++ n = p - lo; /* size of smaller interval */ ++ lo = p + 1; /* tail call for [p + 1 .. up] (upper interval) */ ++ } ++ else { ++ auxsort(L, p + 1, up, rnd); /* call recursively for upper interval */ ++ n = up - p; /* size of smaller interval */ ++ up = p - 1; /* tail call for [lo .. p - 1] (lower interval) */ ++ } ++ if ((up - lo) / 128 > n) /* partition too imbalanced? */ ++ rnd = l_randomizePivot(); /* try a new randomization */ ++ } /* tail call auxsort(L, lo, up, rnd) */ ++} ++ ++ ++static int sort (lua_State *L) { ++ lua_Integer n = aux_getn(L, 1, TAB_RW); ++ if (n > 1) { /* non-trivial interval? */ ++ luaL_argcheck(L, n < INT_MAX, 1, "array too big"); ++ if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */ ++ luaL_checktype(L, 2, LUA_TFUNCTION); /* must be a function */ ++ lua_settop(L, 2); /* make sure there are two arguments */ ++ auxsort(L, 1, (IdxT)n, 0); ++ } ++ return 0; ++} ++ ++/* }====================================================== */ ++ ++ ++static const luaL_Reg tab_funcs[] = { ++ {"concat", tconcat}, ++ {"insert", tinsert}, ++ {"pack", tpack}, ++ {"unpack", tunpack}, ++ {"remove", tremove}, ++ {"move", tmove}, ++ {"sort", sort}, ++ {NULL, NULL} ++}; ++ ++ ++LUAMOD_API int luaopen_table (lua_State *L) { ++ luaL_newlib(L, tab_funcs); ++ return 1; ++} ++ +diff --git a/src/bin/lua/ltm.c b/src/bin/lua/ltm.c +new file mode 100644 +index 0000000000..b657b783a8 +--- /dev/null ++++ b/src/bin/lua/ltm.c +@@ -0,0 +1,271 @@ ++/* ++** $Id: ltm.c $ ++** Tag methods ++** See Copyright Notice in lua.h ++*/ ++ ++#define ltm_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++#include ++ ++#include "lua.h" ++ ++#include "ldebug.h" ++#include "ldo.h" ++#include "lgc.h" ++#include "lobject.h" ++#include "lstate.h" ++#include "lstring.h" ++#include "ltable.h" ++#include "ltm.h" ++#include "lvm.h" ++ ++ ++static const char udatatypename[] = "userdata"; ++ ++LUAI_DDEF const char *const luaT_typenames_[LUA_TOTALTYPES] = { ++ "no value", ++ "nil", "boolean", udatatypename, "number", ++ "string", "table", "function", udatatypename, "thread", ++ "upvalue", "proto" /* these last cases are used for tests only */ ++}; ++ ++ ++void luaT_init (lua_State *L) { ++ static const char *const luaT_eventname[] = { /* ORDER TM */ ++ "__index", "__newindex", ++ "__gc", "__mode", "__len", "__eq", ++ "__add", "__sub", "__mul", "__mod", "__pow", ++ "__div", "__idiv", ++ "__band", "__bor", "__bxor", "__shl", "__shr", ++ "__unm", "__bnot", "__lt", "__le", ++ "__concat", "__call", "__close" ++ }; ++ int i; ++ for (i=0; itmname[i] = luaS_new(L, luaT_eventname[i]); ++ luaC_fix(L, obj2gco(G(L)->tmname[i])); /* never collect these names */ ++ } ++} ++ ++ ++/* ++** function to be used with macro "fasttm": optimized for absence of ++** tag methods ++*/ ++const TValue *luaT_gettm (Table *events, TMS event, TString *ename) { ++ const TValue *tm = luaH_getshortstr(events, ename); ++ lua_assert(event <= TM_EQ); ++ if (notm(tm)) { /* no tag method? */ ++ events->flags |= cast_byte(1u<metatable; ++ break; ++ case LUA_TUSERDATA: ++ mt = uvalue(o)->metatable; ++ break; ++ default: ++ mt = G(L)->mt[ttype(o)]; ++ } ++ return (mt ? luaH_getshortstr(mt, G(L)->tmname[event]) : &G(L)->nilvalue); ++} ++ ++ ++/* ++** Return the name of the type of an object. For tables and userdata ++** with metatable, use their '__name' metafield, if present. ++*/ ++const char *luaT_objtypename (lua_State *L, const TValue *o) { ++ Table *mt; ++ if ((ttistable(o) && (mt = hvalue(o)->metatable) != NULL) || ++ (ttisfulluserdata(o) && (mt = uvalue(o)->metatable) != NULL)) { ++ const TValue *name = luaH_getshortstr(mt, luaS_new(L, "__name")); ++ if (ttisstring(name)) /* is '__name' a string? */ ++ return getstr(tsvalue(name)); /* use it as type name */ ++ } ++ return ttypename(ttype(o)); /* else use standard type name */ ++} ++ ++ ++void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1, ++ const TValue *p2, const TValue *p3) { ++ StkId func = L->top; ++ setobj2s(L, func, f); /* push function (assume EXTRA_STACK) */ ++ setobj2s(L, func + 1, p1); /* 1st argument */ ++ setobj2s(L, func + 2, p2); /* 2nd argument */ ++ setobj2s(L, func + 3, p3); /* 3rd argument */ ++ L->top = func + 4; ++ /* metamethod may yield only when called from Lua code */ ++ if (isLuacode(L->ci)) ++ luaD_call(L, func, 0); ++ else ++ luaD_callnoyield(L, func, 0); ++} ++ ++ ++void luaT_callTMres (lua_State *L, const TValue *f, const TValue *p1, ++ const TValue *p2, StkId res) { ++ ptrdiff_t result = savestack(L, res); ++ StkId func = L->top; ++ setobj2s(L, func, f); /* push function (assume EXTRA_STACK) */ ++ setobj2s(L, func + 1, p1); /* 1st argument */ ++ setobj2s(L, func + 2, p2); /* 2nd argument */ ++ L->top += 3; ++ /* metamethod may yield only when called from Lua code */ ++ if (isLuacode(L->ci)) ++ luaD_call(L, func, 1); ++ else ++ luaD_callnoyield(L, func, 1); ++ res = restorestack(L, result); ++ setobjs2s(L, res, --L->top); /* move result to its place */ ++} ++ ++ ++static int callbinTM (lua_State *L, const TValue *p1, const TValue *p2, ++ StkId res, TMS event) { ++ const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */ ++ if (notm(tm)) ++ tm = luaT_gettmbyobj(L, p2, event); /* try second operand */ ++ if (notm(tm)) return 0; ++ luaT_callTMres(L, tm, p1, p2, res); ++ return 1; ++} ++ ++ ++void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2, ++ StkId res, TMS event) { ++ if (l_unlikely(!callbinTM(L, p1, p2, res, event))) { ++ switch (event) { ++ case TM_BAND: case TM_BOR: case TM_BXOR: ++ case TM_SHL: case TM_SHR: case TM_BNOT: { ++ if (ttisnumber(p1) && ttisnumber(p2)) ++ luaG_tointerror(L, p1, p2); ++ else ++ luaG_opinterror(L, p1, p2, "perform bitwise operation on"); ++ } ++ /* calls never return, but to avoid warnings: *//* FALLTHROUGH */ ++ default: ++ luaG_opinterror(L, p1, p2, "perform arithmetic on"); ++ } ++ } ++} ++ ++ ++void luaT_tryconcatTM (lua_State *L) { ++ StkId top = L->top; ++ if (l_unlikely(!callbinTM(L, s2v(top - 2), s2v(top - 1), top - 2, ++ TM_CONCAT))) ++ luaG_concaterror(L, s2v(top - 2), s2v(top - 1)); ++} ++ ++ ++void luaT_trybinassocTM (lua_State *L, const TValue *p1, const TValue *p2, ++ int flip, StkId res, TMS event) { ++ if (flip) ++ luaT_trybinTM(L, p2, p1, res, event); ++ else ++ luaT_trybinTM(L, p1, p2, res, event); ++} ++ ++ ++void luaT_trybiniTM (lua_State *L, const TValue *p1, lua_Integer i2, ++ int flip, StkId res, TMS event) { ++ TValue aux; ++ setivalue(&aux, i2); ++ luaT_trybinassocTM(L, p1, &aux, flip, res, event); ++} ++ ++ ++/* ++** Calls an order tag method. ++** For lessequal, LUA_COMPAT_LT_LE keeps compatibility with old ++** behavior: if there is no '__le', try '__lt', based on l <= r iff ++** !(r < l) (assuming a total order). If the metamethod yields during ++** this substitution, the continuation has to know about it (to negate ++** the result of rtop, event)) /* try original event */ ++ return !l_isfalse(s2v(L->top)); ++#if defined(LUA_COMPAT_LT_LE) ++ else if (event == TM_LE) { ++ /* try '!(p2 < p1)' for '(p1 <= p2)' */ ++ L->ci->callstatus |= CIST_LEQ; /* mark it is doing 'lt' for 'le' */ ++ if (callbinTM(L, p2, p1, L->top, TM_LT)) { ++ L->ci->callstatus ^= CIST_LEQ; /* clear mark */ ++ return l_isfalse(s2v(L->top)); ++ } ++ /* else error will remove this 'ci'; no need to clear mark */ ++ } ++#endif ++ luaG_ordererror(L, p1, p2); /* no metamethod found */ ++ return 0; /* to avoid warnings */ ++} ++ ++ ++int luaT_callorderiTM (lua_State *L, const TValue *p1, int v2, ++ int flip, int isfloat, TMS event) { ++ TValue aux; const TValue *p2; ++ if (isfloat) { ++ setfltvalue(&aux, cast_num(v2)); ++ } ++ else ++ setivalue(&aux, v2); ++ if (flip) { /* arguments were exchanged? */ ++ p2 = p1; p1 = &aux; /* correct them */ ++ } ++ else ++ p2 = &aux; ++ return luaT_callorderTM(L, p1, p2, event); ++} ++ ++ ++void luaT_adjustvarargs (lua_State *L, int nfixparams, CallInfo *ci, ++ const Proto *p) { ++ int i; ++ int actual = cast_int(L->top - ci->func) - 1; /* number of arguments */ ++ int nextra = actual - nfixparams; /* number of extra arguments */ ++ ci->u.l.nextraargs = nextra; ++ luaD_checkstack(L, p->maxstacksize + 1); ++ /* copy function to the top of the stack */ ++ setobjs2s(L, L->top++, ci->func); ++ /* move fixed parameters to the top of the stack */ ++ for (i = 1; i <= nfixparams; i++) { ++ setobjs2s(L, L->top++, ci->func + i); ++ setnilvalue(s2v(ci->func + i)); /* erase original parameter (for GC) */ ++ } ++ ci->func += actual + 1; ++ ci->top += actual + 1; ++ lua_assert(L->top <= ci->top && ci->top <= L->stack_last); ++} ++ ++ ++void luaT_getvarargs (lua_State *L, CallInfo *ci, StkId where, int wanted) { ++ int i; ++ int nextra = ci->u.l.nextraargs; ++ if (wanted < 0) { ++ wanted = nextra; /* get all extra arguments available */ ++ checkstackGCp(L, nextra, where); /* ensure stack space */ ++ L->top = where + nextra; /* next instruction will need top */ ++ } ++ for (i = 0; i < wanted && i < nextra; i++) ++ setobjs2s(L, where + i, ci->func - nextra + i); ++ for (; i < wanted; i++) /* complete required results with nil */ ++ setnilvalue(s2v(where + i)); ++} ++ +diff --git a/src/bin/lua/ltm.h b/src/bin/lua/ltm.h +new file mode 100644 +index 0000000000..73b833c605 +--- /dev/null ++++ b/src/bin/lua/ltm.h +@@ -0,0 +1,103 @@ ++/* ++** $Id: ltm.h $ ++** Tag methods ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef ltm_h ++#define ltm_h ++ ++ ++#include "lobject.h" ++ ++ ++/* ++* WARNING: if you change the order of this enumeration, ++* grep "ORDER TM" and "ORDER OP" ++*/ ++typedef enum { ++ TM_INDEX, ++ TM_NEWINDEX, ++ TM_GC, ++ TM_MODE, ++ TM_LEN, ++ TM_EQ, /* last tag method with fast access */ ++ TM_ADD, ++ TM_SUB, ++ TM_MUL, ++ TM_MOD, ++ TM_POW, ++ TM_DIV, ++ TM_IDIV, ++ TM_BAND, ++ TM_BOR, ++ TM_BXOR, ++ TM_SHL, ++ TM_SHR, ++ TM_UNM, ++ TM_BNOT, ++ TM_LT, ++ TM_LE, ++ TM_CONCAT, ++ TM_CALL, ++ TM_CLOSE, ++ TM_N /* number of elements in the enum */ ++} TMS; ++ ++ ++/* ++** Mask with 1 in all fast-access methods. A 1 in any of these bits ++** in the flag of a (meta)table means the metatable does not have the ++** corresponding metamethod field. (Bit 7 of the flag is used for ++** 'isrealasize'.) ++*/ ++#define maskflags (~(~0u << (TM_EQ + 1))) ++ ++ ++/* ++** Test whether there is no tagmethod. ++** (Because tagmethods use raw accesses, the result may be an "empty" nil.) ++*/ ++#define notm(tm) ttisnil(tm) ++ ++ ++#define gfasttm(g,et,e) ((et) == NULL ? NULL : \ ++ ((et)->flags & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e])) ++ ++#define fasttm(l,et,e) gfasttm(G(l), et, e) ++ ++#define ttypename(x) luaT_typenames_[(x) + 1] ++ ++LUAI_DDEC(const char *const luaT_typenames_[LUA_TOTALTYPES];) ++ ++ ++LUAI_FUNC const char *luaT_objtypename (lua_State *L, const TValue *o); ++ ++LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename); ++LUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, ++ TMS event); ++LUAI_FUNC void luaT_init (lua_State *L); ++ ++LUAI_FUNC void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1, ++ const TValue *p2, const TValue *p3); ++LUAI_FUNC void luaT_callTMres (lua_State *L, const TValue *f, ++ const TValue *p1, const TValue *p2, StkId p3); ++LUAI_FUNC void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2, ++ StkId res, TMS event); ++LUAI_FUNC void luaT_tryconcatTM (lua_State *L); ++LUAI_FUNC void luaT_trybinassocTM (lua_State *L, const TValue *p1, ++ const TValue *p2, int inv, StkId res, TMS event); ++LUAI_FUNC void luaT_trybiniTM (lua_State *L, const TValue *p1, lua_Integer i2, ++ int inv, StkId res, TMS event); ++LUAI_FUNC int luaT_callorderTM (lua_State *L, const TValue *p1, ++ const TValue *p2, TMS event); ++LUAI_FUNC int luaT_callorderiTM (lua_State *L, const TValue *p1, int v2, ++ int inv, int isfloat, TMS event); ++ ++LUAI_FUNC void luaT_adjustvarargs (lua_State *L, int nfixparams, ++ struct CallInfo *ci, const Proto *p); ++LUAI_FUNC void luaT_getvarargs (lua_State *L, struct CallInfo *ci, ++ StkId where, int wanted); ++ ++ ++#endif +diff --git a/src/bin/lua/lua.c b/src/bin/lua/lua.c +new file mode 100644 +index 0000000000..46b48dba92 +--- /dev/null ++++ b/src/bin/lua/lua.c +@@ -0,0 +1,659 @@ ++/* ++** $Id: lua.c $ ++** Lua stand-alone interpreter ++** See Copyright Notice in lua.h ++*/ ++ ++#define lua_c ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++#include ++ ++#include ++ ++#include "lua.h" ++ ++#include "lauxlib.h" ++#include "lualib.h" ++ ++ ++#if !defined(LUA_PROGNAME) ++#define LUA_PROGNAME "lua" ++#endif ++ ++#if !defined(LUA_INIT_VAR) ++#define LUA_INIT_VAR "LUA_INIT" ++#endif ++ ++#define LUA_INITVARVERSION LUA_INIT_VAR LUA_VERSUFFIX ++ ++ ++static lua_State *globalL = NULL; ++ ++static const char *progname = LUA_PROGNAME; ++ ++ ++#if defined(LUA_USE_POSIX) /* { */ ++ ++/* ++** Use 'sigaction' when available. ++*/ ++static void setsignal (int sig, void (*handler)(int)) { ++ struct sigaction sa; ++ sa.sa_handler = handler; ++ sa.sa_flags = 0; ++ sigemptyset(&sa.sa_mask); /* do not mask any signal */ ++ sigaction(sig, &sa, NULL); ++} ++ ++#else /* }{ */ ++ ++#define setsignal signal ++ ++#endif /* } */ ++ ++ ++/* ++** Hook set by signal function to stop the interpreter. ++*/ ++static void lstop (lua_State *L, lua_Debug *ar) { ++ (void)ar; /* unused arg. */ ++ lua_sethook(L, NULL, 0, 0); /* reset hook */ ++ luaL_error(L, "interrupted!"); ++} ++ ++ ++/* ++** Function to be called at a C signal. Because a C signal cannot ++** just change a Lua state (as there is no proper synchronization), ++** this function only sets a hook that, when called, will stop the ++** interpreter. ++*/ ++static void laction (int i) { ++ int flag = LUA_MASKCALL | LUA_MASKRET | LUA_MASKLINE | LUA_MASKCOUNT; ++ setsignal(i, SIG_DFL); /* if another SIGINT happens, terminate process */ ++ lua_sethook(globalL, lstop, flag, 1); ++} ++ ++ ++static void print_usage (const char *badoption) { ++ lua_writestringerror("%s: ", progname); ++ if (badoption[1] == 'e' || badoption[1] == 'l') ++ lua_writestringerror("'%s' needs argument\n", badoption); ++ else ++ lua_writestringerror("unrecognized option '%s'\n", badoption); ++ lua_writestringerror( ++ "usage: %s [options] [script [args]]\n" ++ "Available options are:\n" ++ " -e stat execute string 'stat'\n" ++ " -i enter interactive mode after executing 'script'\n" ++ " -l name require library 'name' into global 'name'\n" ++ " -v show version information\n" ++ " -E ignore environment variables\n" ++ " -W turn warnings on\n" ++ " -- stop handling options\n" ++ " - stop handling options and execute stdin\n" ++ , ++ progname); ++} ++ ++ ++/* ++** Prints an error message, adding the program name in front of it ++** (if present) ++*/ ++static void l_message (const char *pname, const char *msg) { ++ if (pname) lua_writestringerror("%s: ", pname); ++ lua_writestringerror("%s\n", msg); ++} ++ ++ ++/* ++** Check whether 'status' is not OK and, if so, prints the error ++** message on the top of the stack. It assumes that the error object ++** is a string, as it was either generated by Lua or by 'msghandler'. ++*/ ++static int report (lua_State *L, int status) { ++ if (status != LUA_OK) { ++ const char *msg = lua_tostring(L, -1); ++ l_message(progname, msg); ++ lua_pop(L, 1); /* remove message */ ++ } ++ return status; ++} ++ ++ ++/* ++** Message handler used to run all chunks ++*/ ++static int msghandler (lua_State *L) { ++ const char *msg = lua_tostring(L, 1); ++ if (msg == NULL) { /* is error object not a string? */ ++ if (luaL_callmeta(L, 1, "__tostring") && /* does it have a metamethod */ ++ lua_type(L, -1) == LUA_TSTRING) /* that produces a string? */ ++ return 1; /* that is the message */ ++ else ++ msg = lua_pushfstring(L, "(error object is a %s value)", ++ luaL_typename(L, 1)); ++ } ++ luaL_traceback(L, L, msg, 1); /* append a standard traceback */ ++ return 1; /* return the traceback */ ++} ++ ++ ++/* ++** Interface to 'lua_pcall', which sets appropriate message function ++** and C-signal handler. Used to run all chunks. ++*/ ++static int docall (lua_State *L, int narg, int nres) { ++ int status; ++ int base = lua_gettop(L) - narg; /* function index */ ++ lua_pushcfunction(L, msghandler); /* push message handler */ ++ lua_insert(L, base); /* put it under function and args */ ++ globalL = L; /* to be available to 'laction' */ ++ setsignal(SIGINT, laction); /* set C-signal handler */ ++ status = lua_pcall(L, narg, nres, base); ++ setsignal(SIGINT, SIG_DFL); /* reset C-signal handler */ ++ lua_remove(L, base); /* remove message handler from the stack */ ++ return status; ++} ++ ++ ++static void print_version (void) { ++ lua_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT)); ++ lua_writeline(); ++} ++ ++ ++/* ++** Create the 'arg' table, which stores all arguments from the ++** command line ('argv'). It should be aligned so that, at index 0, ++** it has 'argv[script]', which is the script name. The arguments ++** to the script (everything after 'script') go to positive indices; ++** other arguments (before the script name) go to negative indices. ++** If there is no script name, assume interpreter's name as base. ++*/ ++static void createargtable (lua_State *L, char **argv, int argc, int script) { ++ int i, narg; ++ if (script == argc) script = 0; /* no script name? */ ++ narg = argc - (script + 1); /* number of positive indices */ ++ lua_createtable(L, narg, script + 1); ++ for (i = 0; i < argc; i++) { ++ lua_pushstring(L, argv[i]); ++ lua_rawseti(L, -2, i - script); ++ } ++ lua_setglobal(L, "arg"); ++} ++ ++ ++static int dochunk (lua_State *L, int status) { ++ if (status == LUA_OK) status = docall(L, 0, 0); ++ return report(L, status); ++} ++ ++ ++static int dofile (lua_State *L, const char *name) { ++ return dochunk(L, luaL_loadfile(L, name)); ++} ++ ++ ++static int dostring (lua_State *L, const char *s, const char *name) { ++ return dochunk(L, luaL_loadbuffer(L, s, strlen(s), name)); ++} ++ ++ ++/* ++** Calls 'require(name)' and stores the result in a global variable ++** with the given name. ++*/ ++static int dolibrary (lua_State *L, const char *name) { ++ int status; ++ lua_getglobal(L, "require"); ++ lua_pushstring(L, name); ++ status = docall(L, 1, 1); /* call 'require(name)' */ ++ if (status == LUA_OK) ++ lua_setglobal(L, name); /* global[name] = require return */ ++ return report(L, status); ++} ++ ++ ++/* ++** Push on the stack the contents of table 'arg' from 1 to #arg ++*/ ++static int pushargs (lua_State *L) { ++ int i, n; ++ if (lua_getglobal(L, "arg") != LUA_TTABLE) ++ luaL_error(L, "'arg' is not a table"); ++ n = (int)luaL_len(L, -1); ++ luaL_checkstack(L, n + 3, "too many arguments to script"); ++ for (i = 1; i <= n; i++) ++ lua_rawgeti(L, -i, i); ++ lua_remove(L, -i); /* remove table from the stack */ ++ return n; ++} ++ ++ ++static int handle_script (lua_State *L, char **argv) { ++ int status; ++ const char *fname = argv[0]; ++ if (strcmp(fname, "-") == 0 && strcmp(argv[-1], "--") != 0) ++ fname = NULL; /* stdin */ ++ status = luaL_loadfile(L, fname); ++ if (status == LUA_OK) { ++ int n = pushargs(L); /* push arguments to script */ ++ status = docall(L, n, LUA_MULTRET); ++ } ++ return report(L, status); ++} ++ ++ ++/* bits of various argument indicators in 'args' */ ++#define has_error 1 /* bad option */ ++#define has_i 2 /* -i */ ++#define has_v 4 /* -v */ ++#define has_e 8 /* -e */ ++#define has_E 16 /* -E */ ++ ++ ++/* ++** Traverses all arguments from 'argv', returning a mask with those ++** needed before running any Lua code (or an error code if it finds ++** any invalid argument). 'first' returns the first not-handled argument ++** (either the script name or a bad argument in case of error). ++*/ ++static int collectargs (char **argv, int *first) { ++ int args = 0; ++ int i; ++ for (i = 1; argv[i] != NULL; i++) { ++ *first = i; ++ if (argv[i][0] != '-') /* not an option? */ ++ return args; /* stop handling options */ ++ switch (argv[i][1]) { /* else check option */ ++ case '-': /* '--' */ ++ if (argv[i][2] != '\0') /* extra characters after '--'? */ ++ return has_error; /* invalid option */ ++ *first = i + 1; ++ return args; ++ case '\0': /* '-' */ ++ return args; /* script "name" is '-' */ ++ case 'E': ++ if (argv[i][2] != '\0') /* extra characters? */ ++ return has_error; /* invalid option */ ++ args |= has_E; ++ break; ++ case 'W': ++ if (argv[i][2] != '\0') /* extra characters? */ ++ return has_error; /* invalid option */ ++ break; ++ case 'i': ++ args |= has_i; /* (-i implies -v) *//* FALLTHROUGH */ ++ case 'v': ++ if (argv[i][2] != '\0') /* extra characters? */ ++ return has_error; /* invalid option */ ++ args |= has_v; ++ break; ++ case 'e': ++ args |= has_e; /* FALLTHROUGH */ ++ case 'l': /* both options need an argument */ ++ if (argv[i][2] == '\0') { /* no concatenated argument? */ ++ i++; /* try next 'argv' */ ++ if (argv[i] == NULL || argv[i][0] == '-') ++ return has_error; /* no next argument or it is another option */ ++ } ++ break; ++ default: /* invalid option */ ++ return has_error; ++ } ++ } ++ *first = i; /* no script name */ ++ return args; ++} ++ ++ ++/* ++** Processes options 'e' and 'l', which involve running Lua code, and ++** 'W', which also affects the state. ++** Returns 0 if some code raises an error. ++*/ ++static int runargs (lua_State *L, char **argv, int n) { ++ int i; ++ for (i = 1; i < n; i++) { ++ int option = argv[i][1]; ++ lua_assert(argv[i][0] == '-'); /* already checked */ ++ switch (option) { ++ case 'e': case 'l': { ++ int status; ++ const char *extra = argv[i] + 2; /* both options need an argument */ ++ if (*extra == '\0') extra = argv[++i]; ++ lua_assert(extra != NULL); ++ status = (option == 'e') ++ ? dostring(L, extra, "=(command line)") ++ : dolibrary(L, extra); ++ if (status != LUA_OK) return 0; ++ break; ++ } ++ case 'W': ++ lua_warning(L, "@on", 0); /* warnings on */ ++ break; ++ } ++ } ++ return 1; ++} ++ ++ ++static int handle_luainit (lua_State *L) { ++ const char *name = "=" LUA_INITVARVERSION; ++ const char *init = getenv(name + 1); ++ if (init == NULL) { ++ name = "=" LUA_INIT_VAR; ++ init = getenv(name + 1); /* try alternative name */ ++ } ++ if (init == NULL) return LUA_OK; ++ else if (init[0] == '@') ++ return dofile(L, init+1); ++ else ++ return dostring(L, init, name); ++} ++ ++ ++/* ++** {================================================================== ++** Read-Eval-Print Loop (REPL) ++** =================================================================== ++*/ ++ ++#if !defined(LUA_PROMPT) ++#define LUA_PROMPT "> " ++#define LUA_PROMPT2 ">> " ++#endif ++ ++#if !defined(LUA_MAXINPUT) ++#define LUA_MAXINPUT 512 ++#endif ++ ++ ++/* ++** lua_stdin_is_tty detects whether the standard input is a 'tty' (that ++** is, whether we're running lua interactively). ++*/ ++#if !defined(lua_stdin_is_tty) /* { */ ++ ++#if defined(LUA_USE_POSIX) /* { */ ++ ++#include ++#define lua_stdin_is_tty() isatty(0) ++ ++#elif defined(LUA_USE_WINDOWS) /* }{ */ ++ ++#include ++#include ++ ++#define lua_stdin_is_tty() _isatty(_fileno(stdin)) ++ ++#else /* }{ */ ++ ++/* ISO C definition */ ++#define lua_stdin_is_tty() 1 /* assume stdin is a tty */ ++ ++#endif /* } */ ++ ++#endif /* } */ ++ ++ ++/* ++** lua_readline defines how to show a prompt and then read a line from ++** the standard input. ++** lua_saveline defines how to "save" a read line in a "history". ++** lua_freeline defines how to free a line read by lua_readline. ++*/ ++#if !defined(lua_readline) /* { */ ++ ++#if defined(LUA_USE_READLINE) /* { */ ++ ++#include ++#include ++#define lua_initreadline(L) ((void)L, rl_readline_name="lua") ++#define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL) ++#define lua_saveline(L,line) ((void)L, add_history(line)) ++#define lua_freeline(L,b) ((void)L, free(b)) ++ ++#else /* }{ */ ++ ++#define lua_initreadline(L) ((void)L) ++#define lua_readline(L,b,p) \ ++ ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \ ++ fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */ ++#define lua_saveline(L,line) { (void)L; (void)line; } ++#define lua_freeline(L,b) { (void)L; (void)b; } ++ ++#endif /* } */ ++ ++#endif /* } */ ++ ++ ++/* ++** Return the string to be used as a prompt by the interpreter. Leave ++** the string (or nil, if using the default value) on the stack, to keep ++** it anchored. ++*/ ++static const char *get_prompt (lua_State *L, int firstline) { ++ if (lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2") == LUA_TNIL) ++ return (firstline ? LUA_PROMPT : LUA_PROMPT2); /* use the default */ ++ else { /* apply 'tostring' over the value */ ++ const char *p = luaL_tolstring(L, -1, NULL); ++ lua_remove(L, -2); /* remove original value */ ++ return p; ++ } ++} ++ ++/* mark in error messages for incomplete statements */ ++#define EOFMARK "" ++#define marklen (sizeof(EOFMARK)/sizeof(char) - 1) ++ ++ ++/* ++** Check whether 'status' signals a syntax error and the error ++** message at the top of the stack ends with the above mark for ++** incomplete statements. ++*/ ++static int incomplete (lua_State *L, int status) { ++ if (status == LUA_ERRSYNTAX) { ++ size_t lmsg; ++ const char *msg = lua_tolstring(L, -1, &lmsg); ++ if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0) { ++ lua_pop(L, 1); ++ return 1; ++ } ++ } ++ return 0; /* else... */ ++} ++ ++ ++/* ++** Prompt the user, read a line, and push it into the Lua stack. ++*/ ++static int pushline (lua_State *L, int firstline) { ++ char buffer[LUA_MAXINPUT]; ++ char *b = buffer; ++ size_t l; ++ const char *prmt = get_prompt(L, firstline); ++ int readstatus = lua_readline(L, b, prmt); ++ if (readstatus == 0) ++ return 0; /* no input (prompt will be popped by caller) */ ++ lua_pop(L, 1); /* remove prompt */ ++ l = strlen(b); ++ if (l > 0 && b[l-1] == '\n') /* line ends with newline? */ ++ b[--l] = '\0'; /* remove it */ ++ if (firstline && b[0] == '=') /* for compatibility with 5.2, ... */ ++ lua_pushfstring(L, "return %s", b + 1); /* change '=' to 'return' */ ++ else ++ lua_pushlstring(L, b, l); ++ lua_freeline(L, b); ++ return 1; ++} ++ ++ ++/* ++** Try to compile line on the stack as 'return ;'; on return, stack ++** has either compiled chunk or original line (if compilation failed). ++*/ ++static int addreturn (lua_State *L) { ++ const char *line = lua_tostring(L, -1); /* original line */ ++ const char *retline = lua_pushfstring(L, "return %s;", line); ++ int status = luaL_loadbuffer(L, retline, strlen(retline), "=stdin"); ++ if (status == LUA_OK) { ++ lua_remove(L, -2); /* remove modified line */ ++ if (line[0] != '\0') /* non empty? */ ++ lua_saveline(L, line); /* keep history */ ++ } ++ else ++ lua_pop(L, 2); /* pop result from 'luaL_loadbuffer' and modified line */ ++ return status; ++} ++ ++ ++/* ++** Read multiple lines until a complete Lua statement ++*/ ++static int multiline (lua_State *L) { ++ for (;;) { /* repeat until gets a complete statement */ ++ size_t len; ++ const char *line = lua_tolstring(L, 1, &len); /* get what it has */ ++ int status = luaL_loadbuffer(L, line, len, "=stdin"); /* try it */ ++ if (!incomplete(L, status) || !pushline(L, 0)) { ++ lua_saveline(L, line); /* keep history */ ++ return status; /* cannot or should not try to add continuation line */ ++ } ++ lua_pushliteral(L, "\n"); /* add newline... */ ++ lua_insert(L, -2); /* ...between the two lines */ ++ lua_concat(L, 3); /* join them */ ++ } ++} ++ ++ ++/* ++** Read a line and try to load (compile) it first as an expression (by ++** adding "return " in front of it) and second as a statement. Return ++** the final status of load/call with the resulting function (if any) ++** in the top of the stack. ++*/ ++static int loadline (lua_State *L) { ++ int status; ++ lua_settop(L, 0); ++ if (!pushline(L, 1)) ++ return -1; /* no input */ ++ if ((status = addreturn(L)) != LUA_OK) /* 'return ...' did not work? */ ++ status = multiline(L); /* try as command, maybe with continuation lines */ ++ lua_remove(L, 1); /* remove line from the stack */ ++ lua_assert(lua_gettop(L) == 1); ++ return status; ++} ++ ++ ++/* ++** Prints (calling the Lua 'print' function) any values on the stack ++*/ ++static void l_print (lua_State *L) { ++ int n = lua_gettop(L); ++ if (n > 0) { /* any result to be printed? */ ++ luaL_checkstack(L, LUA_MINSTACK, "too many results to print"); ++ lua_getglobal(L, "print"); ++ lua_insert(L, 1); ++ if (lua_pcall(L, n, 0, 0) != LUA_OK) ++ l_message(progname, lua_pushfstring(L, "error calling 'print' (%s)", ++ lua_tostring(L, -1))); ++ } ++} ++ ++ ++/* ++** Do the REPL: repeatedly read (load) a line, evaluate (call) it, and ++** print any results. ++*/ ++static void doREPL (lua_State *L) { ++ int status; ++ const char *oldprogname = progname; ++ progname = NULL; /* no 'progname' on errors in interactive mode */ ++ lua_initreadline(L); ++ while ((status = loadline(L)) != -1) { ++ if (status == LUA_OK) ++ status = docall(L, 0, LUA_MULTRET); ++ if (status == LUA_OK) l_print(L); ++ else report(L, status); ++ } ++ lua_settop(L, 0); /* clear stack */ ++ lua_writeline(); ++ progname = oldprogname; ++} ++ ++/* }================================================================== */ ++ ++ ++/* ++** Main body of stand-alone interpreter (to be called in protected mode). ++** Reads the options and handles them all. ++*/ ++static int pmain (lua_State *L) { ++ int argc = (int)lua_tointeger(L, 1); ++ char **argv = (char **)lua_touserdata(L, 2); ++ int script; ++ int args = collectargs(argv, &script); ++ luaL_checkversion(L); /* check that interpreter has correct version */ ++ if (argv[0] && argv[0][0]) progname = argv[0]; ++ if (args == has_error) { /* bad arg? */ ++ print_usage(argv[script]); /* 'script' has index of bad arg. */ ++ return 0; ++ } ++ if (args & has_v) /* option '-v'? */ ++ print_version(); ++ if (args & has_E) { /* option '-E'? */ ++ lua_pushboolean(L, 1); /* signal for libraries to ignore env. vars. */ ++ lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); ++ } ++ luaL_openlibs(L); /* open standard libraries */ ++ createargtable(L, argv, argc, script); /* create table 'arg' */ ++ lua_gc(L, LUA_GCGEN, 0, 0); /* GC in generational mode */ ++ if (!(args & has_E)) { /* no option '-E'? */ ++ if (handle_luainit(L) != LUA_OK) /* run LUA_INIT */ ++ return 0; /* error running LUA_INIT */ ++ } ++ if (!runargs(L, argv, script)) /* execute arguments -e and -l */ ++ return 0; /* something failed */ ++ if (script < argc && /* execute main script (if there is one) */ ++ handle_script(L, argv + script) != LUA_OK) ++ return 0; ++ if (args & has_i) /* -i option? */ ++ doREPL(L); /* do read-eval-print loop */ ++ else if (script == argc && !(args & (has_e | has_v))) { /* no arguments? */ ++ if (lua_stdin_is_tty()) { /* running in interactive mode? */ ++ print_version(); ++ doREPL(L); /* do read-eval-print loop */ ++ } ++ else dofile(L, NULL); /* executes stdin as a file */ ++ } ++ lua_pushboolean(L, 1); /* signal no errors */ ++ return 1; ++} ++ ++ ++int main (int argc, char **argv) { ++ int status, result; ++ lua_State *L = luaL_newstate(); /* create state */ ++ if (L == NULL) { ++ l_message(argv[0], "cannot create state: not enough memory"); ++ return EXIT_FAILURE; ++ } ++ lua_pushcfunction(L, &pmain); /* to call 'pmain' in protected mode */ ++ lua_pushinteger(L, argc); /* 1st argument */ ++ lua_pushlightuserdata(L, argv); /* 2nd argument */ ++ status = lua_pcall(L, 2, 1, 0); /* do the call */ ++ result = lua_toboolean(L, -1); /* get result */ ++ report(L, status); ++ lua_close(L); ++ return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE; ++} ++ +diff --git a/src/bin/lua/lua.h b/src/bin/lua/lua.h +new file mode 100644 +index 0000000000..820535b948 +--- /dev/null ++++ b/src/bin/lua/lua.h +@@ -0,0 +1,518 @@ ++/* ++** $Id: lua.h $ ++** Lua - A Scripting Language ++** Lua.org, PUC-Rio, Brazil (http://www.lua.org) ++** See Copyright Notice at the end of this file ++*/ ++ ++ ++#ifndef lua_h ++#define lua_h ++ ++#include ++#include ++ ++ ++#include "luaconf.h" ++ ++ ++#define LUA_VERSION_MAJOR "5" ++#define LUA_VERSION_MINOR "4" ++#define LUA_VERSION_RELEASE "3" ++ ++#define LUA_VERSION_NUM 504 ++#define LUA_VERSION_RELEASE_NUM (LUA_VERSION_NUM * 100 + 0) ++ ++#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR ++#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE ++#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2021 Lua.org, PUC-Rio" ++#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes" ++ ++ ++/* mark for precompiled code ('Lua') */ ++#define LUA_SIGNATURE "\x1bLua" ++ ++/* option for multiple returns in 'lua_pcall' and 'lua_call' */ ++#define LUA_MULTRET (-1) ++ ++ ++/* ++** Pseudo-indices ++** (-LUAI_MAXSTACK is the minimum valid index; we keep some free empty ++** space after that to help overflow detection) ++*/ ++#define LUA_REGISTRYINDEX (-LUAI_MAXSTACK - 1000) ++#define lua_upvalueindex(i) (LUA_REGISTRYINDEX - (i)) ++ ++ ++/* thread status */ ++#define LUA_OK 0 ++#define LUA_YIELD 1 ++#define LUA_ERRRUN 2 ++#define LUA_ERRSYNTAX 3 ++#define LUA_ERRMEM 4 ++#define LUA_ERRERR 5 ++ ++ ++typedef struct lua_State lua_State; ++ ++ ++/* ++** basic types ++*/ ++#define LUA_TNONE (-1) ++ ++#define LUA_TNIL 0 ++#define LUA_TBOOLEAN 1 ++#define LUA_TLIGHTUSERDATA 2 ++#define LUA_TNUMBER 3 ++#define LUA_TSTRING 4 ++#define LUA_TTABLE 5 ++#define LUA_TFUNCTION 6 ++#define LUA_TUSERDATA 7 ++#define LUA_TTHREAD 8 ++ ++#define LUA_NUMTYPES 9 ++ ++ ++ ++/* minimum Lua stack available to a C function */ ++#define LUA_MINSTACK 20 ++ ++ ++/* predefined values in the registry */ ++#define LUA_RIDX_MAINTHREAD 1 ++#define LUA_RIDX_GLOBALS 2 ++#define LUA_RIDX_LAST LUA_RIDX_GLOBALS ++ ++ ++/* type of numbers in Lua */ ++typedef LUA_NUMBER lua_Number; ++ ++ ++/* type for integer functions */ ++typedef LUA_INTEGER lua_Integer; ++ ++/* unsigned integer type */ ++typedef LUA_UNSIGNED lua_Unsigned; ++ ++/* type for continuation-function contexts */ ++typedef LUA_KCONTEXT lua_KContext; ++ ++ ++/* ++** Type for C functions registered with Lua ++*/ ++typedef int (*lua_CFunction) (lua_State *L); ++ ++/* ++** Type for continuation functions ++*/ ++typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx); ++ ++ ++/* ++** Type for functions that read/write blocks when loading/dumping Lua chunks ++*/ ++typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz); ++ ++typedef int (*lua_Writer) (lua_State *L, const void *p, size_t sz, void *ud); ++ ++ ++/* ++** Type for memory-allocation functions ++*/ ++typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); ++ ++ ++/* ++** Type for warning functions ++*/ ++typedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont); ++ ++ ++ ++ ++/* ++** generic extra include file ++*/ ++#if defined(LUA_USER_H) ++#include LUA_USER_H ++#endif ++ ++ ++/* ++** RCS ident string ++*/ ++extern const char lua_ident[]; ++ ++ ++/* ++** state manipulation ++*/ ++LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud); ++LUA_API void (lua_close) (lua_State *L); ++LUA_API lua_State *(lua_newthread) (lua_State *L); ++LUA_API int (lua_resetthread) (lua_State *L); ++ ++LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf); ++ ++ ++LUA_API lua_Number (lua_version) (lua_State *L); ++ ++ ++/* ++** basic stack manipulation ++*/ ++LUA_API int (lua_absindex) (lua_State *L, int idx); ++LUA_API int (lua_gettop) (lua_State *L); ++LUA_API void (lua_settop) (lua_State *L, int idx); ++LUA_API void (lua_pushvalue) (lua_State *L, int idx); ++LUA_API void (lua_rotate) (lua_State *L, int idx, int n); ++LUA_API void (lua_copy) (lua_State *L, int fromidx, int toidx); ++LUA_API int (lua_checkstack) (lua_State *L, int n); ++ ++LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n); ++ ++ ++/* ++** access functions (stack -> C) ++*/ ++ ++LUA_API int (lua_isnumber) (lua_State *L, int idx); ++LUA_API int (lua_isstring) (lua_State *L, int idx); ++LUA_API int (lua_iscfunction) (lua_State *L, int idx); ++LUA_API int (lua_isinteger) (lua_State *L, int idx); ++LUA_API int (lua_isuserdata) (lua_State *L, int idx); ++LUA_API int (lua_type) (lua_State *L, int idx); ++LUA_API const char *(lua_typename) (lua_State *L, int tp); ++ ++LUA_API lua_Number (lua_tonumberx) (lua_State *L, int idx, int *isnum); ++LUA_API lua_Integer (lua_tointegerx) (lua_State *L, int idx, int *isnum); ++LUA_API int (lua_toboolean) (lua_State *L, int idx); ++LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len); ++LUA_API lua_Unsigned (lua_rawlen) (lua_State *L, int idx); ++LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx); ++LUA_API void *(lua_touserdata) (lua_State *L, int idx); ++LUA_API lua_State *(lua_tothread) (lua_State *L, int idx); ++LUA_API const void *(lua_topointer) (lua_State *L, int idx); ++ ++ ++/* ++** Comparison and arithmetic functions ++*/ ++ ++#define LUA_OPADD 0 /* ORDER TM, ORDER OP */ ++#define LUA_OPSUB 1 ++#define LUA_OPMUL 2 ++#define LUA_OPMOD 3 ++#define LUA_OPPOW 4 ++#define LUA_OPDIV 5 ++#define LUA_OPIDIV 6 ++#define LUA_OPBAND 7 ++#define LUA_OPBOR 8 ++#define LUA_OPBXOR 9 ++#define LUA_OPSHL 10 ++#define LUA_OPSHR 11 ++#define LUA_OPUNM 12 ++#define LUA_OPBNOT 13 ++ ++LUA_API void (lua_arith) (lua_State *L, int op); ++ ++#define LUA_OPEQ 0 ++#define LUA_OPLT 1 ++#define LUA_OPLE 2 ++ ++LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2); ++LUA_API int (lua_compare) (lua_State *L, int idx1, int idx2, int op); ++ ++ ++/* ++** push functions (C -> stack) ++*/ ++LUA_API void (lua_pushnil) (lua_State *L); ++LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n); ++LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n); ++LUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t len); ++LUA_API const char *(lua_pushstring) (lua_State *L, const char *s); ++LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt, ++ va_list argp); ++LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...); ++LUA_API void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n); ++LUA_API void (lua_pushboolean) (lua_State *L, int b); ++LUA_API void (lua_pushlightuserdata) (lua_State *L, void *p); ++LUA_API int (lua_pushthread) (lua_State *L); ++ ++ ++/* ++** get functions (Lua -> stack) ++*/ ++LUA_API int (lua_getglobal) (lua_State *L, const char *name); ++LUA_API int (lua_gettable) (lua_State *L, int idx); ++LUA_API int (lua_getfield) (lua_State *L, int idx, const char *k); ++LUA_API int (lua_geti) (lua_State *L, int idx, lua_Integer n); ++LUA_API int (lua_rawget) (lua_State *L, int idx); ++LUA_API int (lua_rawgeti) (lua_State *L, int idx, lua_Integer n); ++LUA_API int (lua_rawgetp) (lua_State *L, int idx, const void *p); ++ ++LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec); ++LUA_API void *(lua_newuserdatauv) (lua_State *L, size_t sz, int nuvalue); ++LUA_API int (lua_getmetatable) (lua_State *L, int objindex); ++LUA_API int (lua_getiuservalue) (lua_State *L, int idx, int n); ++ ++ ++/* ++** set functions (stack -> Lua) ++*/ ++LUA_API void (lua_setglobal) (lua_State *L, const char *name); ++LUA_API void (lua_settable) (lua_State *L, int idx); ++LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k); ++LUA_API void (lua_seti) (lua_State *L, int idx, lua_Integer n); ++LUA_API void (lua_rawset) (lua_State *L, int idx); ++LUA_API void (lua_rawseti) (lua_State *L, int idx, lua_Integer n); ++LUA_API void (lua_rawsetp) (lua_State *L, int idx, const void *p); ++LUA_API int (lua_setmetatable) (lua_State *L, int objindex); ++LUA_API int (lua_setiuservalue) (lua_State *L, int idx, int n); ++ ++ ++/* ++** 'load' and 'call' functions (load and run Lua code) ++*/ ++LUA_API void (lua_callk) (lua_State *L, int nargs, int nresults, ++ lua_KContext ctx, lua_KFunction k); ++#define lua_call(L,n,r) lua_callk(L, (n), (r), 0, NULL) ++ ++LUA_API int (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc, ++ lua_KContext ctx, lua_KFunction k); ++#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL) ++ ++LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt, ++ const char *chunkname, const char *mode); ++ ++LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data, int strip); ++ ++ ++/* ++** coroutine functions ++*/ ++LUA_API int (lua_yieldk) (lua_State *L, int nresults, lua_KContext ctx, ++ lua_KFunction k); ++LUA_API int (lua_resume) (lua_State *L, lua_State *from, int narg, ++ int *nres); ++LUA_API int (lua_status) (lua_State *L); ++LUA_API int (lua_isyieldable) (lua_State *L); ++ ++#define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL) ++ ++ ++/* ++** Warning-related functions ++*/ ++LUA_API void (lua_setwarnf) (lua_State *L, lua_WarnFunction f, void *ud); ++LUA_API void (lua_warning) (lua_State *L, const char *msg, int tocont); ++ ++ ++/* ++** garbage-collection function and options ++*/ ++ ++#define LUA_GCSTOP 0 ++#define LUA_GCRESTART 1 ++#define LUA_GCCOLLECT 2 ++#define LUA_GCCOUNT 3 ++#define LUA_GCCOUNTB 4 ++#define LUA_GCSTEP 5 ++#define LUA_GCSETPAUSE 6 ++#define LUA_GCSETSTEPMUL 7 ++#define LUA_GCISRUNNING 9 ++#define LUA_GCGEN 10 ++#define LUA_GCINC 11 ++ ++LUA_API int (lua_gc) (lua_State *L, int what, ...); ++ ++ ++/* ++** miscellaneous functions ++*/ ++ ++LUA_API int (lua_error) (lua_State *L); ++ ++LUA_API int (lua_next) (lua_State *L, int idx); ++ ++LUA_API void (lua_concat) (lua_State *L, int n); ++LUA_API void (lua_len) (lua_State *L, int idx); ++ ++LUA_API size_t (lua_stringtonumber) (lua_State *L, const char *s); ++ ++LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud); ++LUA_API void (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud); ++ ++LUA_API void (lua_toclose) (lua_State *L, int idx); ++LUA_API void (lua_closeslot) (lua_State *L, int idx); ++ ++ ++/* ++** {============================================================== ++** some useful macros ++** =============================================================== ++*/ ++ ++#define lua_getextraspace(L) ((void *)((char *)(L) - LUA_EXTRASPACE)) ++ ++#define lua_tonumber(L,i) lua_tonumberx(L,(i),NULL) ++#define lua_tointeger(L,i) lua_tointegerx(L,(i),NULL) ++ ++#define lua_pop(L,n) lua_settop(L, -(n)-1) ++ ++#define lua_newtable(L) lua_createtable(L, 0, 0) ++ ++#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) ++ ++#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) ++ ++#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) ++#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) ++#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) ++#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) ++#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) ++#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) ++#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE) ++#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0) ++ ++#define lua_pushliteral(L, s) lua_pushstring(L, "" s) ++ ++#define lua_pushglobaltable(L) \ ++ ((void)lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS)) ++ ++#define lua_tostring(L,i) lua_tolstring(L, (i), NULL) ++ ++ ++#define lua_insert(L,idx) lua_rotate(L, (idx), 1) ++ ++#define lua_remove(L,idx) (lua_rotate(L, (idx), -1), lua_pop(L, 1)) ++ ++#define lua_replace(L,idx) (lua_copy(L, -1, (idx)), lua_pop(L, 1)) ++ ++/* }============================================================== */ ++ ++ ++/* ++** {============================================================== ++** compatibility macros ++** =============================================================== ++*/ ++#if defined(LUA_COMPAT_APIINTCASTS) ++ ++#define lua_pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n)) ++#define lua_tounsignedx(L,i,is) ((lua_Unsigned)lua_tointegerx(L,i,is)) ++#define lua_tounsigned(L,i) lua_tounsignedx(L,(i),NULL) ++ ++#endif ++ ++#define lua_newuserdata(L,s) lua_newuserdatauv(L,s,1) ++#define lua_getuservalue(L,idx) lua_getiuservalue(L,idx,1) ++#define lua_setuservalue(L,idx) lua_setiuservalue(L,idx,1) ++ ++#define LUA_NUMTAGS LUA_NUMTYPES ++ ++/* }============================================================== */ ++ ++/* ++** {====================================================================== ++** Debug API ++** ======================================================================= ++*/ ++ ++ ++/* ++** Event codes ++*/ ++#define LUA_HOOKCALL 0 ++#define LUA_HOOKRET 1 ++#define LUA_HOOKLINE 2 ++#define LUA_HOOKCOUNT 3 ++#define LUA_HOOKTAILCALL 4 ++ ++ ++/* ++** Event masks ++*/ ++#define LUA_MASKCALL (1 << LUA_HOOKCALL) ++#define LUA_MASKRET (1 << LUA_HOOKRET) ++#define LUA_MASKLINE (1 << LUA_HOOKLINE) ++#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) ++ ++typedef struct lua_Debug lua_Debug; /* activation record */ ++ ++ ++/* Functions to be called by the debugger in specific events */ ++typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); ++ ++ ++LUA_API int (lua_getstack) (lua_State *L, int level, lua_Debug *ar); ++LUA_API int (lua_getinfo) (lua_State *L, const char *what, lua_Debug *ar); ++LUA_API const char *(lua_getlocal) (lua_State *L, const lua_Debug *ar, int n); ++LUA_API const char *(lua_setlocal) (lua_State *L, const lua_Debug *ar, int n); ++LUA_API const char *(lua_getupvalue) (lua_State *L, int funcindex, int n); ++LUA_API const char *(lua_setupvalue) (lua_State *L, int funcindex, int n); ++ ++LUA_API void *(lua_upvalueid) (lua_State *L, int fidx, int n); ++LUA_API void (lua_upvaluejoin) (lua_State *L, int fidx1, int n1, ++ int fidx2, int n2); ++ ++LUA_API void (lua_sethook) (lua_State *L, lua_Hook func, int mask, int count); ++LUA_API lua_Hook (lua_gethook) (lua_State *L); ++LUA_API int (lua_gethookmask) (lua_State *L); ++LUA_API int (lua_gethookcount) (lua_State *L); ++ ++LUA_API int (lua_setcstacklimit) (lua_State *L, unsigned int limit); ++ ++struct lua_Debug { ++ int event; ++ const char *name; /* (n) */ ++ const char *namewhat; /* (n) 'global', 'local', 'field', 'method' */ ++ const char *what; /* (S) 'Lua', 'C', 'main', 'tail' */ ++ const char *source; /* (S) */ ++ size_t srclen; /* (S) */ ++ int currentline; /* (l) */ ++ int linedefined; /* (S) */ ++ int lastlinedefined; /* (S) */ ++ unsigned char nups; /* (u) number of upvalues */ ++ unsigned char nparams;/* (u) number of parameters */ ++ char isvararg; /* (u) */ ++ char istailcall; /* (t) */ ++ unsigned short ftransfer; /* (r) index of first value transferred */ ++ unsigned short ntransfer; /* (r) number of transferred values */ ++ char short_src[LUA_IDSIZE]; /* (S) */ ++ /* private part */ ++ struct CallInfo *i_ci; /* active function */ ++}; ++ ++/* }====================================================================== */ ++ ++ ++/****************************************************************************** ++* Copyright (C) 1994-2021 Lua.org, PUC-Rio. ++* ++* Permission is hereby granted, free of charge, to any person obtaining ++* a copy of this software and associated documentation files (the ++* "Software"), to deal in the Software without restriction, including ++* without limitation the rights to use, copy, modify, merge, publish, ++* distribute, sublicense, and/or sell copies of the Software, and to ++* permit persons to whom the Software is furnished to do so, subject to ++* the following conditions: ++* ++* The above copyright notice and this permission notice shall be ++* included in all copies or substantial portions of the Software. ++* ++* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ++* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ++* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ++* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY ++* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ++* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE ++* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ++******************************************************************************/ ++ ++ ++#endif +diff --git a/src/bin/lua/lua.hpp b/src/bin/lua/lua.hpp +new file mode 100644 +index 0000000000..ec417f5946 +--- /dev/null ++++ b/src/bin/lua/lua.hpp +@@ -0,0 +1,9 @@ ++// lua.hpp ++// Lua header files for C++ ++// <> not supplied automatically because Lua also compiles as C++ ++ ++extern "C" { ++#include "lua.h" ++#include "lualib.h" ++#include "lauxlib.h" ++} +diff --git a/src/bin/lua/luac.c b/src/bin/lua/luac.c +new file mode 100644 +index 0000000000..56ddc41483 +--- /dev/null ++++ b/src/bin/lua/luac.c +@@ -0,0 +1,724 @@ ++/* ++** $Id: luac.c $ ++** Lua compiler (saves bytecodes to files; also lists bytecodes) ++** See Copyright Notice in lua.h ++*/ ++ ++#define luac_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++#include ++#include ++#include ++#include ++#include ++ ++#include "lua.h" ++#include "lauxlib.h" ++ ++#include "ldebug.h" ++#include "lobject.h" ++#include "lopcodes.h" ++#include "lopnames.h" ++#include "lstate.h" ++#include "lundump.h" ++ ++static void PrintFunction(const Proto* f, int full); ++#define luaU_print PrintFunction ++ ++#define PROGNAME "luac" /* default program name */ ++#define OUTPUT PROGNAME ".out" /* default output file */ ++ ++static int listing=0; /* list bytecodes? */ ++static int dumping=1; /* dump bytecodes? */ ++static int stripping=0; /* strip debug information? */ ++static char Output[]={ OUTPUT }; /* default output file name */ ++static const char* output=Output; /* actual output file name */ ++static const char* progname=PROGNAME; /* actual program name */ ++static TString **tmname; ++ ++static void fatal(const char* message) ++{ ++ fprintf(stderr,"%s: %s\n",progname,message); ++ exit(EXIT_FAILURE); ++} ++ ++static void cannot(const char* what) ++{ ++ fprintf(stderr,"%s: cannot %s %s: %s\n",progname,what,output,strerror(errno)); ++ exit(EXIT_FAILURE); ++} ++ ++static void usage(const char* message) ++{ ++ if (*message=='-') ++ fprintf(stderr,"%s: unrecognized option '%s'\n",progname,message); ++ else ++ fprintf(stderr,"%s: %s\n",progname,message); ++ fprintf(stderr, ++ "usage: %s [options] [filenames]\n" ++ "Available options are:\n" ++ " -l list (use -l -l for full listing)\n" ++ " -o name output to file 'name' (default is \"%s\")\n" ++ " -p parse only\n" ++ " -s strip debug information\n" ++ " -v show version information\n" ++ " -- stop handling options\n" ++ " - stop handling options and process stdin\n" ++ ,progname,Output); ++ exit(EXIT_FAILURE); ++} ++ ++#define IS(s) (strcmp(argv[i],s)==0) ++ ++static int doargs(int argc, char* argv[]) ++{ ++ int i; ++ int version=0; ++ if (argv[0]!=NULL && *argv[0]!=0) progname=argv[0]; ++ for (i=1; itop+(i))) ++ ++static const Proto* combine(lua_State* L, int n) ++{ ++ if (n==1) ++ return toproto(L,-1); ++ else ++ { ++ Proto* f; ++ int i=n; ++ if (lua_load(L,reader,&i,"=(" PROGNAME ")",NULL)!=LUA_OK) fatal(lua_tostring(L,-1)); ++ f=toproto(L,-1); ++ for (i=0; ip[i]=toproto(L,i-n-1); ++ if (f->p[i]->sizeupvalues>0) f->p[i]->upvalues[0].instack=0; ++ } ++ f->sizelineinfo=0; ++ return f; ++ } ++} ++ ++static int writer(lua_State* L, const void* p, size_t size, void* u) ++{ ++ UNUSED(L); ++ return (fwrite(p,size,1,(FILE*)u)!=1) && (size!=0); ++} ++ ++static int pmain(lua_State* L) ++{ ++ int argc=(int)lua_tointeger(L,1); ++ char** argv=(char**)lua_touserdata(L,2); ++ const Proto* f; ++ int i; ++ tmname=G(L)->tmname; ++ if (!lua_checkstack(L,argc)) fatal("too many input files"); ++ for (i=0; i1); ++ if (dumping) ++ { ++ FILE* D= (output==NULL) ? stdout : fopen(output,"wb"); ++ if (D==NULL) cannot("open"); ++ lua_lock(L); ++ luaU_dump(L,f,writer,D,stripping); ++ lua_unlock(L); ++ if (ferror(D)) cannot("write"); ++ if (fclose(D)) cannot("close"); ++ } ++ return 0; ++} ++ ++int main(int argc, char* argv[]) ++{ ++ lua_State* L; ++ int i=doargs(argc,argv); ++ argc-=i; argv+=i; ++ if (argc<=0) usage("no input files given"); ++ L=luaL_newstate(); ++ if (L==NULL) fatal("cannot create state: not enough memory"); ++ lua_pushcfunction(L,&pmain); ++ lua_pushinteger(L,argc); ++ lua_pushlightuserdata(L,argv); ++ if (lua_pcall(L,2,0,0)!=LUA_OK) fatal(lua_tostring(L,-1)); ++ lua_close(L); ++ return EXIT_SUCCESS; ++} ++ ++/* ++** print bytecodes ++*/ ++ ++#define UPVALNAME(x) ((f->upvalues[x].name) ? getstr(f->upvalues[x].name) : "-") ++#define VOID(p) ((const void*)(p)) ++#define eventname(i) (getstr(tmname[i])) ++ ++static void PrintString(const TString* ts) ++{ ++ const char* s=getstr(ts); ++ size_t i,n=tsslen(ts); ++ printf("\""); ++ for (i=0; ik[i]; ++ switch (ttypetag(o)) ++ { ++ case LUA_VNIL: ++ printf("N"); ++ break; ++ case LUA_VFALSE: ++ case LUA_VTRUE: ++ printf("B"); ++ break; ++ case LUA_VNUMFLT: ++ printf("F"); ++ break; ++ case LUA_VNUMINT: ++ printf("I"); ++ break; ++ case LUA_VSHRSTR: ++ case LUA_VLNGSTR: ++ printf("S"); ++ break; ++ default: /* cannot happen */ ++ printf("?%d",ttypetag(o)); ++ break; ++ } ++ printf("\t"); ++} ++ ++static void PrintConstant(const Proto* f, int i) ++{ ++ const TValue* o=&f->k[i]; ++ switch (ttypetag(o)) ++ { ++ case LUA_VNIL: ++ printf("nil"); ++ break; ++ case LUA_VFALSE: ++ printf("false"); ++ break; ++ case LUA_VTRUE: ++ printf("true"); ++ break; ++ case LUA_VNUMFLT: ++ { ++ char buff[100]; ++ sprintf(buff,LUA_NUMBER_FMT,fltvalue(o)); ++ printf("%s",buff); ++ if (buff[strspn(buff,"-0123456789")]=='\0') printf(".0"); ++ break; ++ } ++ case LUA_VNUMINT: ++ printf(LUA_INTEGER_FMT,ivalue(o)); ++ break; ++ case LUA_VSHRSTR: ++ case LUA_VLNGSTR: ++ PrintString(tsvalue(o)); ++ break; ++ default: /* cannot happen */ ++ printf("?%d",ttypetag(o)); ++ break; ++ } ++} ++ ++#define COMMENT "\t; " ++#define EXTRAARG GETARG_Ax(code[pc+1]) ++#define EXTRAARGC (EXTRAARG*(MAXARG_C+1)) ++#define ISK (isk ? "k" : "") ++ ++static void PrintCode(const Proto* f) ++{ ++ const Instruction* code=f->code; ++ int pc,n=f->sizecode; ++ for (pc=0; pc0) printf("[%d]\t",line); else printf("[-]\t"); ++ printf("%-9s\t",opnames[o]); ++ switch (o) ++ { ++ case OP_MOVE: ++ printf("%d %d",a,b); ++ break; ++ case OP_LOADI: ++ printf("%d %d",a,sbx); ++ break; ++ case OP_LOADF: ++ printf("%d %d",a,sbx); ++ break; ++ case OP_LOADK: ++ printf("%d %d",a,bx); ++ printf(COMMENT); PrintConstant(f,bx); ++ break; ++ case OP_LOADKX: ++ printf("%d",a); ++ printf(COMMENT); PrintConstant(f,EXTRAARG); ++ break; ++ case OP_LOADFALSE: ++ printf("%d",a); ++ break; ++ case OP_LFALSESKIP: ++ printf("%d",a); ++ break; ++ case OP_LOADTRUE: ++ printf("%d",a); ++ break; ++ case OP_LOADNIL: ++ printf("%d %d",a,b); ++ printf(COMMENT "%d out",b+1); ++ break; ++ case OP_GETUPVAL: ++ printf("%d %d",a,b); ++ printf(COMMENT "%s",UPVALNAME(b)); ++ break; ++ case OP_SETUPVAL: ++ printf("%d %d",a,b); ++ printf(COMMENT "%s",UPVALNAME(b)); ++ break; ++ case OP_GETTABUP: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT "%s",UPVALNAME(b)); ++ printf(" "); PrintConstant(f,c); ++ break; ++ case OP_GETTABLE: ++ printf("%d %d %d",a,b,c); ++ break; ++ case OP_GETI: ++ printf("%d %d %d",a,b,c); ++ break; ++ case OP_GETFIELD: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT); PrintConstant(f,c); ++ break; ++ case OP_SETTABUP: ++ printf("%d %d %d%s",a,b,c,ISK); ++ printf(COMMENT "%s",UPVALNAME(a)); ++ printf(" "); PrintConstant(f,b); ++ if (isk) { printf(" "); PrintConstant(f,c); } ++ break; ++ case OP_SETTABLE: ++ printf("%d %d %d%s",a,b,c,ISK); ++ if (isk) { printf(COMMENT); PrintConstant(f,c); } ++ break; ++ case OP_SETI: ++ printf("%d %d %d%s",a,b,c,ISK); ++ if (isk) { printf(COMMENT); PrintConstant(f,c); } ++ break; ++ case OP_SETFIELD: ++ printf("%d %d %d%s",a,b,c,ISK); ++ printf(COMMENT); PrintConstant(f,b); ++ if (isk) { printf(" "); PrintConstant(f,c); } ++ break; ++ case OP_NEWTABLE: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT "%d",c+EXTRAARGC); ++ break; ++ case OP_SELF: ++ printf("%d %d %d%s",a,b,c,ISK); ++ if (isk) { printf(COMMENT); PrintConstant(f,c); } ++ break; ++ case OP_ADDI: ++ printf("%d %d %d",a,b,sc); ++ break; ++ case OP_ADDK: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT); PrintConstant(f,c); ++ break; ++ case OP_SUBK: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT); PrintConstant(f,c); ++ break; ++ case OP_MULK: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT); PrintConstant(f,c); ++ break; ++ case OP_MODK: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT); PrintConstant(f,c); ++ break; ++ case OP_POWK: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT); PrintConstant(f,c); ++ break; ++ case OP_DIVK: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT); PrintConstant(f,c); ++ break; ++ case OP_IDIVK: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT); PrintConstant(f,c); ++ break; ++ case OP_BANDK: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT); PrintConstant(f,c); ++ break; ++ case OP_BORK: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT); PrintConstant(f,c); ++ break; ++ case OP_BXORK: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT); PrintConstant(f,c); ++ break; ++ case OP_SHRI: ++ printf("%d %d %d",a,b,sc); ++ break; ++ case OP_SHLI: ++ printf("%d %d %d",a,b,sc); ++ break; ++ case OP_ADD: ++ printf("%d %d %d",a,b,c); ++ break; ++ case OP_SUB: ++ printf("%d %d %d",a,b,c); ++ break; ++ case OP_MUL: ++ printf("%d %d %d",a,b,c); ++ break; ++ case OP_MOD: ++ printf("%d %d %d",a,b,c); ++ break; ++ case OP_POW: ++ printf("%d %d %d",a,b,c); ++ break; ++ case OP_DIV: ++ printf("%d %d %d",a,b,c); ++ break; ++ case OP_IDIV: ++ printf("%d %d %d",a,b,c); ++ break; ++ case OP_BAND: ++ printf("%d %d %d",a,b,c); ++ break; ++ case OP_BOR: ++ printf("%d %d %d",a,b,c); ++ break; ++ case OP_BXOR: ++ printf("%d %d %d",a,b,c); ++ break; ++ case OP_SHL: ++ printf("%d %d %d",a,b,c); ++ break; ++ case OP_SHR: ++ printf("%d %d %d",a,b,c); ++ break; ++ case OP_MMBIN: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT "%s",eventname(c)); ++ break; ++ case OP_MMBINI: ++ printf("%d %d %d %d",a,sb,c,isk); ++ printf(COMMENT "%s",eventname(c)); ++ if (isk) printf(" flip"); ++ break; ++ case OP_MMBINK: ++ printf("%d %d %d %d",a,b,c,isk); ++ printf(COMMENT "%s ",eventname(c)); PrintConstant(f,b); ++ if (isk) printf(" flip"); ++ break; ++ case OP_UNM: ++ printf("%d %d",a,b); ++ break; ++ case OP_BNOT: ++ printf("%d %d",a,b); ++ break; ++ case OP_NOT: ++ printf("%d %d",a,b); ++ break; ++ case OP_LEN: ++ printf("%d %d",a,b); ++ break; ++ case OP_CONCAT: ++ printf("%d %d",a,b); ++ break; ++ case OP_CLOSE: ++ printf("%d",a); ++ break; ++ case OP_TBC: ++ printf("%d",a); ++ break; ++ case OP_JMP: ++ printf("%d",GETARG_sJ(i)); ++ printf(COMMENT "to %d",GETARG_sJ(i)+pc+2); ++ break; ++ case OP_EQ: ++ printf("%d %d %d",a,b,isk); ++ break; ++ case OP_LT: ++ printf("%d %d %d",a,b,isk); ++ break; ++ case OP_LE: ++ printf("%d %d %d",a,b,isk); ++ break; ++ case OP_EQK: ++ printf("%d %d %d",a,b,isk); ++ printf(COMMENT); PrintConstant(f,b); ++ break; ++ case OP_EQI: ++ printf("%d %d %d",a,sb,isk); ++ break; ++ case OP_LTI: ++ printf("%d %d %d",a,sb,isk); ++ break; ++ case OP_LEI: ++ printf("%d %d %d",a,sb,isk); ++ break; ++ case OP_GTI: ++ printf("%d %d %d",a,sb,isk); ++ break; ++ case OP_GEI: ++ printf("%d %d %d",a,sb,isk); ++ break; ++ case OP_TEST: ++ printf("%d %d",a,isk); ++ break; ++ case OP_TESTSET: ++ printf("%d %d %d",a,b,isk); ++ break; ++ case OP_CALL: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT); ++ if (b==0) printf("all in "); else printf("%d in ",b-1); ++ if (c==0) printf("all out"); else printf("%d out",c-1); ++ break; ++ case OP_TAILCALL: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT "%d in",b-1); ++ break; ++ case OP_RETURN: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT); ++ if (b==0) printf("all out"); else printf("%d out",b-1); ++ break; ++ case OP_RETURN0: ++ break; ++ case OP_RETURN1: ++ printf("%d",a); ++ break; ++ case OP_FORLOOP: ++ printf("%d %d",a,bx); ++ printf(COMMENT "to %d",pc-bx+2); ++ break; ++ case OP_FORPREP: ++ printf("%d %d",a,bx); ++ printf(COMMENT "to %d",pc+bx+2); ++ break; ++ case OP_TFORPREP: ++ printf("%d %d",a,bx); ++ printf(COMMENT "to %d",pc+bx+2); ++ break; ++ case OP_TFORCALL: ++ printf("%d %d",a,c); ++ break; ++ case OP_TFORLOOP: ++ printf("%d %d",a,bx); ++ printf(COMMENT "to %d",pc-bx+2); ++ break; ++ case OP_SETLIST: ++ printf("%d %d %d",a,b,c); ++ if (isk) printf(COMMENT "%d",c+EXTRAARGC); ++ break; ++ case OP_CLOSURE: ++ printf("%d %d",a,bx); ++ printf(COMMENT "%p",VOID(f->p[bx])); ++ break; ++ case OP_VARARG: ++ printf("%d %d",a,c); ++ printf(COMMENT); ++ if (c==0) printf("all out"); else printf("%d out",c-1); ++ break; ++ case OP_VARARGPREP: ++ printf("%d",a); ++ break; ++ case OP_EXTRAARG: ++ printf("%d",ax); ++ break; ++#if 0 ++ default: ++ printf("%d %d %d",a,b,c); ++ printf(COMMENT "not handled"); ++ break; ++#endif ++ } ++ printf("\n"); ++ } ++} ++ ++ ++#define SS(x) ((x==1)?"":"s") ++#define S(x) (int)(x),SS(x) ++ ++static void PrintHeader(const Proto* f) ++{ ++ const char* s=f->source ? getstr(f->source) : "=?"; ++ if (*s=='@' || *s=='=') ++ s++; ++ else if (*s==LUA_SIGNATURE[0]) ++ s="(bstring)"; ++ else ++ s="(string)"; ++ printf("\n%s <%s:%d,%d> (%d instruction%s at %p)\n", ++ (f->linedefined==0)?"main":"function",s, ++ f->linedefined,f->lastlinedefined, ++ S(f->sizecode),VOID(f)); ++ printf("%d%s param%s, %d slot%s, %d upvalue%s, ", ++ (int)(f->numparams),f->is_vararg?"+":"",SS(f->numparams), ++ S(f->maxstacksize),S(f->sizeupvalues)); ++ printf("%d local%s, %d constant%s, %d function%s\n", ++ S(f->sizelocvars),S(f->sizek),S(f->sizep)); ++} ++ ++static void PrintDebug(const Proto* f) ++{ ++ int i,n; ++ n=f->sizek; ++ printf("constants (%d) for %p:\n",n,VOID(f)); ++ for (i=0; isizelocvars; ++ printf("locals (%d) for %p:\n",n,VOID(f)); ++ for (i=0; ilocvars[i].varname),f->locvars[i].startpc+1,f->locvars[i].endpc+1); ++ } ++ n=f->sizeupvalues; ++ printf("upvalues (%d) for %p:\n",n,VOID(f)); ++ for (i=0; iupvalues[i].instack,f->upvalues[i].idx); ++ } ++} ++ ++static void PrintFunction(const Proto* f, int full) ++{ ++ int i,n=f->sizep; ++ PrintHeader(f); ++ PrintCode(f); ++ if (full) PrintDebug(f); ++ for (i=0; ip[i],full); ++} +diff --git a/src/bin/lua/luaconf.h b/src/bin/lua/luaconf.h +new file mode 100644 +index 0000000000..e64d2ee392 +--- /dev/null ++++ b/src/bin/lua/luaconf.h +@@ -0,0 +1,790 @@ ++/* ++** $Id: luaconf.h $ ++** Configuration file for Lua ++** See Copyright Notice in lua.h ++*/ ++ ++ ++#ifndef luaconf_h ++#define luaconf_h ++ ++#include ++#include ++ ++ ++/* ++** =================================================================== ++** General Configuration File for Lua ++** ++** Some definitions here can be changed externally, through the compiler ++** (e.g., with '-D' options): They are commented out or protected ++** by '#if !defined' guards. However, several other definitions ++** should be changed directly here, either because they affect the ++** Lua ABI (by making the changes here, you ensure that all software ++** connected to Lua, such as C libraries, will be compiled with the same ++** configuration); or because they are seldom changed. ++** ++** Search for "@@" to find all configurable definitions. ++** =================================================================== ++*/ ++ ++ ++/* ++** {==================================================================== ++** System Configuration: macros to adapt (if needed) Lua to some ++** particular platform, for instance restricting it to C89. ++** ===================================================================== ++*/ ++ ++/* ++@@ LUA_USE_C89 controls the use of non-ISO-C89 features. ++** Define it if you want Lua to avoid the use of a few C99 features ++** or Windows-specific features on Windows. ++*/ ++/* #define LUA_USE_C89 */ ++ ++ ++/* ++** By default, Lua on Windows use (some) specific Windows features ++*/ ++#if !defined(LUA_USE_C89) && defined(_WIN32) && !defined(_WIN32_WCE) ++#define LUA_USE_WINDOWS /* enable goodies for regular Windows */ ++#endif ++ ++ ++#if defined(LUA_USE_WINDOWS) ++#define LUA_DL_DLL /* enable support for DLL */ ++#define LUA_USE_C89 /* broadly, Windows is C89 */ ++#endif ++ ++ ++#if defined(LUA_USE_LINUX) ++#define LUA_USE_POSIX ++#define LUA_USE_DLOPEN /* needs an extra library: -ldl */ ++#endif ++ ++ ++#if defined(LUA_USE_MACOSX) ++#define LUA_USE_POSIX ++#define LUA_USE_DLOPEN /* MacOS does not need -ldl */ ++#endif ++ ++ ++/* ++@@ LUAI_IS32INT is true iff 'int' has (at least) 32 bits. ++*/ ++#define LUAI_IS32INT ((UINT_MAX >> 30) >= 3) ++ ++/* }================================================================== */ ++ ++ ++ ++/* ++** {================================================================== ++** Configuration for Number types. These options should not be ++** set externally, because any other code connected to Lua must ++** use the same configuration. ++** =================================================================== ++*/ ++ ++/* ++@@ LUA_INT_TYPE defines the type for Lua integers. ++@@ LUA_FLOAT_TYPE defines the type for Lua floats. ++** Lua should work fine with any mix of these options supported ++** by your C compiler. The usual configurations are 64-bit integers ++** and 'double' (the default), 32-bit integers and 'float' (for ++** restricted platforms), and 'long'/'double' (for C compilers not ++** compliant with C99, which may not have support for 'long long'). ++*/ ++ ++/* predefined options for LUA_INT_TYPE */ ++#define LUA_INT_INT 1 ++#define LUA_INT_LONG 2 ++#define LUA_INT_LONGLONG 3 ++ ++/* predefined options for LUA_FLOAT_TYPE */ ++#define LUA_FLOAT_FLOAT 1 ++#define LUA_FLOAT_DOUBLE 2 ++#define LUA_FLOAT_LONGDOUBLE 3 ++ ++ ++/* Default configuration ('long long' and 'double', for 64-bit Lua) */ ++#define LUA_INT_DEFAULT LUA_INT_LONGLONG ++#define LUA_FLOAT_DEFAULT LUA_FLOAT_DOUBLE ++ ++ ++/* ++@@ LUA_32BITS enables Lua with 32-bit integers and 32-bit floats. ++*/ ++#define LUA_32BITS 0 ++ ++ ++/* ++@@ LUA_C89_NUMBERS ensures that Lua uses the largest types available for ++** C89 ('long' and 'double'); Windows always has '__int64', so it does ++** not need to use this case. ++*/ ++#if defined(LUA_USE_C89) && !defined(LUA_USE_WINDOWS) ++#define LUA_C89_NUMBERS 1 ++#else ++#define LUA_C89_NUMBERS 0 ++#endif ++ ++ ++#if LUA_32BITS /* { */ ++/* ++** 32-bit integers and 'float' ++*/ ++#if LUAI_IS32INT /* use 'int' if big enough */ ++#define LUA_INT_TYPE LUA_INT_INT ++#else /* otherwise use 'long' */ ++#define LUA_INT_TYPE LUA_INT_LONG ++#endif ++#define LUA_FLOAT_TYPE LUA_FLOAT_FLOAT ++ ++#elif LUA_C89_NUMBERS /* }{ */ ++/* ++** largest types available for C89 ('long' and 'double') ++*/ ++#define LUA_INT_TYPE LUA_INT_LONG ++#define LUA_FLOAT_TYPE LUA_FLOAT_DOUBLE ++ ++#else /* }{ */ ++/* use defaults */ ++ ++#define LUA_INT_TYPE LUA_INT_DEFAULT ++#define LUA_FLOAT_TYPE LUA_FLOAT_DEFAULT ++ ++#endif /* } */ ++ ++ ++/* }================================================================== */ ++ ++ ++ ++/* ++** {================================================================== ++** Configuration for Paths. ++** =================================================================== ++*/ ++ ++/* ++** LUA_PATH_SEP is the character that separates templates in a path. ++** LUA_PATH_MARK is the string that marks the substitution points in a ++** template. ++** LUA_EXEC_DIR in a Windows path is replaced by the executable's ++** directory. ++*/ ++#define LUA_PATH_SEP ";" ++#define LUA_PATH_MARK "?" ++#define LUA_EXEC_DIR "!" ++ ++ ++/* ++@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for ++** Lua libraries. ++@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for ++** C libraries. ++** CHANGE them if your machine has a non-conventional directory ++** hierarchy or if you want to install your libraries in ++** non-conventional directories. ++*/ ++ ++#define LUA_VDIR LUA_VERSION_MAJOR "." LUA_VERSION_MINOR ++#if defined(_WIN32) /* { */ ++/* ++** In Windows, any exclamation mark ('!') in the path is replaced by the ++** path of the directory of the executable file of the current process. ++*/ ++#define LUA_LDIR "!\\lua\\" ++#define LUA_CDIR "!\\" ++#define LUA_SHRDIR "!\\..\\share\\lua\\" LUA_VDIR "\\" ++ ++#if !defined(LUA_PATH_DEFAULT) ++#define LUA_PATH_DEFAULT \ ++ LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \ ++ LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" \ ++ LUA_SHRDIR"?.lua;" LUA_SHRDIR"?\\init.lua;" \ ++ ".\\?.lua;" ".\\?\\init.lua" ++#endif ++ ++#if !defined(LUA_CPATH_DEFAULT) ++#define LUA_CPATH_DEFAULT \ ++ LUA_CDIR"?.dll;" \ ++ LUA_CDIR"..\\lib\\lua\\" LUA_VDIR "\\?.dll;" \ ++ LUA_CDIR"loadall.dll;" ".\\?.dll" ++#endif ++ ++#else /* }{ */ ++ ++#define LUA_ROOT "/usr/local/" ++#define LUA_LDIR LUA_ROOT "share/lua/" LUA_VDIR "/" ++#define LUA_CDIR LUA_ROOT "lib/lua/" LUA_VDIR "/" ++ ++#if !defined(LUA_PATH_DEFAULT) ++#define LUA_PATH_DEFAULT \ ++ LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ ++ LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" \ ++ "./?.lua;" "./?/init.lua" ++#endif ++ ++#if !defined(LUA_CPATH_DEFAULT) ++#define LUA_CPATH_DEFAULT \ ++ LUA_CDIR"?.so;" LUA_CDIR"loadall.so;" "./?.so" ++#endif ++ ++#endif /* } */ ++ ++ ++/* ++@@ LUA_DIRSEP is the directory separator (for submodules). ++** CHANGE it if your machine does not use "/" as the directory separator ++** and is not Windows. (On Windows Lua automatically uses "\".) ++*/ ++#if !defined(LUA_DIRSEP) ++ ++#if defined(_WIN32) ++#define LUA_DIRSEP "\\" ++#else ++#define LUA_DIRSEP "/" ++#endif ++ ++#endif ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Marks for exported symbols in the C code ++** =================================================================== ++*/ ++ ++/* ++@@ LUA_API is a mark for all core API functions. ++@@ LUALIB_API is a mark for all auxiliary library functions. ++@@ LUAMOD_API is a mark for all standard library opening functions. ++** CHANGE them if you need to define those functions in some special way. ++** For instance, if you want to create one Windows DLL with the core and ++** the libraries, you may want to use the following definition (define ++** LUA_BUILD_AS_DLL to get it). ++*/ ++#if defined(LUA_BUILD_AS_DLL) /* { */ ++ ++#if defined(LUA_CORE) || defined(LUA_LIB) /* { */ ++#define LUA_API __declspec(dllexport) ++#else /* }{ */ ++#define LUA_API __declspec(dllimport) ++#endif /* } */ ++ ++#else /* }{ */ ++ ++#define LUA_API extern ++ ++#endif /* } */ ++ ++ ++/* ++** More often than not the libs go together with the core. ++*/ ++#define LUALIB_API LUA_API ++#define LUAMOD_API LUA_API ++ ++ ++/* ++@@ LUAI_FUNC is a mark for all extern functions that are not to be ++** exported to outside modules. ++@@ LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables, ++** none of which to be exported to outside modules (LUAI_DDEF for ++** definitions and LUAI_DDEC for declarations). ++** CHANGE them if you need to mark them in some special way. Elf/gcc ++** (versions 3.2 and later) mark them as "hidden" to optimize access ++** when Lua is compiled as a shared library. Not all elf targets support ++** this attribute. Unfortunately, gcc does not offer a way to check ++** whether the target offers that support, and those without support ++** give a warning about it. To avoid these warnings, change to the ++** default definition. ++*/ ++#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \ ++ defined(__ELF__) /* { */ ++#define LUAI_FUNC __attribute__((visibility("internal"))) extern ++#else /* }{ */ ++#define LUAI_FUNC extern ++#endif /* } */ ++ ++#define LUAI_DDEC(dec) LUAI_FUNC dec ++#define LUAI_DDEF /* empty */ ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Compatibility with previous versions ++** =================================================================== ++*/ ++ ++/* ++@@ LUA_COMPAT_5_3 controls other macros for compatibility with Lua 5.3. ++** You can define it to get all options, or change specific options ++** to fit your specific needs. ++*/ ++#if defined(LUA_COMPAT_5_3) /* { */ ++ ++/* ++@@ LUA_COMPAT_MATHLIB controls the presence of several deprecated ++** functions in the mathematical library. ++** (These functions were already officially removed in 5.3; ++** nevertheless they are still available here.) ++*/ ++#define LUA_COMPAT_MATHLIB ++ ++/* ++@@ LUA_COMPAT_APIINTCASTS controls the presence of macros for ++** manipulating other integer types (lua_pushunsigned, lua_tounsigned, ++** luaL_checkint, luaL_checklong, etc.) ++** (These macros were also officially removed in 5.3, but they are still ++** available here.) ++*/ ++#define LUA_COMPAT_APIINTCASTS ++ ++ ++/* ++@@ LUA_COMPAT_LT_LE controls the emulation of the '__le' metamethod ++** using '__lt'. ++*/ ++#define LUA_COMPAT_LT_LE ++ ++ ++/* ++@@ The following macros supply trivial compatibility for some ++** changes in the API. The macros themselves document how to ++** change your code to avoid using them. ++** (Once more, these macros were officially removed in 5.3, but they are ++** still available here.) ++*/ ++#define lua_strlen(L,i) lua_rawlen(L, (i)) ++ ++#define lua_objlen(L,i) lua_rawlen(L, (i)) ++ ++#define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ) ++#define lua_lessthan(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPLT) ++ ++#endif /* } */ ++ ++/* }================================================================== */ ++ ++ ++ ++/* ++** {================================================================== ++** Configuration for Numbers (low-level part). ++** Change these definitions if no predefined LUA_FLOAT_* / LUA_INT_* ++** satisfy your needs. ++** =================================================================== ++*/ ++ ++/* ++@@ LUAI_UACNUMBER is the result of a 'default argument promotion' ++@@ over a floating number. ++@@ l_floatatt(x) corrects float attribute 'x' to the proper float type ++** by prefixing it with one of FLT/DBL/LDBL. ++@@ LUA_NUMBER_FRMLEN is the length modifier for writing floats. ++@@ LUA_NUMBER_FMT is the format for writing floats. ++@@ lua_number2str converts a float to a string. ++@@ l_mathop allows the addition of an 'l' or 'f' to all math operations. ++@@ l_floor takes the floor of a float. ++@@ lua_str2number converts a decimal numeral to a number. ++*/ ++ ++ ++/* The following definitions are good for most cases here */ ++ ++#define l_floor(x) (l_mathop(floor)(x)) ++ ++#define lua_number2str(s,sz,n) \ ++ l_sprintf((s), sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)(n)) ++ ++/* ++@@ lua_numbertointeger converts a float number with an integral value ++** to an integer, or returns 0 if float is not within the range of ++** a lua_Integer. (The range comparisons are tricky because of ++** rounding. The tests here assume a two-complement representation, ++** where MININTEGER always has an exact representation as a float; ++** MAXINTEGER may not have one, and therefore its conversion to float ++** may have an ill-defined value.) ++*/ ++#define lua_numbertointeger(n,p) \ ++ ((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \ ++ (n) < -(LUA_NUMBER)(LUA_MININTEGER) && \ ++ (*(p) = (LUA_INTEGER)(n), 1)) ++ ++ ++/* now the variable definitions */ ++ ++#if LUA_FLOAT_TYPE == LUA_FLOAT_FLOAT /* { single float */ ++ ++#define LUA_NUMBER float ++ ++#define l_floatatt(n) (FLT_##n) ++ ++#define LUAI_UACNUMBER double ++ ++#define LUA_NUMBER_FRMLEN "" ++#define LUA_NUMBER_FMT "%.7g" ++ ++#define l_mathop(op) op##f ++ ++#define lua_str2number(s,p) strtof((s), (p)) ++ ++ ++#elif LUA_FLOAT_TYPE == LUA_FLOAT_LONGDOUBLE /* }{ long double */ ++ ++#define LUA_NUMBER long double ++ ++#define l_floatatt(n) (LDBL_##n) ++ ++#define LUAI_UACNUMBER long double ++ ++#define LUA_NUMBER_FRMLEN "L" ++#define LUA_NUMBER_FMT "%.19Lg" ++ ++#define l_mathop(op) op##l ++ ++#define lua_str2number(s,p) strtold((s), (p)) ++ ++#elif LUA_FLOAT_TYPE == LUA_FLOAT_DOUBLE /* }{ double */ ++ ++#define LUA_NUMBER double ++ ++#define l_floatatt(n) (DBL_##n) ++ ++#define LUAI_UACNUMBER double ++ ++#define LUA_NUMBER_FRMLEN "" ++#define LUA_NUMBER_FMT "%.14g" ++ ++#define l_mathop(op) op ++ ++#define lua_str2number(s,p) strtod((s), (p)) ++ ++#else /* }{ */ ++ ++#error "numeric float type not defined" ++ ++#endif /* } */ ++ ++ ++ ++/* ++@@ LUA_UNSIGNED is the unsigned version of LUA_INTEGER. ++@@ LUAI_UACINT is the result of a 'default argument promotion' ++@@ over a LUA_INTEGER. ++@@ LUA_INTEGER_FRMLEN is the length modifier for reading/writing integers. ++@@ LUA_INTEGER_FMT is the format for writing integers. ++@@ LUA_MAXINTEGER is the maximum value for a LUA_INTEGER. ++@@ LUA_MININTEGER is the minimum value for a LUA_INTEGER. ++@@ LUA_MAXUNSIGNED is the maximum value for a LUA_UNSIGNED. ++@@ LUA_UNSIGNEDBITS is the number of bits in a LUA_UNSIGNED. ++@@ lua_integer2str converts an integer to a string. ++*/ ++ ++ ++/* The following definitions are good for most cases here */ ++ ++#define LUA_INTEGER_FMT "%" LUA_INTEGER_FRMLEN "d" ++ ++#define LUAI_UACINT LUA_INTEGER ++ ++#define lua_integer2str(s,sz,n) \ ++ l_sprintf((s), sz, LUA_INTEGER_FMT, (LUAI_UACINT)(n)) ++ ++/* ++** use LUAI_UACINT here to avoid problems with promotions (which ++** can turn a comparison between unsigneds into a signed comparison) ++*/ ++#define LUA_UNSIGNED unsigned LUAI_UACINT ++ ++ ++#define LUA_UNSIGNEDBITS (sizeof(LUA_UNSIGNED) * CHAR_BIT) ++ ++ ++/* now the variable definitions */ ++ ++#if LUA_INT_TYPE == LUA_INT_INT /* { int */ ++ ++#define LUA_INTEGER int ++#define LUA_INTEGER_FRMLEN "" ++ ++#define LUA_MAXINTEGER INT_MAX ++#define LUA_MININTEGER INT_MIN ++ ++#define LUA_MAXUNSIGNED UINT_MAX ++ ++#elif LUA_INT_TYPE == LUA_INT_LONG /* }{ long */ ++ ++#define LUA_INTEGER long ++#define LUA_INTEGER_FRMLEN "l" ++ ++#define LUA_MAXINTEGER LONG_MAX ++#define LUA_MININTEGER LONG_MIN ++ ++#define LUA_MAXUNSIGNED ULONG_MAX ++ ++#elif LUA_INT_TYPE == LUA_INT_LONGLONG /* }{ long long */ ++ ++/* use presence of macro LLONG_MAX as proxy for C99 compliance */ ++#if defined(LLONG_MAX) /* { */ ++/* use ISO C99 stuff */ ++ ++#define LUA_INTEGER long long ++#define LUA_INTEGER_FRMLEN "ll" ++ ++#define LUA_MAXINTEGER LLONG_MAX ++#define LUA_MININTEGER LLONG_MIN ++ ++#define LUA_MAXUNSIGNED ULLONG_MAX ++ ++#elif defined(LUA_USE_WINDOWS) /* }{ */ ++/* in Windows, can use specific Windows types */ ++ ++#define LUA_INTEGER __int64 ++#define LUA_INTEGER_FRMLEN "I64" ++ ++#define LUA_MAXINTEGER _I64_MAX ++#define LUA_MININTEGER _I64_MIN ++ ++#define LUA_MAXUNSIGNED _UI64_MAX ++ ++#else /* }{ */ ++ ++#error "Compiler does not support 'long long'. Use option '-DLUA_32BITS' \ ++ or '-DLUA_C89_NUMBERS' (see file 'luaconf.h' for details)" ++ ++#endif /* } */ ++ ++#else /* }{ */ ++ ++#error "numeric integer type not defined" ++ ++#endif /* } */ ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Dependencies with C99 and other C details ++** =================================================================== ++*/ ++ ++/* ++@@ l_sprintf is equivalent to 'snprintf' or 'sprintf' in C89. ++** (All uses in Lua have only one format item.) ++*/ ++#if !defined(LUA_USE_C89) ++#define l_sprintf(s,sz,f,i) snprintf(s,sz,f,i) ++#else ++#define l_sprintf(s,sz,f,i) ((void)(sz), sprintf(s,f,i)) ++#endif ++ ++ ++/* ++@@ lua_strx2number converts a hexadecimal numeral to a number. ++** In C99, 'strtod' does that conversion. Otherwise, you can ++** leave 'lua_strx2number' undefined and Lua will provide its own ++** implementation. ++*/ ++#if !defined(LUA_USE_C89) ++#define lua_strx2number(s,p) lua_str2number(s,p) ++#endif ++ ++ ++/* ++@@ lua_pointer2str converts a pointer to a readable string in a ++** non-specified way. ++*/ ++#define lua_pointer2str(buff,sz,p) l_sprintf(buff,sz,"%p",p) ++ ++ ++/* ++@@ lua_number2strx converts a float to a hexadecimal numeral. ++** In C99, 'sprintf' (with format specifiers '%a'/'%A') does that. ++** Otherwise, you can leave 'lua_number2strx' undefined and Lua will ++** provide its own implementation. ++*/ ++#if !defined(LUA_USE_C89) ++#define lua_number2strx(L,b,sz,f,n) \ ++ ((void)L, l_sprintf(b,sz,f,(LUAI_UACNUMBER)(n))) ++#endif ++ ++ ++/* ++** 'strtof' and 'opf' variants for math functions are not valid in ++** C89. Otherwise, the macro 'HUGE_VALF' is a good proxy for testing the ++** availability of these variants. ('math.h' is already included in ++** all files that use these macros.) ++*/ ++#if defined(LUA_USE_C89) || (defined(HUGE_VAL) && !defined(HUGE_VALF)) ++#undef l_mathop /* variants not available */ ++#undef lua_str2number ++#define l_mathop(op) (lua_Number)op /* no variant */ ++#define lua_str2number(s,p) ((lua_Number)strtod((s), (p))) ++#endif ++ ++ ++/* ++@@ LUA_KCONTEXT is the type of the context ('ctx') for continuation ++** functions. It must be a numerical type; Lua will use 'intptr_t' if ++** available, otherwise it will use 'ptrdiff_t' (the nearest thing to ++** 'intptr_t' in C89) ++*/ ++#define LUA_KCONTEXT ptrdiff_t ++ ++#if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \ ++ __STDC_VERSION__ >= 199901L ++#include ++#if defined(INTPTR_MAX) /* even in C99 this type is optional */ ++#undef LUA_KCONTEXT ++#define LUA_KCONTEXT intptr_t ++#endif ++#endif ++ ++ ++/* ++@@ lua_getlocaledecpoint gets the locale "radix character" (decimal point). ++** Change that if you do not want to use C locales. (Code using this ++** macro must include the header 'locale.h'.) ++*/ ++#if !defined(lua_getlocaledecpoint) ++#define lua_getlocaledecpoint() (localeconv()->decimal_point[0]) ++#endif ++ ++ ++/* ++** macros to improve jump prediction, used mostly for error handling ++** and debug facilities. (Some macros in the Lua API use these macros. ++** Define LUA_NOBUILTIN if you do not want '__builtin_expect' in your ++** code.) ++*/ ++#if !defined(luai_likely) ++ ++#if defined(__GNUC__) && !defined(LUA_NOBUILTIN) ++#define luai_likely(x) (__builtin_expect(((x) != 0), 1)) ++#define luai_unlikely(x) (__builtin_expect(((x) != 0), 0)) ++#else ++#define luai_likely(x) (x) ++#define luai_unlikely(x) (x) ++#endif ++ ++#endif ++ ++ ++#if defined(LUA_CORE) || defined(LUA_LIB) ++/* shorter names for Lua's own use */ ++#define l_likely(x) luai_likely(x) ++#define l_unlikely(x) luai_unlikely(x) ++#endif ++ ++ ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Language Variations ++** ===================================================================== ++*/ ++ ++/* ++@@ LUA_NOCVTN2S/LUA_NOCVTS2N control how Lua performs some ++** coercions. Define LUA_NOCVTN2S to turn off automatic coercion from ++** numbers to strings. Define LUA_NOCVTS2N to turn off automatic ++** coercion from strings to numbers. ++*/ ++/* #define LUA_NOCVTN2S */ ++/* #define LUA_NOCVTS2N */ ++ ++ ++/* ++@@ LUA_USE_APICHECK turns on several consistency checks on the C API. ++** Define it as a help when debugging C code. ++*/ ++#if defined(LUA_USE_APICHECK) ++#include ++#define luai_apicheck(l,e) assert(e) ++#endif ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Macros that affect the API and must be stable (that is, must be the ++** same when you compile Lua and when you compile code that links to ++** Lua). ++** ===================================================================== ++*/ ++ ++/* ++@@ LUAI_MAXSTACK limits the size of the Lua stack. ++** CHANGE it if you need a different limit. This limit is arbitrary; ++** its only purpose is to stop Lua from consuming unlimited stack ++** space (and to reserve some numbers for pseudo-indices). ++** (It must fit into max(size_t)/32.) ++*/ ++#if LUAI_IS32INT ++#define LUAI_MAXSTACK 1000000 ++#else ++#define LUAI_MAXSTACK 15000 ++#endif ++ ++ ++/* ++@@ LUA_EXTRASPACE defines the size of a raw memory area associated with ++** a Lua state with very fast access. ++** CHANGE it if you need a different size. ++*/ ++#define LUA_EXTRASPACE (sizeof(void *)) ++ ++ ++/* ++@@ LUA_IDSIZE gives the maximum size for the description of the source ++@@ of a function in debug information. ++** CHANGE it if you want a different size. ++*/ ++#define LUA_IDSIZE 60 ++ ++ ++/* ++@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system. ++*/ ++#define LUAL_BUFFERSIZE ((int)(16 * sizeof(void*) * sizeof(lua_Number))) ++ ++ ++/* ++@@ LUAI_MAXALIGN defines fields that, when used in a union, ensure ++** maximum alignment for the other items in that union. ++*/ ++#define LUAI_MAXALIGN lua_Number n; double u; void *s; lua_Integer i; long l ++ ++/* }================================================================== */ ++ ++ ++ ++ ++ ++/* =================================================================== */ ++ ++/* ++** Local configuration. You can use this space to add your redefinitions ++** without modifying the main part of the file. ++*/ ++ ++ ++ ++ ++ ++#endif ++ +diff --git a/src/bin/lua/lualib.h b/src/bin/lua/lualib.h +new file mode 100644 +index 0000000000..2625529076 +--- /dev/null ++++ b/src/bin/lua/lualib.h +@@ -0,0 +1,52 @@ ++/* ++** $Id: lualib.h $ ++** Lua standard libraries ++** See Copyright Notice in lua.h ++*/ ++ ++ ++#ifndef lualib_h ++#define lualib_h ++ ++#include "lua.h" ++ ++ ++/* version suffix for environment variable names */ ++#define LUA_VERSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR ++ ++ ++LUAMOD_API int (luaopen_base) (lua_State *L); ++ ++#define LUA_COLIBNAME "coroutine" ++LUAMOD_API int (luaopen_coroutine) (lua_State *L); ++ ++#define LUA_TABLIBNAME "table" ++LUAMOD_API int (luaopen_table) (lua_State *L); ++ ++#define LUA_IOLIBNAME "io" ++LUAMOD_API int (luaopen_io) (lua_State *L); ++ ++#define LUA_OSLIBNAME "os" ++LUAMOD_API int (luaopen_os) (lua_State *L); ++ ++#define LUA_STRLIBNAME "string" ++LUAMOD_API int (luaopen_string) (lua_State *L); ++ ++#define LUA_UTF8LIBNAME "utf8" ++LUAMOD_API int (luaopen_utf8) (lua_State *L); ++ ++#define LUA_MATHLIBNAME "math" ++LUAMOD_API int (luaopen_math) (lua_State *L); ++ ++#define LUA_DBLIBNAME "debug" ++LUAMOD_API int (luaopen_debug) (lua_State *L); ++ ++#define LUA_LOADLIBNAME "package" ++LUAMOD_API int (luaopen_package) (lua_State *L); ++ ++ ++/* open all previous libraries */ ++LUALIB_API void (luaL_openlibs) (lua_State *L); ++ ++ ++#endif +diff --git a/src/bin/lua/lundump.c b/src/bin/lua/lundump.c +new file mode 100644 +index 0000000000..5aa55c4457 +--- /dev/null ++++ b/src/bin/lua/lundump.c +@@ -0,0 +1,333 @@ ++/* ++** $Id: lundump.c $ ++** load precompiled Lua chunks ++** See Copyright Notice in lua.h ++*/ ++ ++#define lundump_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++ ++#include "lua.h" ++ ++#include "ldebug.h" ++#include "ldo.h" ++#include "lfunc.h" ++#include "lmem.h" ++#include "lobject.h" ++#include "lstring.h" ++#include "lundump.h" ++#include "lzio.h" ++ ++ ++#if !defined(luai_verifycode) ++#define luai_verifycode(L,f) /* empty */ ++#endif ++ ++ ++typedef struct { ++ lua_State *L; ++ ZIO *Z; ++ const char *name; ++} LoadState; ++ ++ ++static l_noret error (LoadState *S, const char *why) { ++ luaO_pushfstring(S->L, "%s: bad binary format (%s)", S->name, why); ++ luaD_throw(S->L, LUA_ERRSYNTAX); ++} ++ ++ ++/* ++** All high-level loads go through loadVector; you can change it to ++** adapt to the endianness of the input ++*/ ++#define loadVector(S,b,n) loadBlock(S,b,(n)*sizeof((b)[0])) ++ ++static void loadBlock (LoadState *S, void *b, size_t size) { ++ if (luaZ_read(S->Z, b, size) != 0) ++ error(S, "truncated chunk"); ++} ++ ++ ++#define loadVar(S,x) loadVector(S,&x,1) ++ ++ ++static lu_byte loadByte (LoadState *S) { ++ int b = zgetc(S->Z); ++ if (b == EOZ) ++ error(S, "truncated chunk"); ++ return cast_byte(b); ++} ++ ++ ++static size_t loadUnsigned (LoadState *S, size_t limit) { ++ size_t x = 0; ++ int b; ++ limit >>= 7; ++ do { ++ b = loadByte(S); ++ if (x >= limit) ++ error(S, "integer overflow"); ++ x = (x << 7) | (b & 0x7f); ++ } while ((b & 0x80) == 0); ++ return x; ++} ++ ++ ++static size_t loadSize (LoadState *S) { ++ return loadUnsigned(S, ~(size_t)0); ++} ++ ++ ++static int loadInt (LoadState *S) { ++ return cast_int(loadUnsigned(S, INT_MAX)); ++} ++ ++ ++static lua_Number loadNumber (LoadState *S) { ++ lua_Number x; ++ loadVar(S, x); ++ return x; ++} ++ ++ ++static lua_Integer loadInteger (LoadState *S) { ++ lua_Integer x; ++ loadVar(S, x); ++ return x; ++} ++ ++ ++/* ++** Load a nullable string into prototype 'p'. ++*/ ++static TString *loadStringN (LoadState *S, Proto *p) { ++ lua_State *L = S->L; ++ TString *ts; ++ size_t size = loadSize(S); ++ if (size == 0) /* no string? */ ++ return NULL; ++ else if (--size <= LUAI_MAXSHORTLEN) { /* short string? */ ++ char buff[LUAI_MAXSHORTLEN]; ++ loadVector(S, buff, size); /* load string into buffer */ ++ ts = luaS_newlstr(L, buff, size); /* create string */ ++ } ++ else { /* long string */ ++ ts = luaS_createlngstrobj(L, size); /* create string */ ++ setsvalue2s(L, L->top, ts); /* anchor it ('loadVector' can GC) */ ++ luaD_inctop(L); ++ loadVector(S, getstr(ts), size); /* load directly in final place */ ++ L->top--; /* pop string */ ++ } ++ luaC_objbarrier(L, p, ts); ++ return ts; ++} ++ ++ ++/* ++** Load a non-nullable string into prototype 'p'. ++*/ ++static TString *loadString (LoadState *S, Proto *p) { ++ TString *st = loadStringN(S, p); ++ if (st == NULL) ++ error(S, "bad format for constant string"); ++ return st; ++} ++ ++ ++static void loadCode (LoadState *S, Proto *f) { ++ int n = loadInt(S); ++ f->code = luaM_newvectorchecked(S->L, n, Instruction); ++ f->sizecode = n; ++ loadVector(S, f->code, n); ++} ++ ++ ++static void loadFunction(LoadState *S, Proto *f, TString *psource); ++ ++ ++static void loadConstants (LoadState *S, Proto *f) { ++ int i; ++ int n = loadInt(S); ++ f->k = luaM_newvectorchecked(S->L, n, TValue); ++ f->sizek = n; ++ for (i = 0; i < n; i++) ++ setnilvalue(&f->k[i]); ++ for (i = 0; i < n; i++) { ++ TValue *o = &f->k[i]; ++ int t = loadByte(S); ++ switch (t) { ++ case LUA_VNIL: ++ setnilvalue(o); ++ break; ++ case LUA_VFALSE: ++ setbfvalue(o); ++ break; ++ case LUA_VTRUE: ++ setbtvalue(o); ++ break; ++ case LUA_VNUMFLT: ++ setfltvalue(o, loadNumber(S)); ++ break; ++ case LUA_VNUMINT: ++ setivalue(o, loadInteger(S)); ++ break; ++ case LUA_VSHRSTR: ++ case LUA_VLNGSTR: ++ setsvalue2n(S->L, o, loadString(S, f)); ++ break; ++ default: lua_assert(0); ++ } ++ } ++} ++ ++ ++static void loadProtos (LoadState *S, Proto *f) { ++ int i; ++ int n = loadInt(S); ++ f->p = luaM_newvectorchecked(S->L, n, Proto *); ++ f->sizep = n; ++ for (i = 0; i < n; i++) ++ f->p[i] = NULL; ++ for (i = 0; i < n; i++) { ++ f->p[i] = luaF_newproto(S->L); ++ luaC_objbarrier(S->L, f, f->p[i]); ++ loadFunction(S, f->p[i], f->source); ++ } ++} ++ ++ ++/* ++** Load the upvalues for a function. The names must be filled first, ++** because the filling of the other fields can raise read errors and ++** the creation of the error message can call an emergency collection; ++** in that case all prototypes must be consistent for the GC. ++*/ ++static void loadUpvalues (LoadState *S, Proto *f) { ++ int i, n; ++ n = loadInt(S); ++ f->upvalues = luaM_newvectorchecked(S->L, n, Upvaldesc); ++ f->sizeupvalues = n; ++ for (i = 0; i < n; i++) /* make array valid for GC */ ++ f->upvalues[i].name = NULL; ++ for (i = 0; i < n; i++) { /* following calls can raise errors */ ++ f->upvalues[i].instack = loadByte(S); ++ f->upvalues[i].idx = loadByte(S); ++ f->upvalues[i].kind = loadByte(S); ++ } ++} ++ ++ ++static void loadDebug (LoadState *S, Proto *f) { ++ int i, n; ++ n = loadInt(S); ++ f->lineinfo = luaM_newvectorchecked(S->L, n, ls_byte); ++ f->sizelineinfo = n; ++ loadVector(S, f->lineinfo, n); ++ n = loadInt(S); ++ f->abslineinfo = luaM_newvectorchecked(S->L, n, AbsLineInfo); ++ f->sizeabslineinfo = n; ++ for (i = 0; i < n; i++) { ++ f->abslineinfo[i].pc = loadInt(S); ++ f->abslineinfo[i].line = loadInt(S); ++ } ++ n = loadInt(S); ++ f->locvars = luaM_newvectorchecked(S->L, n, LocVar); ++ f->sizelocvars = n; ++ for (i = 0; i < n; i++) ++ f->locvars[i].varname = NULL; ++ for (i = 0; i < n; i++) { ++ f->locvars[i].varname = loadStringN(S, f); ++ f->locvars[i].startpc = loadInt(S); ++ f->locvars[i].endpc = loadInt(S); ++ } ++ n = loadInt(S); ++ for (i = 0; i < n; i++) ++ f->upvalues[i].name = loadStringN(S, f); ++} ++ ++ ++static void loadFunction (LoadState *S, Proto *f, TString *psource) { ++ f->source = loadStringN(S, f); ++ if (f->source == NULL) /* no source in dump? */ ++ f->source = psource; /* reuse parent's source */ ++ f->linedefined = loadInt(S); ++ f->lastlinedefined = loadInt(S); ++ f->numparams = loadByte(S); ++ f->is_vararg = loadByte(S); ++ f->maxstacksize = loadByte(S); ++ loadCode(S, f); ++ loadConstants(S, f); ++ loadUpvalues(S, f); ++ loadProtos(S, f); ++ loadDebug(S, f); ++} ++ ++ ++static void checkliteral (LoadState *S, const char *s, const char *msg) { ++ char buff[sizeof(LUA_SIGNATURE) + sizeof(LUAC_DATA)]; /* larger than both */ ++ size_t len = strlen(s); ++ loadVector(S, buff, len); ++ if (memcmp(s, buff, len) != 0) ++ error(S, msg); ++} ++ ++ ++static void fchecksize (LoadState *S, size_t size, const char *tname) { ++ if (loadByte(S) != size) ++ error(S, luaO_pushfstring(S->L, "%s size mismatch", tname)); ++} ++ ++ ++#define checksize(S,t) fchecksize(S,sizeof(t),#t) ++ ++static void checkHeader (LoadState *S) { ++ /* skip 1st char (already read and checked) */ ++ checkliteral(S, &LUA_SIGNATURE[1], "not a binary chunk"); ++ if (loadByte(S) != LUAC_VERSION) ++ error(S, "version mismatch"); ++ if (loadByte(S) != LUAC_FORMAT) ++ error(S, "format mismatch"); ++ checkliteral(S, LUAC_DATA, "corrupted chunk"); ++ checksize(S, Instruction); ++ checksize(S, lua_Integer); ++ checksize(S, lua_Number); ++ if (loadInteger(S) != LUAC_INT) ++ error(S, "integer format mismatch"); ++ if (loadNumber(S) != LUAC_NUM) ++ error(S, "float format mismatch"); ++} ++ ++ ++/* ++** Load precompiled chunk. ++*/ ++LClosure *luaU_undump(lua_State *L, ZIO *Z, const char *name) { ++ LoadState S; ++ LClosure *cl; ++ if (*name == '@' || *name == '=') ++ S.name = name + 1; ++ else if (*name == LUA_SIGNATURE[0]) ++ S.name = "binary string"; ++ else ++ S.name = name; ++ S.L = L; ++ S.Z = Z; ++ checkHeader(&S); ++ cl = luaF_newLclosure(L, loadByte(&S)); ++ setclLvalue2s(L, L->top, cl); ++ luaD_inctop(L); ++ cl->p = luaF_newproto(L); ++ luaC_objbarrier(L, cl, cl->p); ++ loadFunction(&S, cl->p, NULL); ++ lua_assert(cl->nupvalues == cl->p->sizeupvalues); ++ luai_verifycode(L, cl->p); ++ return cl; ++} ++ +diff --git a/src/bin/lua/lundump.h b/src/bin/lua/lundump.h +new file mode 100644 +index 0000000000..f3748a9980 +--- /dev/null ++++ b/src/bin/lua/lundump.h +@@ -0,0 +1,36 @@ ++/* ++** $Id: lundump.h $ ++** load precompiled Lua chunks ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef lundump_h ++#define lundump_h ++ ++#include "llimits.h" ++#include "lobject.h" ++#include "lzio.h" ++ ++ ++/* data to catch conversion errors */ ++#define LUAC_DATA "\x19\x93\r\n\x1a\n" ++ ++#define LUAC_INT 0x5678 ++#define LUAC_NUM cast_num(370.5) ++ ++/* ++** Encode major-minor version in one byte, one nibble for each ++*/ ++#define MYINT(s) (s[0]-'0') /* assume one-digit numerals */ ++#define LUAC_VERSION (MYINT(LUA_VERSION_MAJOR)*16+MYINT(LUA_VERSION_MINOR)) ++ ++#define LUAC_FORMAT 0 /* this is the official format */ ++ ++/* load one chunk; from lundump.c */ ++LUAI_FUNC LClosure* luaU_undump (lua_State* L, ZIO* Z, const char* name); ++ ++/* dump one chunk; from ldump.c */ ++LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, ++ void* data, int strip); ++ ++#endif +diff --git a/src/bin/lua/lutf8lib.c b/src/bin/lua/lutf8lib.c +new file mode 100644 +index 0000000000..901d985f8d +--- /dev/null ++++ b/src/bin/lua/lutf8lib.c +@@ -0,0 +1,289 @@ ++/* ++** $Id: lutf8lib.c $ ++** Standard library for UTF-8 manipulation ++** See Copyright Notice in lua.h ++*/ ++ ++#define lutf8lib_c ++#define LUA_LIB ++ ++#include "lprefix.h" ++ ++ ++#include ++#include ++#include ++#include ++ ++#include "lua.h" ++ ++#include "lauxlib.h" ++#include "lualib.h" ++ ++ ++#define MAXUNICODE 0x10FFFFu ++ ++#define MAXUTF 0x7FFFFFFFu ++ ++/* ++** Integer type for decoded UTF-8 values; MAXUTF needs 31 bits. ++*/ ++#if (UINT_MAX >> 30) >= 1 ++typedef unsigned int utfint; ++#else ++typedef unsigned long utfint; ++#endif ++ ++ ++#define iscont(p) ((*(p) & 0xC0) == 0x80) ++ ++ ++/* from strlib */ ++/* translate a relative string position: negative means back from end */ ++static lua_Integer u_posrelat (lua_Integer pos, size_t len) { ++ if (pos >= 0) return pos; ++ else if (0u - (size_t)pos > len) return 0; ++ else return (lua_Integer)len + pos + 1; ++} ++ ++ ++/* ++** Decode one UTF-8 sequence, returning NULL if byte sequence is ++** invalid. The array 'limits' stores the minimum value for each ++** sequence length, to check for overlong representations. Its first ++** entry forces an error for non-ascii bytes with no continuation ++** bytes (count == 0). ++*/ ++static const char *utf8_decode (const char *s, utfint *val, int strict) { ++ static const utfint limits[] = ++ {~(utfint)0, 0x80, 0x800, 0x10000u, 0x200000u, 0x4000000u}; ++ unsigned int c = (unsigned char)s[0]; ++ utfint res = 0; /* final result */ ++ if (c < 0x80) /* ascii? */ ++ res = c; ++ else { ++ int count = 0; /* to count number of continuation bytes */ ++ for (; c & 0x40; c <<= 1) { /* while it needs continuation bytes... */ ++ unsigned int cc = (unsigned char)s[++count]; /* read next byte */ ++ if ((cc & 0xC0) != 0x80) /* not a continuation byte? */ ++ return NULL; /* invalid byte sequence */ ++ res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */ ++ } ++ res |= ((utfint)(c & 0x7F) << (count * 5)); /* add first byte */ ++ if (count > 5 || res > MAXUTF || res < limits[count]) ++ return NULL; /* invalid byte sequence */ ++ s += count; /* skip continuation bytes read */ ++ } ++ if (strict) { ++ /* check for invalid code points; too large or surrogates */ ++ if (res > MAXUNICODE || (0xD800u <= res && res <= 0xDFFFu)) ++ return NULL; ++ } ++ if (val) *val = res; ++ return s + 1; /* +1 to include first byte */ ++} ++ ++ ++/* ++** utf8len(s [, i [, j [, lax]]]) --> number of characters that ++** start in the range [i,j], or nil + current position if 's' is not ++** well formed in that interval ++*/ ++static int utflen (lua_State *L) { ++ lua_Integer n = 0; /* counter for the number of characters */ ++ size_t len; /* string length in bytes */ ++ const char *s = luaL_checklstring(L, 1, &len); ++ lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len); ++ lua_Integer posj = u_posrelat(luaL_optinteger(L, 3, -1), len); ++ int lax = lua_toboolean(L, 4); ++ luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 2, ++ "initial position out of bounds"); ++ luaL_argcheck(L, --posj < (lua_Integer)len, 3, ++ "final position out of bounds"); ++ while (posi <= posj) { ++ const char *s1 = utf8_decode(s + posi, NULL, !lax); ++ if (s1 == NULL) { /* conversion error? */ ++ luaL_pushfail(L); /* return fail ... */ ++ lua_pushinteger(L, posi + 1); /* ... and current position */ ++ return 2; ++ } ++ posi = s1 - s; ++ n++; ++ } ++ lua_pushinteger(L, n); ++ return 1; ++} ++ ++ ++/* ++** codepoint(s, [i, [j [, lax]]]) -> returns codepoints for all ++** characters that start in the range [i,j] ++*/ ++static int codepoint (lua_State *L) { ++ size_t len; ++ const char *s = luaL_checklstring(L, 1, &len); ++ lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len); ++ lua_Integer pose = u_posrelat(luaL_optinteger(L, 3, posi), len); ++ int lax = lua_toboolean(L, 4); ++ int n; ++ const char *se; ++ luaL_argcheck(L, posi >= 1, 2, "out of bounds"); ++ luaL_argcheck(L, pose <= (lua_Integer)len, 3, "out of bounds"); ++ if (posi > pose) return 0; /* empty interval; return no values */ ++ if (pose - posi >= INT_MAX) /* (lua_Integer -> int) overflow? */ ++ return luaL_error(L, "string slice too long"); ++ n = (int)(pose - posi) + 1; /* upper bound for number of returns */ ++ luaL_checkstack(L, n, "string slice too long"); ++ n = 0; /* count the number of returns */ ++ se = s + pose; /* string end */ ++ for (s += posi - 1; s < se;) { ++ utfint code; ++ s = utf8_decode(s, &code, !lax); ++ if (s == NULL) ++ return luaL_error(L, "invalid UTF-8 code"); ++ lua_pushinteger(L, code); ++ n++; ++ } ++ return n; ++} ++ ++ ++static void pushutfchar (lua_State *L, int arg) { ++ lua_Unsigned code = (lua_Unsigned)luaL_checkinteger(L, arg); ++ luaL_argcheck(L, code <= MAXUTF, arg, "value out of range"); ++ lua_pushfstring(L, "%U", (long)code); ++} ++ ++ ++/* ++** utfchar(n1, n2, ...) -> char(n1)..char(n2)... ++*/ ++static int utfchar (lua_State *L) { ++ int n = lua_gettop(L); /* number of arguments */ ++ if (n == 1) /* optimize common case of single char */ ++ pushutfchar(L, 1); ++ else { ++ int i; ++ luaL_Buffer b; ++ luaL_buffinit(L, &b); ++ for (i = 1; i <= n; i++) { ++ pushutfchar(L, i); ++ luaL_addvalue(&b); ++ } ++ luaL_pushresult(&b); ++ } ++ return 1; ++} ++ ++ ++/* ++** offset(s, n, [i]) -> index where n-th character counting from ++** position 'i' starts; 0 means character at 'i'. ++*/ ++static int byteoffset (lua_State *L) { ++ size_t len; ++ const char *s = luaL_checklstring(L, 1, &len); ++ lua_Integer n = luaL_checkinteger(L, 2); ++ lua_Integer posi = (n >= 0) ? 1 : len + 1; ++ posi = u_posrelat(luaL_optinteger(L, 3, posi), len); ++ luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 3, ++ "position out of bounds"); ++ if (n == 0) { ++ /* find beginning of current byte sequence */ ++ while (posi > 0 && iscont(s + posi)) posi--; ++ } ++ else { ++ if (iscont(s + posi)) ++ return luaL_error(L, "initial position is a continuation byte"); ++ if (n < 0) { ++ while (n < 0 && posi > 0) { /* move back */ ++ do { /* find beginning of previous character */ ++ posi--; ++ } while (posi > 0 && iscont(s + posi)); ++ n++; ++ } ++ } ++ else { ++ n--; /* do not move for 1st character */ ++ while (n > 0 && posi < (lua_Integer)len) { ++ do { /* find beginning of next character */ ++ posi++; ++ } while (iscont(s + posi)); /* (cannot pass final '\0') */ ++ n--; ++ } ++ } ++ } ++ if (n == 0) /* did it find given character? */ ++ lua_pushinteger(L, posi + 1); ++ else /* no such character */ ++ luaL_pushfail(L); ++ return 1; ++} ++ ++ ++static int iter_aux (lua_State *L, int strict) { ++ size_t len; ++ const char *s = luaL_checklstring(L, 1, &len); ++ lua_Integer n = lua_tointeger(L, 2) - 1; ++ if (n < 0) /* first iteration? */ ++ n = 0; /* start from here */ ++ else if (n < (lua_Integer)len) { ++ n++; /* skip current byte */ ++ while (iscont(s + n)) n++; /* and its continuations */ ++ } ++ if (n >= (lua_Integer)len) ++ return 0; /* no more codepoints */ ++ else { ++ utfint code; ++ const char *next = utf8_decode(s + n, &code, strict); ++ if (next == NULL) ++ return luaL_error(L, "invalid UTF-8 code"); ++ lua_pushinteger(L, n + 1); ++ lua_pushinteger(L, code); ++ return 2; ++ } ++} ++ ++ ++static int iter_auxstrict (lua_State *L) { ++ return iter_aux(L, 1); ++} ++ ++static int iter_auxlax (lua_State *L) { ++ return iter_aux(L, 0); ++} ++ ++ ++static int iter_codes (lua_State *L) { ++ int lax = lua_toboolean(L, 2); ++ luaL_checkstring(L, 1); ++ lua_pushcfunction(L, lax ? iter_auxlax : iter_auxstrict); ++ lua_pushvalue(L, 1); ++ lua_pushinteger(L, 0); ++ return 3; ++} ++ ++ ++/* pattern to match a single UTF-8 character */ ++#define UTF8PATT "[\0-\x7F\xC2-\xFD][\x80-\xBF]*" ++ ++ ++static const luaL_Reg funcs[] = { ++ {"offset", byteoffset}, ++ {"codepoint", codepoint}, ++ {"char", utfchar}, ++ {"len", utflen}, ++ {"codes", iter_codes}, ++ /* placeholders */ ++ {"charpattern", NULL}, ++ {NULL, NULL} ++}; ++ ++ ++LUAMOD_API int luaopen_utf8 (lua_State *L) { ++ luaL_newlib(L, funcs); ++ lua_pushlstring(L, UTF8PATT, sizeof(UTF8PATT)/sizeof(char) - 1); ++ lua_setfield(L, -2, "charpattern"); ++ return 1; ++} ++ +diff --git a/src/bin/lua/lvm.c b/src/bin/lua/lvm.c +new file mode 100644 +index 0000000000..c9729bcca0 +--- /dev/null ++++ b/src/bin/lua/lvm.c +@@ -0,0 +1,1836 @@ ++/* ++** $Id: lvm.c $ ++** Lua virtual machine ++** See Copyright Notice in lua.h ++*/ ++ ++#define lvm_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "lua.h" ++ ++#include "ldebug.h" ++#include "ldo.h" ++#include "lfunc.h" ++#include "lgc.h" ++#include "lobject.h" ++#include "lopcodes.h" ++#include "lstate.h" ++#include "lstring.h" ++#include "ltable.h" ++#include "ltm.h" ++#include "lvm.h" ++ ++ ++/* ++** By default, use jump tables in the main interpreter loop on gcc ++** and compatible compilers. ++*/ ++#if !defined(LUA_USE_JUMPTABLE) ++#if defined(__GNUC__) ++#define LUA_USE_JUMPTABLE 1 ++#else ++#define LUA_USE_JUMPTABLE 0 ++#endif ++#endif ++ ++ ++ ++/* limit for table tag-method chains (to avoid infinite loops) */ ++#define MAXTAGLOOP 2000 ++ ++ ++/* ++** 'l_intfitsf' checks whether a given integer is in the range that ++** can be converted to a float without rounding. Used in comparisons. ++*/ ++ ++/* number of bits in the mantissa of a float */ ++#define NBM (l_floatatt(MANT_DIG)) ++ ++/* ++** Check whether some integers may not fit in a float, testing whether ++** (maxinteger >> NBM) > 0. (That implies (1 << NBM) <= maxinteger.) ++** (The shifts are done in parts, to avoid shifting by more than the size ++** of an integer. In a worst case, NBM == 113 for long double and ++** sizeof(long) == 32.) ++*/ ++#if ((((LUA_MAXINTEGER >> (NBM / 4)) >> (NBM / 4)) >> (NBM / 4)) \ ++ >> (NBM - (3 * (NBM / 4)))) > 0 ++ ++/* limit for integers that fit in a float */ ++#define MAXINTFITSF ((lua_Unsigned)1 << NBM) ++ ++/* check whether 'i' is in the interval [-MAXINTFITSF, MAXINTFITSF] */ ++#define l_intfitsf(i) ((MAXINTFITSF + l_castS2U(i)) <= (2 * MAXINTFITSF)) ++ ++#else /* all integers fit in a float precisely */ ++ ++#define l_intfitsf(i) 1 ++ ++#endif ++ ++ ++/* ++** Try to convert a value from string to a number value. ++** If the value is not a string or is a string not representing ++** a valid numeral (or if coercions from strings to numbers ++** are disabled via macro 'cvt2num'), do not modify 'result' ++** and return 0. ++*/ ++static int l_strton (const TValue *obj, TValue *result) { ++ lua_assert(obj != result); ++ if (!cvt2num(obj)) /* is object not a string? */ ++ return 0; ++ else ++ return (luaO_str2num(svalue(obj), result) == vslen(obj) + 1); ++} ++ ++ ++/* ++** Try to convert a value to a float. The float case is already handled ++** by the macro 'tonumber'. ++*/ ++int luaV_tonumber_ (const TValue *obj, lua_Number *n) { ++ TValue v; ++ if (ttisinteger(obj)) { ++ *n = cast_num(ivalue(obj)); ++ return 1; ++ } ++ else if (l_strton(obj, &v)) { /* string coercible to number? */ ++ *n = nvalue(&v); /* convert result of 'luaO_str2num' to a float */ ++ return 1; ++ } ++ else ++ return 0; /* conversion failed */ ++} ++ ++ ++/* ++** try to convert a float to an integer, rounding according to 'mode'. ++*/ ++int luaV_flttointeger (lua_Number n, lua_Integer *p, F2Imod mode) { ++ lua_Number f = l_floor(n); ++ if (n != f) { /* not an integral value? */ ++ if (mode == F2Ieq) return 0; /* fails if mode demands integral value */ ++ else if (mode == F2Iceil) /* needs ceil? */ ++ f += 1; /* convert floor to ceil (remember: n != f) */ ++ } ++ return lua_numbertointeger(f, p); ++} ++ ++ ++/* ++** try to convert a value to an integer, rounding according to 'mode', ++** without string coercion. ++** ("Fast track" handled by macro 'tointegerns'.) ++*/ ++int luaV_tointegerns (const TValue *obj, lua_Integer *p, F2Imod mode) { ++ if (ttisfloat(obj)) ++ return luaV_flttointeger(fltvalue(obj), p, mode); ++ else if (ttisinteger(obj)) { ++ *p = ivalue(obj); ++ return 1; ++ } ++ else ++ return 0; ++} ++ ++ ++/* ++** try to convert a value to an integer. ++*/ ++int luaV_tointeger (const TValue *obj, lua_Integer *p, F2Imod mode) { ++ TValue v; ++ if (l_strton(obj, &v)) /* does 'obj' point to a numerical string? */ ++ obj = &v; /* change it to point to its corresponding number */ ++ return luaV_tointegerns(obj, p, mode); ++} ++ ++ ++/* ++** Try to convert a 'for' limit to an integer, preserving the semantics ++** of the loop. Return true if the loop must not run; otherwise, '*p' ++** gets the integer limit. ++** (The following explanation assumes a positive step; it is valid for ++** negative steps mutatis mutandis.) ++** If the limit is an integer or can be converted to an integer, ++** rounding down, that is the limit. ++** Otherwise, check whether the limit can be converted to a float. If ++** the float is too large, clip it to LUA_MAXINTEGER. If the float ++** is too negative, the loop should not run, because any initial ++** integer value is greater than such limit; so, the function returns ++** true to signal that. (For this latter case, no integer limit would be ++** correct; even a limit of LUA_MININTEGER would run the loop once for ++** an initial value equal to LUA_MININTEGER.) ++*/ ++static int forlimit (lua_State *L, lua_Integer init, const TValue *lim, ++ lua_Integer *p, lua_Integer step) { ++ if (!luaV_tointeger(lim, p, (step < 0 ? F2Iceil : F2Ifloor))) { ++ /* not coercible to in integer */ ++ lua_Number flim; /* try to convert to float */ ++ if (!tonumber(lim, &flim)) /* cannot convert to float? */ ++ luaG_forerror(L, lim, "limit"); ++ /* else 'flim' is a float out of integer bounds */ ++ if (luai_numlt(0, flim)) { /* if it is positive, it is too large */ ++ if (step < 0) return 1; /* initial value must be less than it */ ++ *p = LUA_MAXINTEGER; /* truncate */ ++ } ++ else { /* it is less than min integer */ ++ if (step > 0) return 1; /* initial value must be greater than it */ ++ *p = LUA_MININTEGER; /* truncate */ ++ } ++ } ++ return (step > 0 ? init > *p : init < *p); /* not to run? */ ++} ++ ++ ++/* ++** Prepare a numerical for loop (opcode OP_FORPREP). ++** Return true to skip the loop. Otherwise, ++** after preparation, stack will be as follows: ++** ra : internal index (safe copy of the control variable) ++** ra + 1 : loop counter (integer loops) or limit (float loops) ++** ra + 2 : step ++** ra + 3 : control variable ++*/ ++static int forprep (lua_State *L, StkId ra) { ++ TValue *pinit = s2v(ra); ++ TValue *plimit = s2v(ra + 1); ++ TValue *pstep = s2v(ra + 2); ++ if (ttisinteger(pinit) && ttisinteger(pstep)) { /* integer loop? */ ++ lua_Integer init = ivalue(pinit); ++ lua_Integer step = ivalue(pstep); ++ lua_Integer limit; ++ if (step == 0) ++ luaG_runerror(L, "'for' step is zero"); ++ setivalue(s2v(ra + 3), init); /* control variable */ ++ if (forlimit(L, init, plimit, &limit, step)) ++ return 1; /* skip the loop */ ++ else { /* prepare loop counter */ ++ lua_Unsigned count; ++ if (step > 0) { /* ascending loop? */ ++ count = l_castS2U(limit) - l_castS2U(init); ++ if (step != 1) /* avoid division in the too common case */ ++ count /= l_castS2U(step); ++ } ++ else { /* step < 0; descending loop */ ++ count = l_castS2U(init) - l_castS2U(limit); ++ /* 'step+1' avoids negating 'mininteger' */ ++ count /= l_castS2U(-(step + 1)) + 1u; ++ } ++ /* store the counter in place of the limit (which won't be ++ needed anymore) */ ++ setivalue(plimit, l_castU2S(count)); ++ } ++ } ++ else { /* try making all values floats */ ++ lua_Number init; lua_Number limit; lua_Number step; ++ if (l_unlikely(!tonumber(plimit, &limit))) ++ luaG_forerror(L, plimit, "limit"); ++ if (l_unlikely(!tonumber(pstep, &step))) ++ luaG_forerror(L, pstep, "step"); ++ if (l_unlikely(!tonumber(pinit, &init))) ++ luaG_forerror(L, pinit, "initial value"); ++ if (step == 0) ++ luaG_runerror(L, "'for' step is zero"); ++ if (luai_numlt(0, step) ? luai_numlt(limit, init) ++ : luai_numlt(init, limit)) ++ return 1; /* skip the loop */ ++ else { ++ /* make sure internal values are all floats */ ++ setfltvalue(plimit, limit); ++ setfltvalue(pstep, step); ++ setfltvalue(s2v(ra), init); /* internal index */ ++ setfltvalue(s2v(ra + 3), init); /* control variable */ ++ } ++ } ++ return 0; ++} ++ ++ ++/* ++** Execute a step of a float numerical for loop, returning ++** true iff the loop must continue. (The integer case is ++** written online with opcode OP_FORLOOP, for performance.) ++*/ ++static int floatforloop (StkId ra) { ++ lua_Number step = fltvalue(s2v(ra + 2)); ++ lua_Number limit = fltvalue(s2v(ra + 1)); ++ lua_Number idx = fltvalue(s2v(ra)); /* internal index */ ++ idx = luai_numadd(L, idx, step); /* increment index */ ++ if (luai_numlt(0, step) ? luai_numle(idx, limit) ++ : luai_numle(limit, idx)) { ++ chgfltvalue(s2v(ra), idx); /* update internal index */ ++ setfltvalue(s2v(ra + 3), idx); /* and control variable */ ++ return 1; /* jump back */ ++ } ++ else ++ return 0; /* finish the loop */ ++} ++ ++ ++/* ++** Finish the table access 'val = t[key]'. ++** if 'slot' is NULL, 't' is not a table; otherwise, 'slot' points to ++** t[k] entry (which must be empty). ++*/ ++void luaV_finishget (lua_State *L, const TValue *t, TValue *key, StkId val, ++ const TValue *slot) { ++ int loop; /* counter to avoid infinite loops */ ++ const TValue *tm; /* metamethod */ ++ for (loop = 0; loop < MAXTAGLOOP; loop++) { ++ if (slot == NULL) { /* 't' is not a table? */ ++ lua_assert(!ttistable(t)); ++ tm = luaT_gettmbyobj(L, t, TM_INDEX); ++ if (l_unlikely(notm(tm))) ++ luaG_typeerror(L, t, "index"); /* no metamethod */ ++ /* else will try the metamethod */ ++ } ++ else { /* 't' is a table */ ++ lua_assert(isempty(slot)); ++ tm = fasttm(L, hvalue(t)->metatable, TM_INDEX); /* table's metamethod */ ++ if (tm == NULL) { /* no metamethod? */ ++ setnilvalue(s2v(val)); /* result is nil */ ++ return; ++ } ++ /* else will try the metamethod */ ++ } ++ if (ttisfunction(tm)) { /* is metamethod a function? */ ++ luaT_callTMres(L, tm, t, key, val); /* call it */ ++ return; ++ } ++ t = tm; /* else try to access 'tm[key]' */ ++ if (luaV_fastget(L, t, key, slot, luaH_get)) { /* fast track? */ ++ setobj2s(L, val, slot); /* done */ ++ return; ++ } ++ /* else repeat (tail call 'luaV_finishget') */ ++ } ++ luaG_runerror(L, "'__index' chain too long; possible loop"); ++} ++ ++ ++/* ++** Finish a table assignment 't[key] = val'. ++** If 'slot' is NULL, 't' is not a table. Otherwise, 'slot' points ++** to the entry 't[key]', or to a value with an absent key if there ++** is no such entry. (The value at 'slot' must be empty, otherwise ++** 'luaV_fastget' would have done the job.) ++*/ ++void luaV_finishset (lua_State *L, const TValue *t, TValue *key, ++ TValue *val, const TValue *slot) { ++ int loop; /* counter to avoid infinite loops */ ++ for (loop = 0; loop < MAXTAGLOOP; loop++) { ++ const TValue *tm; /* '__newindex' metamethod */ ++ if (slot != NULL) { /* is 't' a table? */ ++ Table *h = hvalue(t); /* save 't' table */ ++ lua_assert(isempty(slot)); /* slot must be empty */ ++ tm = fasttm(L, h->metatable, TM_NEWINDEX); /* get metamethod */ ++ if (tm == NULL) { /* no metamethod? */ ++ luaH_finishset(L, h, key, slot, val); /* set new value */ ++ invalidateTMcache(h); ++ luaC_barrierback(L, obj2gco(h), val); ++ return; ++ } ++ /* else will try the metamethod */ ++ } ++ else { /* not a table; check metamethod */ ++ tm = luaT_gettmbyobj(L, t, TM_NEWINDEX); ++ if (l_unlikely(notm(tm))) ++ luaG_typeerror(L, t, "index"); ++ } ++ /* try the metamethod */ ++ if (ttisfunction(tm)) { ++ luaT_callTM(L, tm, t, key, val); ++ return; ++ } ++ t = tm; /* else repeat assignment over 'tm' */ ++ if (luaV_fastget(L, t, key, slot, luaH_get)) { ++ luaV_finishfastset(L, t, slot, val); ++ return; /* done */ ++ } ++ /* else 'return luaV_finishset(L, t, key, val, slot)' (loop) */ ++ } ++ luaG_runerror(L, "'__newindex' chain too long; possible loop"); ++} ++ ++ ++/* ++** Compare two strings 'ls' x 'rs', returning an integer less-equal- ++** -greater than zero if 'ls' is less-equal-greater than 'rs'. ++** The code is a little tricky because it allows '\0' in the strings ++** and it uses 'strcoll' (to respect locales) for each segments ++** of the strings. ++*/ ++static int l_strcmp (const TString *ls, const TString *rs) { ++ const char *l = getstr(ls); ++ size_t ll = tsslen(ls); ++ const char *r = getstr(rs); ++ size_t lr = tsslen(rs); ++ for (;;) { /* for each segment */ ++ int temp = strcoll(l, r); ++ if (temp != 0) /* not equal? */ ++ return temp; /* done */ ++ else { /* strings are equal up to a '\0' */ ++ size_t len = strlen(l); /* index of first '\0' in both strings */ ++ if (len == lr) /* 'rs' is finished? */ ++ return (len == ll) ? 0 : 1; /* check 'ls' */ ++ else if (len == ll) /* 'ls' is finished? */ ++ return -1; /* 'ls' is less than 'rs' ('rs' is not finished) */ ++ /* both strings longer than 'len'; go on comparing after the '\0' */ ++ len++; ++ l += len; ll -= len; r += len; lr -= len; ++ } ++ } ++} ++ ++ ++/* ++** Check whether integer 'i' is less than float 'f'. If 'i' has an ++** exact representation as a float ('l_intfitsf'), compare numbers as ++** floats. Otherwise, use the equivalence 'i < f <=> i < ceil(f)'. ++** If 'ceil(f)' is out of integer range, either 'f' is greater than ++** all integers or less than all integers. ++** (The test with 'l_intfitsf' is only for performance; the else ++** case is correct for all values, but it is slow due to the conversion ++** from float to int.) ++** When 'f' is NaN, comparisons must result in false. ++*/ ++static int LTintfloat (lua_Integer i, lua_Number f) { ++ if (l_intfitsf(i)) ++ return luai_numlt(cast_num(i), f); /* compare them as floats */ ++ else { /* i < f <=> i < ceil(f) */ ++ lua_Integer fi; ++ if (luaV_flttointeger(f, &fi, F2Iceil)) /* fi = ceil(f) */ ++ return i < fi; /* compare them as integers */ ++ else /* 'f' is either greater or less than all integers */ ++ return f > 0; /* greater? */ ++ } ++} ++ ++ ++/* ++** Check whether integer 'i' is less than or equal to float 'f'. ++** See comments on previous function. ++*/ ++static int LEintfloat (lua_Integer i, lua_Number f) { ++ if (l_intfitsf(i)) ++ return luai_numle(cast_num(i), f); /* compare them as floats */ ++ else { /* i <= f <=> i <= floor(f) */ ++ lua_Integer fi; ++ if (luaV_flttointeger(f, &fi, F2Ifloor)) /* fi = floor(f) */ ++ return i <= fi; /* compare them as integers */ ++ else /* 'f' is either greater or less than all integers */ ++ return f > 0; /* greater? */ ++ } ++} ++ ++ ++/* ++** Check whether float 'f' is less than integer 'i'. ++** See comments on previous function. ++*/ ++static int LTfloatint (lua_Number f, lua_Integer i) { ++ if (l_intfitsf(i)) ++ return luai_numlt(f, cast_num(i)); /* compare them as floats */ ++ else { /* f < i <=> floor(f) < i */ ++ lua_Integer fi; ++ if (luaV_flttointeger(f, &fi, F2Ifloor)) /* fi = floor(f) */ ++ return fi < i; /* compare them as integers */ ++ else /* 'f' is either greater or less than all integers */ ++ return f < 0; /* less? */ ++ } ++} ++ ++ ++/* ++** Check whether float 'f' is less than or equal to integer 'i'. ++** See comments on previous function. ++*/ ++static int LEfloatint (lua_Number f, lua_Integer i) { ++ if (l_intfitsf(i)) ++ return luai_numle(f, cast_num(i)); /* compare them as floats */ ++ else { /* f <= i <=> ceil(f) <= i */ ++ lua_Integer fi; ++ if (luaV_flttointeger(f, &fi, F2Iceil)) /* fi = ceil(f) */ ++ return fi <= i; /* compare them as integers */ ++ else /* 'f' is either greater or less than all integers */ ++ return f < 0; /* less? */ ++ } ++} ++ ++ ++/* ++** Return 'l < r', for numbers. ++*/ ++static int LTnum (const TValue *l, const TValue *r) { ++ lua_assert(ttisnumber(l) && ttisnumber(r)); ++ if (ttisinteger(l)) { ++ lua_Integer li = ivalue(l); ++ if (ttisinteger(r)) ++ return li < ivalue(r); /* both are integers */ ++ else /* 'l' is int and 'r' is float */ ++ return LTintfloat(li, fltvalue(r)); /* l < r ? */ ++ } ++ else { ++ lua_Number lf = fltvalue(l); /* 'l' must be float */ ++ if (ttisfloat(r)) ++ return luai_numlt(lf, fltvalue(r)); /* both are float */ ++ else /* 'l' is float and 'r' is int */ ++ return LTfloatint(lf, ivalue(r)); ++ } ++} ++ ++ ++/* ++** Return 'l <= r', for numbers. ++*/ ++static int LEnum (const TValue *l, const TValue *r) { ++ lua_assert(ttisnumber(l) && ttisnumber(r)); ++ if (ttisinteger(l)) { ++ lua_Integer li = ivalue(l); ++ if (ttisinteger(r)) ++ return li <= ivalue(r); /* both are integers */ ++ else /* 'l' is int and 'r' is float */ ++ return LEintfloat(li, fltvalue(r)); /* l <= r ? */ ++ } ++ else { ++ lua_Number lf = fltvalue(l); /* 'l' must be float */ ++ if (ttisfloat(r)) ++ return luai_numle(lf, fltvalue(r)); /* both are float */ ++ else /* 'l' is float and 'r' is int */ ++ return LEfloatint(lf, ivalue(r)); ++ } ++} ++ ++ ++/* ++** return 'l < r' for non-numbers. ++*/ ++static int lessthanothers (lua_State *L, const TValue *l, const TValue *r) { ++ lua_assert(!ttisnumber(l) || !ttisnumber(r)); ++ if (ttisstring(l) && ttisstring(r)) /* both are strings? */ ++ return l_strcmp(tsvalue(l), tsvalue(r)) < 0; ++ else ++ return luaT_callorderTM(L, l, r, TM_LT); ++} ++ ++ ++/* ++** Main operation less than; return 'l < r'. ++*/ ++int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) { ++ if (ttisnumber(l) && ttisnumber(r)) /* both operands are numbers? */ ++ return LTnum(l, r); ++ else return lessthanothers(L, l, r); ++} ++ ++ ++/* ++** return 'l <= r' for non-numbers. ++*/ ++static int lessequalothers (lua_State *L, const TValue *l, const TValue *r) { ++ lua_assert(!ttisnumber(l) || !ttisnumber(r)); ++ if (ttisstring(l) && ttisstring(r)) /* both are strings? */ ++ return l_strcmp(tsvalue(l), tsvalue(r)) <= 0; ++ else ++ return luaT_callorderTM(L, l, r, TM_LE); ++} ++ ++ ++/* ++** Main operation less than or equal to; return 'l <= r'. ++*/ ++int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) { ++ if (ttisnumber(l) && ttisnumber(r)) /* both operands are numbers? */ ++ return LEnum(l, r); ++ else return lessequalothers(L, l, r); ++} ++ ++ ++/* ++** Main operation for equality of Lua values; return 't1 == t2'. ++** L == NULL means raw equality (no metamethods) ++*/ ++int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2) { ++ const TValue *tm; ++ if (ttypetag(t1) != ttypetag(t2)) { /* not the same variant? */ ++ if (ttype(t1) != ttype(t2) || ttype(t1) != LUA_TNUMBER) ++ return 0; /* only numbers can be equal with different variants */ ++ else { /* two numbers with different variants */ ++ /* One of them is an integer. If the other does not have an ++ integer value, they cannot be equal; otherwise, compare their ++ integer values. */ ++ lua_Integer i1, i2; ++ return (luaV_tointegerns(t1, &i1, F2Ieq) && ++ luaV_tointegerns(t2, &i2, F2Ieq) && ++ i1 == i2); ++ } ++ } ++ /* values have same type and same variant */ ++ switch (ttypetag(t1)) { ++ case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE: return 1; ++ case LUA_VNUMINT: return (ivalue(t1) == ivalue(t2)); ++ case LUA_VNUMFLT: return luai_numeq(fltvalue(t1), fltvalue(t2)); ++ case LUA_VLIGHTUSERDATA: return pvalue(t1) == pvalue(t2); ++ case LUA_VLCF: return fvalue(t1) == fvalue(t2); ++ case LUA_VSHRSTR: return eqshrstr(tsvalue(t1), tsvalue(t2)); ++ case LUA_VLNGSTR: return luaS_eqlngstr(tsvalue(t1), tsvalue(t2)); ++ case LUA_VUSERDATA: { ++ if (uvalue(t1) == uvalue(t2)) return 1; ++ else if (L == NULL) return 0; ++ tm = fasttm(L, uvalue(t1)->metatable, TM_EQ); ++ if (tm == NULL) ++ tm = fasttm(L, uvalue(t2)->metatable, TM_EQ); ++ break; /* will try TM */ ++ } ++ case LUA_VTABLE: { ++ if (hvalue(t1) == hvalue(t2)) return 1; ++ else if (L == NULL) return 0; ++ tm = fasttm(L, hvalue(t1)->metatable, TM_EQ); ++ if (tm == NULL) ++ tm = fasttm(L, hvalue(t2)->metatable, TM_EQ); ++ break; /* will try TM */ ++ } ++ default: ++ return gcvalue(t1) == gcvalue(t2); ++ } ++ if (tm == NULL) /* no TM? */ ++ return 0; /* objects are different */ ++ else { ++ luaT_callTMres(L, tm, t1, t2, L->top); /* call TM */ ++ return !l_isfalse(s2v(L->top)); ++ } ++} ++ ++ ++/* macro used by 'luaV_concat' to ensure that element at 'o' is a string */ ++#define tostring(L,o) \ ++ (ttisstring(o) || (cvt2str(o) && (luaO_tostring(L, o), 1))) ++ ++#define isemptystr(o) (ttisshrstring(o) && tsvalue(o)->shrlen == 0) ++ ++/* copy strings in stack from top - n up to top - 1 to buffer */ ++static void copy2buff (StkId top, int n, char *buff) { ++ size_t tl = 0; /* size already copied */ ++ do { ++ size_t l = vslen(s2v(top - n)); /* length of string being copied */ ++ memcpy(buff + tl, svalue(s2v(top - n)), l * sizeof(char)); ++ tl += l; ++ } while (--n > 0); ++} ++ ++ ++/* ++** Main operation for concatenation: concat 'total' values in the stack, ++** from 'L->top - total' up to 'L->top - 1'. ++*/ ++void luaV_concat (lua_State *L, int total) { ++ if (total == 1) ++ return; /* "all" values already concatenated */ ++ do { ++ StkId top = L->top; ++ int n = 2; /* number of elements handled in this pass (at least 2) */ ++ if (!(ttisstring(s2v(top - 2)) || cvt2str(s2v(top - 2))) || ++ !tostring(L, s2v(top - 1))) ++ luaT_tryconcatTM(L); ++ else if (isemptystr(s2v(top - 1))) /* second operand is empty? */ ++ cast_void(tostring(L, s2v(top - 2))); /* result is first operand */ ++ else if (isemptystr(s2v(top - 2))) { /* first operand is empty string? */ ++ setobjs2s(L, top - 2, top - 1); /* result is second op. */ ++ } ++ else { ++ /* at least two non-empty string values; get as many as possible */ ++ size_t tl = vslen(s2v(top - 1)); ++ TString *ts; ++ /* collect total length and number of strings */ ++ for (n = 1; n < total && tostring(L, s2v(top - n - 1)); n++) { ++ size_t l = vslen(s2v(top - n - 1)); ++ if (l_unlikely(l >= (MAX_SIZE/sizeof(char)) - tl)) ++ luaG_runerror(L, "string length overflow"); ++ tl += l; ++ } ++ if (tl <= LUAI_MAXSHORTLEN) { /* is result a short string? */ ++ char buff[LUAI_MAXSHORTLEN]; ++ copy2buff(top, n, buff); /* copy strings to buffer */ ++ ts = luaS_newlstr(L, buff, tl); ++ } ++ else { /* long string; copy strings directly to final result */ ++ ts = luaS_createlngstrobj(L, tl); ++ copy2buff(top, n, getstr(ts)); ++ } ++ setsvalue2s(L, top - n, ts); /* create result */ ++ } ++ total -= n-1; /* got 'n' strings to create 1 new */ ++ L->top -= n-1; /* popped 'n' strings and pushed one */ ++ } while (total > 1); /* repeat until only 1 result left */ ++} ++ ++ ++/* ++** Main operation 'ra = #rb'. ++*/ ++void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) { ++ const TValue *tm; ++ switch (ttypetag(rb)) { ++ case LUA_VTABLE: { ++ Table *h = hvalue(rb); ++ tm = fasttm(L, h->metatable, TM_LEN); ++ if (tm) break; /* metamethod? break switch to call it */ ++ setivalue(s2v(ra), luaH_getn(h)); /* else primitive len */ ++ return; ++ } ++ case LUA_VSHRSTR: { ++ setivalue(s2v(ra), tsvalue(rb)->shrlen); ++ return; ++ } ++ case LUA_VLNGSTR: { ++ setivalue(s2v(ra), tsvalue(rb)->u.lnglen); ++ return; ++ } ++ default: { /* try metamethod */ ++ tm = luaT_gettmbyobj(L, rb, TM_LEN); ++ if (l_unlikely(notm(tm))) /* no metamethod? */ ++ luaG_typeerror(L, rb, "get length of"); ++ break; ++ } ++ } ++ luaT_callTMres(L, tm, rb, rb, ra); ++} ++ ++ ++/* ++** Integer division; return 'm // n', that is, floor(m/n). ++** C division truncates its result (rounds towards zero). ++** 'floor(q) == trunc(q)' when 'q >= 0' or when 'q' is integer, ++** otherwise 'floor(q) == trunc(q) - 1'. ++*/ ++lua_Integer luaV_idiv (lua_State *L, lua_Integer m, lua_Integer n) { ++ if (l_unlikely(l_castS2U(n) + 1u <= 1u)) { /* special cases: -1 or 0 */ ++ if (n == 0) ++ luaG_runerror(L, "attempt to divide by zero"); ++ return intop(-, 0, m); /* n==-1; avoid overflow with 0x80000...//-1 */ ++ } ++ else { ++ lua_Integer q = m / n; /* perform C division */ ++ if ((m ^ n) < 0 && m % n != 0) /* 'm/n' would be negative non-integer? */ ++ q -= 1; /* correct result for different rounding */ ++ return q; ++ } ++} ++ ++ ++/* ++** Integer modulus; return 'm % n'. (Assume that C '%' with ++** negative operands follows C99 behavior. See previous comment ++** about luaV_idiv.) ++*/ ++lua_Integer luaV_mod (lua_State *L, lua_Integer m, lua_Integer n) { ++ if (l_unlikely(l_castS2U(n) + 1u <= 1u)) { /* special cases: -1 or 0 */ ++ if (n == 0) ++ luaG_runerror(L, "attempt to perform 'n%%0'"); ++ return 0; /* m % -1 == 0; avoid overflow with 0x80000...%-1 */ ++ } ++ else { ++ lua_Integer r = m % n; ++ if (r != 0 && (r ^ n) < 0) /* 'm/n' would be non-integer negative? */ ++ r += n; /* correct result for different rounding */ ++ return r; ++ } ++} ++ ++ ++/* ++** Float modulus ++*/ ++lua_Number luaV_modf (lua_State *L, lua_Number m, lua_Number n) { ++ lua_Number r; ++ luai_nummod(L, m, n, r); ++ return r; ++} ++ ++ ++/* number of bits in an integer */ ++#define NBITS cast_int(sizeof(lua_Integer) * CHAR_BIT) ++ ++/* ++** Shift left operation. (Shift right just negates 'y'.) ++*/ ++#define luaV_shiftr(x,y) luaV_shiftl(x,-(y)) ++ ++lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y) { ++ if (y < 0) { /* shift right? */ ++ if (y <= -NBITS) return 0; ++ else return intop(>>, x, -y); ++ } ++ else { /* shift left */ ++ if (y >= NBITS) return 0; ++ else return intop(<<, x, y); ++ } ++} ++ ++ ++/* ++** create a new Lua closure, push it in the stack, and initialize ++** its upvalues. ++*/ ++static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base, ++ StkId ra) { ++ int nup = p->sizeupvalues; ++ Upvaldesc *uv = p->upvalues; ++ int i; ++ LClosure *ncl = luaF_newLclosure(L, nup); ++ ncl->p = p; ++ setclLvalue2s(L, ra, ncl); /* anchor new closure in stack */ ++ for (i = 0; i < nup; i++) { /* fill in its upvalues */ ++ if (uv[i].instack) /* upvalue refers to local variable? */ ++ ncl->upvals[i] = luaF_findupval(L, base + uv[i].idx); ++ else /* get upvalue from enclosing function */ ++ ncl->upvals[i] = encup[uv[i].idx]; ++ luaC_objbarrier(L, ncl, ncl->upvals[i]); ++ } ++} ++ ++ ++/* ++** finish execution of an opcode interrupted by a yield ++*/ ++void luaV_finishOp (lua_State *L) { ++ CallInfo *ci = L->ci; ++ StkId base = ci->func + 1; ++ Instruction inst = *(ci->u.l.savedpc - 1); /* interrupted instruction */ ++ OpCode op = GET_OPCODE(inst); ++ switch (op) { /* finish its execution */ ++ case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: { ++ setobjs2s(L, base + GETARG_A(*(ci->u.l.savedpc - 2)), --L->top); ++ break; ++ } ++ case OP_UNM: case OP_BNOT: case OP_LEN: ++ case OP_GETTABUP: case OP_GETTABLE: case OP_GETI: ++ case OP_GETFIELD: case OP_SELF: { ++ setobjs2s(L, base + GETARG_A(inst), --L->top); ++ break; ++ } ++ case OP_LT: case OP_LE: ++ case OP_LTI: case OP_LEI: ++ case OP_GTI: case OP_GEI: ++ case OP_EQ: { /* note that 'OP_EQI'/'OP_EQK' cannot yield */ ++ int res = !l_isfalse(s2v(L->top - 1)); ++ L->top--; ++#if defined(LUA_COMPAT_LT_LE) ++ if (ci->callstatus & CIST_LEQ) { /* "<=" using "<" instead? */ ++ ci->callstatus ^= CIST_LEQ; /* clear mark */ ++ res = !res; /* negate result */ ++ } ++#endif ++ lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_JMP); ++ if (res != GETARG_k(inst)) /* condition failed? */ ++ ci->u.l.savedpc++; /* skip jump instruction */ ++ break; ++ } ++ case OP_CONCAT: { ++ StkId top = L->top - 1; /* top when 'luaT_tryconcatTM' was called */ ++ int a = GETARG_A(inst); /* first element to concatenate */ ++ int total = cast_int(top - 1 - (base + a)); /* yet to concatenate */ ++ setobjs2s(L, top - 2, top); /* put TM result in proper position */ ++ L->top = top - 1; /* top is one after last element (at top-2) */ ++ luaV_concat(L, total); /* concat them (may yield again) */ ++ break; ++ } ++ case OP_CLOSE: case OP_RETURN: { /* yielded closing variables */ ++ ci->u.l.savedpc--; /* repeat instruction to close other vars. */ ++ break; ++ } ++ default: { ++ /* only these other opcodes can yield */ ++ lua_assert(op == OP_TFORCALL || op == OP_CALL || ++ op == OP_TAILCALL || op == OP_SETTABUP || op == OP_SETTABLE || ++ op == OP_SETI || op == OP_SETFIELD); ++ break; ++ } ++ } ++} ++ ++ ++ ++ ++/* ++** {================================================================== ++** Macros for arithmetic/bitwise/comparison opcodes in 'luaV_execute' ++** =================================================================== ++*/ ++ ++#define l_addi(L,a,b) intop(+, a, b) ++#define l_subi(L,a,b) intop(-, a, b) ++#define l_muli(L,a,b) intop(*, a, b) ++#define l_band(a,b) intop(&, a, b) ++#define l_bor(a,b) intop(|, a, b) ++#define l_bxor(a,b) intop(^, a, b) ++ ++#define l_lti(a,b) (a < b) ++#define l_lei(a,b) (a <= b) ++#define l_gti(a,b) (a > b) ++#define l_gei(a,b) (a >= b) ++ ++ ++/* ++** Arithmetic operations with immediate operands. 'iop' is the integer ++** operation, 'fop' is the float operation. ++*/ ++#define op_arithI(L,iop,fop) { \ ++ TValue *v1 = vRB(i); \ ++ int imm = GETARG_sC(i); \ ++ if (ttisinteger(v1)) { \ ++ lua_Integer iv1 = ivalue(v1); \ ++ pc++; setivalue(s2v(ra), iop(L, iv1, imm)); \ ++ } \ ++ else if (ttisfloat(v1)) { \ ++ lua_Number nb = fltvalue(v1); \ ++ lua_Number fimm = cast_num(imm); \ ++ pc++; setfltvalue(s2v(ra), fop(L, nb, fimm)); \ ++ }} ++ ++ ++/* ++** Auxiliary function for arithmetic operations over floats and others ++** with two register operands. ++*/ ++#define op_arithf_aux(L,v1,v2,fop) { \ ++ lua_Number n1; lua_Number n2; \ ++ if (tonumberns(v1, n1) && tonumberns(v2, n2)) { \ ++ pc++; setfltvalue(s2v(ra), fop(L, n1, n2)); \ ++ }} ++ ++ ++/* ++** Arithmetic operations over floats and others with register operands. ++*/ ++#define op_arithf(L,fop) { \ ++ TValue *v1 = vRB(i); \ ++ TValue *v2 = vRC(i); \ ++ op_arithf_aux(L, v1, v2, fop); } ++ ++ ++/* ++** Arithmetic operations with K operands for floats. ++*/ ++#define op_arithfK(L,fop) { \ ++ TValue *v1 = vRB(i); \ ++ TValue *v2 = KC(i); lua_assert(ttisnumber(v2)); \ ++ op_arithf_aux(L, v1, v2, fop); } ++ ++ ++/* ++** Arithmetic operations over integers and floats. ++*/ ++#define op_arith_aux(L,v1,v2,iop,fop) { \ ++ if (ttisinteger(v1) && ttisinteger(v2)) { \ ++ lua_Integer i1 = ivalue(v1); lua_Integer i2 = ivalue(v2); \ ++ pc++; setivalue(s2v(ra), iop(L, i1, i2)); \ ++ } \ ++ else op_arithf_aux(L, v1, v2, fop); } ++ ++ ++/* ++** Arithmetic operations with register operands. ++*/ ++#define op_arith(L,iop,fop) { \ ++ TValue *v1 = vRB(i); \ ++ TValue *v2 = vRC(i); \ ++ op_arith_aux(L, v1, v2, iop, fop); } ++ ++ ++/* ++** Arithmetic operations with K operands. ++*/ ++#define op_arithK(L,iop,fop) { \ ++ TValue *v1 = vRB(i); \ ++ TValue *v2 = KC(i); lua_assert(ttisnumber(v2)); \ ++ op_arith_aux(L, v1, v2, iop, fop); } ++ ++ ++/* ++** Bitwise operations with constant operand. ++*/ ++#define op_bitwiseK(L,op) { \ ++ TValue *v1 = vRB(i); \ ++ TValue *v2 = KC(i); \ ++ lua_Integer i1; \ ++ lua_Integer i2 = ivalue(v2); \ ++ if (tointegerns(v1, &i1)) { \ ++ pc++; setivalue(s2v(ra), op(i1, i2)); \ ++ }} ++ ++ ++/* ++** Bitwise operations with register operands. ++*/ ++#define op_bitwise(L,op) { \ ++ TValue *v1 = vRB(i); \ ++ TValue *v2 = vRC(i); \ ++ lua_Integer i1; lua_Integer i2; \ ++ if (tointegerns(v1, &i1) && tointegerns(v2, &i2)) { \ ++ pc++; setivalue(s2v(ra), op(i1, i2)); \ ++ }} ++ ++ ++/* ++** Order operations with register operands. 'opn' actually works ++** for all numbers, but the fast track improves performance for ++** integers. ++*/ ++#define op_order(L,opi,opn,other) { \ ++ int cond; \ ++ TValue *rb = vRB(i); \ ++ if (ttisinteger(s2v(ra)) && ttisinteger(rb)) { \ ++ lua_Integer ia = ivalue(s2v(ra)); \ ++ lua_Integer ib = ivalue(rb); \ ++ cond = opi(ia, ib); \ ++ } \ ++ else if (ttisnumber(s2v(ra)) && ttisnumber(rb)) \ ++ cond = opn(s2v(ra), rb); \ ++ else \ ++ Protect(cond = other(L, s2v(ra), rb)); \ ++ docondjump(); } ++ ++ ++/* ++** Order operations with immediate operand. (Immediate operand is ++** always small enough to have an exact representation as a float.) ++*/ ++#define op_orderI(L,opi,opf,inv,tm) { \ ++ int cond; \ ++ int im = GETARG_sB(i); \ ++ if (ttisinteger(s2v(ra))) \ ++ cond = opi(ivalue(s2v(ra)), im); \ ++ else if (ttisfloat(s2v(ra))) { \ ++ lua_Number fa = fltvalue(s2v(ra)); \ ++ lua_Number fim = cast_num(im); \ ++ cond = opf(fa, fim); \ ++ } \ ++ else { \ ++ int isf = GETARG_C(i); \ ++ Protect(cond = luaT_callorderiTM(L, s2v(ra), im, inv, isf, tm)); \ ++ } \ ++ docondjump(); } ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Function 'luaV_execute': main interpreter loop ++** =================================================================== ++*/ ++ ++/* ++** some macros for common tasks in 'luaV_execute' ++*/ ++ ++ ++#define RA(i) (base+GETARG_A(i)) ++#define RB(i) (base+GETARG_B(i)) ++#define vRB(i) s2v(RB(i)) ++#define KB(i) (k+GETARG_B(i)) ++#define RC(i) (base+GETARG_C(i)) ++#define vRC(i) s2v(RC(i)) ++#define KC(i) (k+GETARG_C(i)) ++#define RKC(i) ((TESTARG_k(i)) ? k + GETARG_C(i) : s2v(base + GETARG_C(i))) ++ ++ ++ ++#define updatetrap(ci) (trap = ci->u.l.trap) ++ ++#define updatebase(ci) (base = ci->func + 1) ++ ++ ++#define updatestack(ci) \ ++ { if (l_unlikely(trap)) { updatebase(ci); ra = RA(i); } } ++ ++ ++/* ++** Execute a jump instruction. The 'updatetrap' allows signals to stop ++** tight loops. (Without it, the local copy of 'trap' could never change.) ++*/ ++#define dojump(ci,i,e) { pc += GETARG_sJ(i) + e; updatetrap(ci); } ++ ++ ++/* for test instructions, execute the jump instruction that follows it */ ++#define donextjump(ci) { Instruction ni = *pc; dojump(ci, ni, 1); } ++ ++/* ++** do a conditional jump: skip next instruction if 'cond' is not what ++** was expected (parameter 'k'), else do next instruction, which must ++** be a jump. ++*/ ++#define docondjump() if (cond != GETARG_k(i)) pc++; else donextjump(ci); ++ ++ ++/* ++** Correct global 'pc'. ++*/ ++#define savepc(L) (ci->u.l.savedpc = pc) ++ ++ ++/* ++** Whenever code can raise errors, the global 'pc' and the global ++** 'top' must be correct to report occasional errors. ++*/ ++#define savestate(L,ci) (savepc(L), L->top = ci->top) ++ ++ ++/* ++** Protect code that, in general, can raise errors, reallocate the ++** stack, and change the hooks. ++*/ ++#define Protect(exp) (savestate(L,ci), (exp), updatetrap(ci)) ++ ++/* special version that does not change the top */ ++#define ProtectNT(exp) (savepc(L), (exp), updatetrap(ci)) ++ ++/* ++** Protect code that can only raise errors. (That is, it cannnot change ++** the stack or hooks.) ++*/ ++#define halfProtect(exp) (savestate(L,ci), (exp)) ++ ++/* 'c' is the limit of live values in the stack */ ++#define checkGC(L,c) \ ++ { luaC_condGC(L, (savepc(L), L->top = (c)), \ ++ updatetrap(ci)); \ ++ luai_threadyield(L); } ++ ++ ++/* fetch an instruction and prepare its execution */ ++#define vmfetch() { \ ++ if (l_unlikely(trap)) { /* stack reallocation or hooks? */ \ ++ trap = luaG_traceexec(L, pc); /* handle hooks */ \ ++ updatebase(ci); /* correct stack */ \ ++ } \ ++ i = *(pc++); \ ++ ra = RA(i); /* WARNING: any stack reallocation invalidates 'ra' */ \ ++} ++ ++#define vmdispatch(o) switch(o) ++#define vmcase(l) case l: ++#define vmbreak break ++ ++ ++void luaV_execute (lua_State *L, CallInfo *ci) { ++ LClosure *cl; ++ TValue *k; ++ StkId base; ++ const Instruction *pc; ++ int trap; ++#if LUA_USE_JUMPTABLE ++#include "ljumptab.h" ++#endif ++ startfunc: ++ trap = L->hookmask; ++ returning: /* trap already set */ ++ cl = clLvalue(s2v(ci->func)); ++ k = cl->p->k; ++ pc = ci->u.l.savedpc; ++ if (l_unlikely(trap)) { ++ if (pc == cl->p->code) { /* first instruction (not resuming)? */ ++ if (cl->p->is_vararg) ++ trap = 0; /* hooks will start after VARARGPREP instruction */ ++ else /* check 'call' hook */ ++ luaD_hookcall(L, ci); ++ } ++ ci->u.l.trap = 1; /* assume trap is on, for now */ ++ } ++ base = ci->func + 1; ++ /* main loop of interpreter */ ++ for (;;) { ++ Instruction i; /* instruction being executed */ ++ StkId ra; /* instruction's A register */ ++ vmfetch(); ++// low-level line tracing for debugging Lua ++// printf("line: %d\n", luaG_getfuncline(cl->p, pcRel(pc, cl->p))); ++ lua_assert(base == ci->func + 1); ++ lua_assert(base <= L->top && L->top < L->stack_last); ++ /* invalidate top for instructions not expecting it */ ++ lua_assert(isIT(i) || (cast_void(L->top = base), 1)); ++ vmdispatch (GET_OPCODE(i)) { ++ vmcase(OP_MOVE) { ++ setobjs2s(L, ra, RB(i)); ++ vmbreak; ++ } ++ vmcase(OP_LOADI) { ++ lua_Integer b = GETARG_sBx(i); ++ setivalue(s2v(ra), b); ++ vmbreak; ++ } ++ vmcase(OP_LOADF) { ++ int b = GETARG_sBx(i); ++ setfltvalue(s2v(ra), cast_num(b)); ++ vmbreak; ++ } ++ vmcase(OP_LOADK) { ++ TValue *rb = k + GETARG_Bx(i); ++ setobj2s(L, ra, rb); ++ vmbreak; ++ } ++ vmcase(OP_LOADKX) { ++ TValue *rb; ++ rb = k + GETARG_Ax(*pc); pc++; ++ setobj2s(L, ra, rb); ++ vmbreak; ++ } ++ vmcase(OP_LOADFALSE) { ++ setbfvalue(s2v(ra)); ++ vmbreak; ++ } ++ vmcase(OP_LFALSESKIP) { ++ setbfvalue(s2v(ra)); ++ pc++; /* skip next instruction */ ++ vmbreak; ++ } ++ vmcase(OP_LOADTRUE) { ++ setbtvalue(s2v(ra)); ++ vmbreak; ++ } ++ vmcase(OP_LOADNIL) { ++ int b = GETARG_B(i); ++ do { ++ setnilvalue(s2v(ra++)); ++ } while (b--); ++ vmbreak; ++ } ++ vmcase(OP_GETUPVAL) { ++ int b = GETARG_B(i); ++ setobj2s(L, ra, cl->upvals[b]->v); ++ vmbreak; ++ } ++ vmcase(OP_SETUPVAL) { ++ UpVal *uv = cl->upvals[GETARG_B(i)]; ++ setobj(L, uv->v, s2v(ra)); ++ luaC_barrier(L, uv, s2v(ra)); ++ vmbreak; ++ } ++ vmcase(OP_GETTABUP) { ++ const TValue *slot; ++ TValue *upval = cl->upvals[GETARG_B(i)]->v; ++ TValue *rc = KC(i); ++ TString *key = tsvalue(rc); /* key must be a string */ ++ if (luaV_fastget(L, upval, key, slot, luaH_getshortstr)) { ++ setobj2s(L, ra, slot); ++ } ++ else ++ Protect(luaV_finishget(L, upval, rc, ra, slot)); ++ vmbreak; ++ } ++ vmcase(OP_GETTABLE) { ++ const TValue *slot; ++ TValue *rb = vRB(i); ++ TValue *rc = vRC(i); ++ lua_Unsigned n; ++ if (ttisinteger(rc) /* fast track for integers? */ ++ ? (cast_void(n = ivalue(rc)), luaV_fastgeti(L, rb, n, slot)) ++ : luaV_fastget(L, rb, rc, slot, luaH_get)) { ++ setobj2s(L, ra, slot); ++ } ++ else ++ Protect(luaV_finishget(L, rb, rc, ra, slot)); ++ vmbreak; ++ } ++ vmcase(OP_GETI) { ++ const TValue *slot; ++ TValue *rb = vRB(i); ++ int c = GETARG_C(i); ++ if (luaV_fastgeti(L, rb, c, slot)) { ++ setobj2s(L, ra, slot); ++ } ++ else { ++ TValue key; ++ setivalue(&key, c); ++ Protect(luaV_finishget(L, rb, &key, ra, slot)); ++ } ++ vmbreak; ++ } ++ vmcase(OP_GETFIELD) { ++ const TValue *slot; ++ TValue *rb = vRB(i); ++ TValue *rc = KC(i); ++ TString *key = tsvalue(rc); /* key must be a string */ ++ if (luaV_fastget(L, rb, key, slot, luaH_getshortstr)) { ++ setobj2s(L, ra, slot); ++ } ++ else ++ Protect(luaV_finishget(L, rb, rc, ra, slot)); ++ vmbreak; ++ } ++ vmcase(OP_SETTABUP) { ++ const TValue *slot; ++ TValue *upval = cl->upvals[GETARG_A(i)]->v; ++ TValue *rb = KB(i); ++ TValue *rc = RKC(i); ++ TString *key = tsvalue(rb); /* key must be a string */ ++ if (luaV_fastget(L, upval, key, slot, luaH_getshortstr)) { ++ luaV_finishfastset(L, upval, slot, rc); ++ } ++ else ++ Protect(luaV_finishset(L, upval, rb, rc, slot)); ++ vmbreak; ++ } ++ vmcase(OP_SETTABLE) { ++ const TValue *slot; ++ TValue *rb = vRB(i); /* key (table is in 'ra') */ ++ TValue *rc = RKC(i); /* value */ ++ lua_Unsigned n; ++ if (ttisinteger(rb) /* fast track for integers? */ ++ ? (cast_void(n = ivalue(rb)), luaV_fastgeti(L, s2v(ra), n, slot)) ++ : luaV_fastget(L, s2v(ra), rb, slot, luaH_get)) { ++ luaV_finishfastset(L, s2v(ra), slot, rc); ++ } ++ else ++ Protect(luaV_finishset(L, s2v(ra), rb, rc, slot)); ++ vmbreak; ++ } ++ vmcase(OP_SETI) { ++ const TValue *slot; ++ int c = GETARG_B(i); ++ TValue *rc = RKC(i); ++ if (luaV_fastgeti(L, s2v(ra), c, slot)) { ++ luaV_finishfastset(L, s2v(ra), slot, rc); ++ } ++ else { ++ TValue key; ++ setivalue(&key, c); ++ Protect(luaV_finishset(L, s2v(ra), &key, rc, slot)); ++ } ++ vmbreak; ++ } ++ vmcase(OP_SETFIELD) { ++ const TValue *slot; ++ TValue *rb = KB(i); ++ TValue *rc = RKC(i); ++ TString *key = tsvalue(rb); /* key must be a string */ ++ if (luaV_fastget(L, s2v(ra), key, slot, luaH_getshortstr)) { ++ luaV_finishfastset(L, s2v(ra), slot, rc); ++ } ++ else ++ Protect(luaV_finishset(L, s2v(ra), rb, rc, slot)); ++ vmbreak; ++ } ++ vmcase(OP_NEWTABLE) { ++ int b = GETARG_B(i); /* log2(hash size) + 1 */ ++ int c = GETARG_C(i); /* array size */ ++ Table *t; ++ if (b > 0) ++ b = 1 << (b - 1); /* size is 2^(b - 1) */ ++ lua_assert((!TESTARG_k(i)) == (GETARG_Ax(*pc) == 0)); ++ if (TESTARG_k(i)) /* non-zero extra argument? */ ++ c += GETARG_Ax(*pc) * (MAXARG_C + 1); /* add it to size */ ++ pc++; /* skip extra argument */ ++ L->top = ra + 1; /* correct top in case of emergency GC */ ++ t = luaH_new(L); /* memory allocation */ ++ sethvalue2s(L, ra, t); ++ if (b != 0 || c != 0) ++ luaH_resize(L, t, c, b); /* idem */ ++ checkGC(L, ra + 1); ++ vmbreak; ++ } ++ vmcase(OP_SELF) { ++ const TValue *slot; ++ TValue *rb = vRB(i); ++ TValue *rc = RKC(i); ++ TString *key = tsvalue(rc); /* key must be a string */ ++ setobj2s(L, ra + 1, rb); ++ if (luaV_fastget(L, rb, key, slot, luaH_getstr)) { ++ setobj2s(L, ra, slot); ++ } ++ else ++ Protect(luaV_finishget(L, rb, rc, ra, slot)); ++ vmbreak; ++ } ++ vmcase(OP_ADDI) { ++ op_arithI(L, l_addi, luai_numadd); ++ vmbreak; ++ } ++ vmcase(OP_ADDK) { ++ op_arithK(L, l_addi, luai_numadd); ++ vmbreak; ++ } ++ vmcase(OP_SUBK) { ++ op_arithK(L, l_subi, luai_numsub); ++ vmbreak; ++ } ++ vmcase(OP_MULK) { ++ op_arithK(L, l_muli, luai_nummul); ++ vmbreak; ++ } ++ vmcase(OP_MODK) { ++ op_arithK(L, luaV_mod, luaV_modf); ++ vmbreak; ++ } ++ vmcase(OP_POWK) { ++ op_arithfK(L, luai_numpow); ++ vmbreak; ++ } ++ vmcase(OP_DIVK) { ++ op_arithfK(L, luai_numdiv); ++ vmbreak; ++ } ++ vmcase(OP_IDIVK) { ++ op_arithK(L, luaV_idiv, luai_numidiv); ++ vmbreak; ++ } ++ vmcase(OP_BANDK) { ++ op_bitwiseK(L, l_band); ++ vmbreak; ++ } ++ vmcase(OP_BORK) { ++ op_bitwiseK(L, l_bor); ++ vmbreak; ++ } ++ vmcase(OP_BXORK) { ++ op_bitwiseK(L, l_bxor); ++ vmbreak; ++ } ++ vmcase(OP_SHRI) { ++ TValue *rb = vRB(i); ++ int ic = GETARG_sC(i); ++ lua_Integer ib; ++ if (tointegerns(rb, &ib)) { ++ pc++; setivalue(s2v(ra), luaV_shiftl(ib, -ic)); ++ } ++ vmbreak; ++ } ++ vmcase(OP_SHLI) { ++ TValue *rb = vRB(i); ++ int ic = GETARG_sC(i); ++ lua_Integer ib; ++ if (tointegerns(rb, &ib)) { ++ pc++; setivalue(s2v(ra), luaV_shiftl(ic, ib)); ++ } ++ vmbreak; ++ } ++ vmcase(OP_ADD) { ++ op_arith(L, l_addi, luai_numadd); ++ vmbreak; ++ } ++ vmcase(OP_SUB) { ++ op_arith(L, l_subi, luai_numsub); ++ vmbreak; ++ } ++ vmcase(OP_MUL) { ++ op_arith(L, l_muli, luai_nummul); ++ vmbreak; ++ } ++ vmcase(OP_MOD) { ++ op_arith(L, luaV_mod, luaV_modf); ++ vmbreak; ++ } ++ vmcase(OP_POW) { ++ op_arithf(L, luai_numpow); ++ vmbreak; ++ } ++ vmcase(OP_DIV) { /* float division (always with floats) */ ++ op_arithf(L, luai_numdiv); ++ vmbreak; ++ } ++ vmcase(OP_IDIV) { /* floor division */ ++ op_arith(L, luaV_idiv, luai_numidiv); ++ vmbreak; ++ } ++ vmcase(OP_BAND) { ++ op_bitwise(L, l_band); ++ vmbreak; ++ } ++ vmcase(OP_BOR) { ++ op_bitwise(L, l_bor); ++ vmbreak; ++ } ++ vmcase(OP_BXOR) { ++ op_bitwise(L, l_bxor); ++ vmbreak; ++ } ++ vmcase(OP_SHR) { ++ op_bitwise(L, luaV_shiftr); ++ vmbreak; ++ } ++ vmcase(OP_SHL) { ++ op_bitwise(L, luaV_shiftl); ++ vmbreak; ++ } ++ vmcase(OP_MMBIN) { ++ Instruction pi = *(pc - 2); /* original arith. expression */ ++ TValue *rb = vRB(i); ++ TMS tm = (TMS)GETARG_C(i); ++ StkId result = RA(pi); ++ lua_assert(OP_ADD <= GET_OPCODE(pi) && GET_OPCODE(pi) <= OP_SHR); ++ Protect(luaT_trybinTM(L, s2v(ra), rb, result, tm)); ++ vmbreak; ++ } ++ vmcase(OP_MMBINI) { ++ Instruction pi = *(pc - 2); /* original arith. expression */ ++ int imm = GETARG_sB(i); ++ TMS tm = (TMS)GETARG_C(i); ++ int flip = GETARG_k(i); ++ StkId result = RA(pi); ++ Protect(luaT_trybiniTM(L, s2v(ra), imm, flip, result, tm)); ++ vmbreak; ++ } ++ vmcase(OP_MMBINK) { ++ Instruction pi = *(pc - 2); /* original arith. expression */ ++ TValue *imm = KB(i); ++ TMS tm = (TMS)GETARG_C(i); ++ int flip = GETARG_k(i); ++ StkId result = RA(pi); ++ Protect(luaT_trybinassocTM(L, s2v(ra), imm, flip, result, tm)); ++ vmbreak; ++ } ++ vmcase(OP_UNM) { ++ TValue *rb = vRB(i); ++ lua_Number nb; ++ if (ttisinteger(rb)) { ++ lua_Integer ib = ivalue(rb); ++ setivalue(s2v(ra), intop(-, 0, ib)); ++ } ++ else if (tonumberns(rb, nb)) { ++ setfltvalue(s2v(ra), luai_numunm(L, nb)); ++ } ++ else ++ Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM)); ++ vmbreak; ++ } ++ vmcase(OP_BNOT) { ++ TValue *rb = vRB(i); ++ lua_Integer ib; ++ if (tointegerns(rb, &ib)) { ++ setivalue(s2v(ra), intop(^, ~l_castS2U(0), ib)); ++ } ++ else ++ Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT)); ++ vmbreak; ++ } ++ vmcase(OP_NOT) { ++ TValue *rb = vRB(i); ++ if (l_isfalse(rb)) ++ setbtvalue(s2v(ra)); ++ else ++ setbfvalue(s2v(ra)); ++ vmbreak; ++ } ++ vmcase(OP_LEN) { ++ Protect(luaV_objlen(L, ra, vRB(i))); ++ vmbreak; ++ } ++ vmcase(OP_CONCAT) { ++ int n = GETARG_B(i); /* number of elements to concatenate */ ++ L->top = ra + n; /* mark the end of concat operands */ ++ ProtectNT(luaV_concat(L, n)); ++ checkGC(L, L->top); /* 'luaV_concat' ensures correct top */ ++ vmbreak; ++ } ++ vmcase(OP_CLOSE) { ++ Protect(luaF_close(L, ra, LUA_OK, 1)); ++ vmbreak; ++ } ++ vmcase(OP_TBC) { ++ /* create new to-be-closed upvalue */ ++ halfProtect(luaF_newtbcupval(L, ra)); ++ vmbreak; ++ } ++ vmcase(OP_JMP) { ++ dojump(ci, i, 0); ++ vmbreak; ++ } ++ vmcase(OP_EQ) { ++ int cond; ++ TValue *rb = vRB(i); ++ Protect(cond = luaV_equalobj(L, s2v(ra), rb)); ++ docondjump(); ++ vmbreak; ++ } ++ vmcase(OP_LT) { ++ op_order(L, l_lti, LTnum, lessthanothers); ++ vmbreak; ++ } ++ vmcase(OP_LE) { ++ op_order(L, l_lei, LEnum, lessequalothers); ++ vmbreak; ++ } ++ vmcase(OP_EQK) { ++ TValue *rb = KB(i); ++ /* basic types do not use '__eq'; we can use raw equality */ ++ int cond = luaV_rawequalobj(s2v(ra), rb); ++ docondjump(); ++ vmbreak; ++ } ++ vmcase(OP_EQI) { ++ int cond; ++ int im = GETARG_sB(i); ++ if (ttisinteger(s2v(ra))) ++ cond = (ivalue(s2v(ra)) == im); ++ else if (ttisfloat(s2v(ra))) ++ cond = luai_numeq(fltvalue(s2v(ra)), cast_num(im)); ++ else ++ cond = 0; /* other types cannot be equal to a number */ ++ docondjump(); ++ vmbreak; ++ } ++ vmcase(OP_LTI) { ++ op_orderI(L, l_lti, luai_numlt, 0, TM_LT); ++ vmbreak; ++ } ++ vmcase(OP_LEI) { ++ op_orderI(L, l_lei, luai_numle, 0, TM_LE); ++ vmbreak; ++ } ++ vmcase(OP_GTI) { ++ op_orderI(L, l_gti, luai_numgt, 1, TM_LT); ++ vmbreak; ++ } ++ vmcase(OP_GEI) { ++ op_orderI(L, l_gei, luai_numge, 1, TM_LE); ++ vmbreak; ++ } ++ vmcase(OP_TEST) { ++ int cond = !l_isfalse(s2v(ra)); ++ docondjump(); ++ vmbreak; ++ } ++ vmcase(OP_TESTSET) { ++ TValue *rb = vRB(i); ++ if (l_isfalse(rb) == GETARG_k(i)) ++ pc++; ++ else { ++ setobj2s(L, ra, rb); ++ donextjump(ci); ++ } ++ vmbreak; ++ } ++ vmcase(OP_CALL) { ++ CallInfo *newci; ++ int b = GETARG_B(i); ++ int nresults = GETARG_C(i) - 1; ++ if (b != 0) /* fixed number of arguments? */ ++ L->top = ra + b; /* top signals number of arguments */ ++ /* else previous instruction set top */ ++ savepc(L); /* in case of errors */ ++ if ((newci = luaD_precall(L, ra, nresults)) == NULL) ++ updatetrap(ci); /* C call; nothing else to be done */ ++ else { /* Lua call: run function in this same C frame */ ++ ci = newci; ++ ci->callstatus = 0; /* call re-uses 'luaV_execute' */ ++ goto startfunc; ++ } ++ vmbreak; ++ } ++ vmcase(OP_TAILCALL) { ++ int b = GETARG_B(i); /* number of arguments + 1 (function) */ ++ int nparams1 = GETARG_C(i); ++ /* delta is virtual 'func' - real 'func' (vararg functions) */ ++ int delta = (nparams1) ? ci->u.l.nextraargs + nparams1 : 0; ++ if (b != 0) ++ L->top = ra + b; ++ else /* previous instruction set top */ ++ b = cast_int(L->top - ra); ++ savepc(ci); /* several calls here can raise errors */ ++ if (TESTARG_k(i)) { ++ luaF_closeupval(L, base); /* close upvalues from current call */ ++ lua_assert(L->tbclist < base); /* no pending tbc variables */ ++ lua_assert(base == ci->func + 1); ++ } ++ while (!ttisfunction(s2v(ra))) { /* not a function? */ ++ luaD_tryfuncTM(L, ra); /* try '__call' metamethod */ ++ b++; /* there is now one extra argument */ ++ checkstackGCp(L, 1, ra); ++ } ++ if (!ttisLclosure(s2v(ra))) { /* C function? */ ++ luaD_precall(L, ra, LUA_MULTRET); /* call it */ ++ updatetrap(ci); ++ updatestack(ci); /* stack may have been relocated */ ++ ci->func -= delta; /* restore 'func' (if vararg) */ ++ luaD_poscall(L, ci, cast_int(L->top - ra)); /* finish caller */ ++ updatetrap(ci); /* 'luaD_poscall' can change hooks */ ++ goto ret; /* caller returns after the tail call */ ++ } ++ ci->func -= delta; /* restore 'func' (if vararg) */ ++ luaD_pretailcall(L, ci, ra, b); /* prepare call frame */ ++ goto startfunc; /* execute the callee */ ++ } ++ vmcase(OP_RETURN) { ++ int n = GETARG_B(i) - 1; /* number of results */ ++ int nparams1 = GETARG_C(i); ++ if (n < 0) /* not fixed? */ ++ n = cast_int(L->top - ra); /* get what is available */ ++ savepc(ci); ++ if (TESTARG_k(i)) { /* may there be open upvalues? */ ++ if (L->top < ci->top) ++ L->top = ci->top; ++ luaF_close(L, base, CLOSEKTOP, 1); ++ updatetrap(ci); ++ updatestack(ci); ++ } ++ if (nparams1) /* vararg function? */ ++ ci->func -= ci->u.l.nextraargs + nparams1; ++ L->top = ra + n; /* set call for 'luaD_poscall' */ ++ luaD_poscall(L, ci, n); ++ updatetrap(ci); /* 'luaD_poscall' can change hooks */ ++ goto ret; ++ } ++ vmcase(OP_RETURN0) { ++ if (l_unlikely(L->hookmask)) { ++ L->top = ra; ++ savepc(ci); ++ luaD_poscall(L, ci, 0); /* no hurry... */ ++ trap = 1; ++ } ++ else { /* do the 'poscall' here */ ++ int nres; ++ L->ci = ci->previous; /* back to caller */ ++ L->top = base - 1; ++ for (nres = ci->nresults; l_unlikely(nres > 0); nres--) ++ setnilvalue(s2v(L->top++)); /* all results are nil */ ++ } ++ goto ret; ++ } ++ vmcase(OP_RETURN1) { ++ if (l_unlikely(L->hookmask)) { ++ L->top = ra + 1; ++ savepc(ci); ++ luaD_poscall(L, ci, 1); /* no hurry... */ ++ trap = 1; ++ } ++ else { /* do the 'poscall' here */ ++ int nres = ci->nresults; ++ L->ci = ci->previous; /* back to caller */ ++ if (nres == 0) ++ L->top = base - 1; /* asked for no results */ ++ else { ++ setobjs2s(L, base - 1, ra); /* at least this result */ ++ L->top = base; ++ for (; l_unlikely(nres > 1); nres--) ++ setnilvalue(s2v(L->top++)); /* complete missing results */ ++ } ++ } ++ ret: /* return from a Lua function */ ++ if (ci->callstatus & CIST_FRESH) ++ return; /* end this frame */ ++ else { ++ ci = ci->previous; ++ goto returning; /* continue running caller in this frame */ ++ } ++ } ++ vmcase(OP_FORLOOP) { ++ if (ttisinteger(s2v(ra + 2))) { /* integer loop? */ ++ lua_Unsigned count = l_castS2U(ivalue(s2v(ra + 1))); ++ if (count > 0) { /* still more iterations? */ ++ lua_Integer step = ivalue(s2v(ra + 2)); ++ lua_Integer idx = ivalue(s2v(ra)); /* internal index */ ++ chgivalue(s2v(ra + 1), count - 1); /* update counter */ ++ idx = intop(+, idx, step); /* add step to index */ ++ chgivalue(s2v(ra), idx); /* update internal index */ ++ setivalue(s2v(ra + 3), idx); /* and control variable */ ++ pc -= GETARG_Bx(i); /* jump back */ ++ } ++ } ++ else if (floatforloop(ra)) /* float loop */ ++ pc -= GETARG_Bx(i); /* jump back */ ++ updatetrap(ci); /* allows a signal to break the loop */ ++ vmbreak; ++ } ++ vmcase(OP_FORPREP) { ++ savestate(L, ci); /* in case of errors */ ++ if (forprep(L, ra)) ++ pc += GETARG_Bx(i) + 1; /* skip the loop */ ++ vmbreak; ++ } ++ vmcase(OP_TFORPREP) { ++ /* create to-be-closed upvalue (if needed) */ ++ halfProtect(luaF_newtbcupval(L, ra + 3)); ++ pc += GETARG_Bx(i); ++ i = *(pc++); /* go to next instruction */ ++ lua_assert(GET_OPCODE(i) == OP_TFORCALL && ra == RA(i)); ++ goto l_tforcall; ++ } ++ vmcase(OP_TFORCALL) { ++ l_tforcall: ++ /* 'ra' has the iterator function, 'ra + 1' has the state, ++ 'ra + 2' has the control variable, and 'ra + 3' has the ++ to-be-closed variable. The call will use the stack after ++ these values (starting at 'ra + 4') ++ */ ++ /* push function, state, and control variable */ ++ memcpy(ra + 4, ra, 3 * sizeof(*ra)); ++ L->top = ra + 4 + 3; ++ ProtectNT(luaD_call(L, ra + 4, GETARG_C(i))); /* do the call */ ++ updatestack(ci); /* stack may have changed */ ++ i = *(pc++); /* go to next instruction */ ++ lua_assert(GET_OPCODE(i) == OP_TFORLOOP && ra == RA(i)); ++ goto l_tforloop; ++ } ++ vmcase(OP_TFORLOOP) { ++ l_tforloop: ++ if (!ttisnil(s2v(ra + 4))) { /* continue loop? */ ++ setobjs2s(L, ra + 2, ra + 4); /* save control variable */ ++ pc -= GETARG_Bx(i); /* jump back */ ++ } ++ vmbreak; ++ } ++ vmcase(OP_SETLIST) { ++ int n = GETARG_B(i); ++ unsigned int last = GETARG_C(i); ++ Table *h = hvalue(s2v(ra)); ++ if (n == 0) ++ n = cast_int(L->top - ra) - 1; /* get up to the top */ ++ else ++ L->top = ci->top; /* correct top in case of emergency GC */ ++ last += n; ++ if (TESTARG_k(i)) { ++ last += GETARG_Ax(*pc) * (MAXARG_C + 1); ++ pc++; ++ } ++ if (last > luaH_realasize(h)) /* needs more space? */ ++ luaH_resizearray(L, h, last); /* preallocate it at once */ ++ for (; n > 0; n--) { ++ TValue *val = s2v(ra + n); ++ setobj2t(L, &h->array[last - 1], val); ++ last--; ++ luaC_barrierback(L, obj2gco(h), val); ++ } ++ vmbreak; ++ } ++ vmcase(OP_CLOSURE) { ++ Proto *p = cl->p->p[GETARG_Bx(i)]; ++ halfProtect(pushclosure(L, p, cl->upvals, base, ra)); ++ checkGC(L, ra + 1); ++ vmbreak; ++ } ++ vmcase(OP_VARARG) { ++ int n = GETARG_C(i) - 1; /* required results */ ++ Protect(luaT_getvarargs(L, ci, ra, n)); ++ vmbreak; ++ } ++ vmcase(OP_VARARGPREP) { ++ ProtectNT(luaT_adjustvarargs(L, GETARG_A(i), ci, cl->p)); ++ if (l_unlikely(trap)) { /* previous "Protect" updated trap */ ++ luaD_hookcall(L, ci); ++ L->oldpc = 1; /* next opcode will be seen as a "new" line */ ++ } ++ updatebase(ci); /* function has new base after adjustment */ ++ vmbreak; ++ } ++ vmcase(OP_EXTRAARG) { ++ lua_assert(0); ++ vmbreak; ++ } ++ } ++ } ++} ++ ++/* }================================================================== */ +diff --git a/src/bin/lua/lvm.h b/src/bin/lua/lvm.h +new file mode 100644 +index 0000000000..1bc16f3a50 +--- /dev/null ++++ b/src/bin/lua/lvm.h +@@ -0,0 +1,136 @@ ++/* ++** $Id: lvm.h $ ++** Lua virtual machine ++** See Copyright Notice in lua.h ++*/ ++ ++#ifndef lvm_h ++#define lvm_h ++ ++ ++#include "ldo.h" ++#include "lobject.h" ++#include "ltm.h" ++ ++ ++#if !defined(LUA_NOCVTN2S) ++#define cvt2str(o) ttisnumber(o) ++#else ++#define cvt2str(o) 0 /* no conversion from numbers to strings */ ++#endif ++ ++ ++#if !defined(LUA_NOCVTS2N) ++#define cvt2num(o) ttisstring(o) ++#else ++#define cvt2num(o) 0 /* no conversion from strings to numbers */ ++#endif ++ ++ ++/* ++** You can define LUA_FLOORN2I if you want to convert floats to integers ++** by flooring them (instead of raising an error if they are not ++** integral values) ++*/ ++#if !defined(LUA_FLOORN2I) ++#define LUA_FLOORN2I F2Ieq ++#endif ++ ++ ++/* ++** Rounding modes for float->integer coercion ++ */ ++typedef enum { ++ F2Ieq, /* no rounding; accepts only integral values */ ++ F2Ifloor, /* takes the floor of the number */ ++ F2Iceil /* takes the ceil of the number */ ++} F2Imod; ++ ++ ++/* convert an object to a float (including string coercion) */ ++#define tonumber(o,n) \ ++ (ttisfloat(o) ? (*(n) = fltvalue(o), 1) : luaV_tonumber_(o,n)) ++ ++ ++/* convert an object to a float (without string coercion) */ ++#define tonumberns(o,n) \ ++ (ttisfloat(o) ? ((n) = fltvalue(o), 1) : \ ++ (ttisinteger(o) ? ((n) = cast_num(ivalue(o)), 1) : 0)) ++ ++ ++/* convert an object to an integer (including string coercion) */ ++#define tointeger(o,i) \ ++ (l_likely(ttisinteger(o)) ? (*(i) = ivalue(o), 1) \ ++ : luaV_tointeger(o,i,LUA_FLOORN2I)) ++ ++ ++/* convert an object to an integer (without string coercion) */ ++#define tointegerns(o,i) \ ++ (l_likely(ttisinteger(o)) ? (*(i) = ivalue(o), 1) \ ++ : luaV_tointegerns(o,i,LUA_FLOORN2I)) ++ ++ ++#define intop(op,v1,v2) l_castU2S(l_castS2U(v1) op l_castS2U(v2)) ++ ++#define luaV_rawequalobj(t1,t2) luaV_equalobj(NULL,t1,t2) ++ ++ ++/* ++** fast track for 'gettable': if 't' is a table and 't[k]' is present, ++** return 1 with 'slot' pointing to 't[k]' (position of final result). ++** Otherwise, return 0 (meaning it will have to check metamethod) ++** with 'slot' pointing to an empty 't[k]' (if 't' is a table) or NULL ++** (otherwise). 'f' is the raw get function to use. ++*/ ++#define luaV_fastget(L,t,k,slot,f) \ ++ (!ttistable(t) \ ++ ? (slot = NULL, 0) /* not a table; 'slot' is NULL and result is 0 */ \ ++ : (slot = f(hvalue(t), k), /* else, do raw access */ \ ++ !isempty(slot))) /* result not empty? */ ++ ++ ++/* ++** Special case of 'luaV_fastget' for integers, inlining the fast case ++** of 'luaH_getint'. ++*/ ++#define luaV_fastgeti(L,t,k,slot) \ ++ (!ttistable(t) \ ++ ? (slot = NULL, 0) /* not a table; 'slot' is NULL and result is 0 */ \ ++ : (slot = (l_castS2U(k) - 1u < hvalue(t)->alimit) \ ++ ? &hvalue(t)->array[k - 1] : luaH_getint(hvalue(t), k), \ ++ !isempty(slot))) /* result not empty? */ ++ ++ ++/* ++** Finish a fast set operation (when fast get succeeds). In that case, ++** 'slot' points to the place to put the value. ++*/ ++#define luaV_finishfastset(L,t,slot,v) \ ++ { setobj2t(L, cast(TValue *,slot), v); \ ++ luaC_barrierback(L, gcvalue(t), v); } ++ ++ ++ ++ ++LUAI_FUNC int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2); ++LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r); ++LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r); ++LUAI_FUNC int luaV_tonumber_ (const TValue *obj, lua_Number *n); ++LUAI_FUNC int luaV_tointeger (const TValue *obj, lua_Integer *p, F2Imod mode); ++LUAI_FUNC int luaV_tointegerns (const TValue *obj, lua_Integer *p, ++ F2Imod mode); ++LUAI_FUNC int luaV_flttointeger (lua_Number n, lua_Integer *p, F2Imod mode); ++LUAI_FUNC void luaV_finishget (lua_State *L, const TValue *t, TValue *key, ++ StkId val, const TValue *slot); ++LUAI_FUNC void luaV_finishset (lua_State *L, const TValue *t, TValue *key, ++ TValue *val, const TValue *slot); ++LUAI_FUNC void luaV_finishOp (lua_State *L); ++LUAI_FUNC void luaV_execute (lua_State *L, CallInfo *ci); ++LUAI_FUNC void luaV_concat (lua_State *L, int total); ++LUAI_FUNC lua_Integer luaV_idiv (lua_State *L, lua_Integer x, lua_Integer y); ++LUAI_FUNC lua_Integer luaV_mod (lua_State *L, lua_Integer x, lua_Integer y); ++LUAI_FUNC lua_Number luaV_modf (lua_State *L, lua_Number x, lua_Number y); ++LUAI_FUNC lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y); ++LUAI_FUNC void luaV_objlen (lua_State *L, StkId ra, const TValue *rb); ++ ++#endif +diff --git a/src/bin/lua/lzio.c b/src/bin/lua/lzio.c +new file mode 100644 +index 0000000000..cd0a02d5f9 +--- /dev/null ++++ b/src/bin/lua/lzio.c +@@ -0,0 +1,68 @@ ++/* ++** $Id: lzio.c $ ++** Buffered streams ++** See Copyright Notice in lua.h ++*/ ++ ++#define lzio_c ++#define LUA_CORE ++ ++#include "lprefix.h" ++ ++ ++#include ++ ++#include "lua.h" ++ ++#include "llimits.h" ++#include "lmem.h" ++#include "lstate.h" ++#include "lzio.h" ++ ++ ++int luaZ_fill (ZIO *z) { ++ size_t size; ++ lua_State *L = z->L; ++ const char *buff; ++ lua_unlock(L); ++ buff = z->reader(L, z->data, &size); ++ lua_lock(L); ++ if (buff == NULL || size == 0) ++ return EOZ; ++ z->n = size - 1; /* discount char being returned */ ++ z->p = buff; ++ return cast_uchar(*(z->p++)); ++} ++ ++ ++void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) { ++ z->L = L; ++ z->reader = reader; ++ z->data = data; ++ z->n = 0; ++ z->p = NULL; ++} ++ ++ ++/* --------------------------------------------------------------- read --- */ ++size_t luaZ_read (ZIO *z, void *b, size_t n) { ++ while (n) { ++ size_t m; ++ if (z->n == 0) { /* no bytes in buffer? */ ++ if (luaZ_fill(z) == EOZ) /* try to read more */ ++ return n; /* no more input; return number of missing bytes */ ++ else { ++ z->n++; /* luaZ_fill consumed first byte; put it back */ ++ z->p--; ++ } ++ } ++ m = (n <= z->n) ? n : z->n; /* min. between n and z->n */ ++ memcpy(b, z->p, m); ++ z->n -= m; ++ z->p += m; ++ b = (char *)b + m; ++ n -= m; ++ } ++ return 0; ++} ++ +diff --git a/src/bin/lua/lzio.h b/src/bin/lua/lzio.h +new file mode 100644 +index 0000000000..38f397fd28 +--- /dev/null ++++ b/src/bin/lua/lzio.h +@@ -0,0 +1,66 @@ ++/* ++** $Id: lzio.h $ ++** Buffered streams ++** See Copyright Notice in lua.h ++*/ ++ ++ ++#ifndef lzio_h ++#define lzio_h ++ ++#include "lua.h" ++ ++#include "lmem.h" ++ ++ ++#define EOZ (-1) /* end of stream */ ++ ++typedef struct Zio ZIO; ++ ++#define zgetc(z) (((z)->n--)>0 ? cast_uchar(*(z)->p++) : luaZ_fill(z)) ++ ++ ++typedef struct Mbuffer { ++ char *buffer; ++ size_t n; ++ size_t buffsize; ++} Mbuffer; ++ ++#define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->buffsize = 0) ++ ++#define luaZ_buffer(buff) ((buff)->buffer) ++#define luaZ_sizebuffer(buff) ((buff)->buffsize) ++#define luaZ_bufflen(buff) ((buff)->n) ++ ++#define luaZ_buffremove(buff,i) ((buff)->n -= (i)) ++#define luaZ_resetbuffer(buff) ((buff)->n = 0) ++ ++ ++#define luaZ_resizebuffer(L, buff, size) \ ++ ((buff)->buffer = luaM_reallocvchar(L, (buff)->buffer, \ ++ (buff)->buffsize, size), \ ++ (buff)->buffsize = size) ++ ++#define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0) ++ ++ ++LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, ++ void *data); ++LUAI_FUNC size_t luaZ_read (ZIO* z, void *b, size_t n); /* read next n bytes */ ++ ++ ++ ++/* --------- Private Part ------------------ */ ++ ++struct Zio { ++ size_t n; /* bytes still unread */ ++ const char *p; /* current position in buffer */ ++ lua_Reader reader; /* reader function */ ++ void *data; /* additional data */ ++ lua_State *L; /* Lua state (for reader) */ ++}; ++ ++ ++LUAI_FUNC int luaZ_fill (ZIO *z); ++ ++#endif +-- +2.30.2 + diff --git a/patchset-hrev55144/0055-SystemManager-add.patch b/patchset-hrev55144/0055-SystemManager-add.patch new file mode 100644 index 0000000..6a63a02 --- /dev/null +++ b/patchset-hrev55144/0055-SystemManager-add.patch @@ -0,0 +1,2817 @@ +From 03bf4b3e55445dd6269d0bf47e3f4e4c3bf5ce06 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 24 May 2021 04:08:45 +0900 +Subject: SystemManager: add + +Change-Id: Ie23c73a1518e7fec4c0b6347c1a7aa9d916b11dd +--- + src/apps/Jamfile | 1 + + src/apps/systemmanager/Errors.cpp | 26 + + src/apps/systemmanager/Errors.h | 39 + + src/apps/systemmanager/Jamfile | 15 + + src/apps/systemmanager/Old.cpp | 121 +++ + src/apps/systemmanager/StackWindow.cpp | 286 +++++++ + src/apps/systemmanager/StackWindow.h | 28 + + src/apps/systemmanager/SystemManager.cpp | 796 ++++++++++++++++++ + src/apps/systemmanager/SystemManager.rdef | 41 + + src/apps/systemmanager/TeamWindow.cpp | 930 ++++++++++++++++++++++ + src/apps/systemmanager/TeamWindow.h | 54 ++ + src/apps/systemmanager/UIUtils.cpp | 95 +++ + src/apps/systemmanager/UIUtils.h | 59 ++ + src/apps/systemmanager/Utils.cpp | 164 ++++ + src/apps/systemmanager/Utils.h | 29 + + 15 files changed, 2684 insertions(+) + create mode 100644 src/apps/systemmanager/Errors.cpp + create mode 100644 src/apps/systemmanager/Errors.h + create mode 100644 src/apps/systemmanager/Jamfile + create mode 100644 src/apps/systemmanager/Old.cpp + create mode 100644 src/apps/systemmanager/StackWindow.cpp + create mode 100644 src/apps/systemmanager/StackWindow.h + create mode 100644 src/apps/systemmanager/SystemManager.cpp + create mode 100644 src/apps/systemmanager/SystemManager.rdef + create mode 100644 src/apps/systemmanager/TeamWindow.cpp + create mode 100644 src/apps/systemmanager/TeamWindow.h + create mode 100644 src/apps/systemmanager/UIUtils.cpp + create mode 100644 src/apps/systemmanager/UIUtils.h + create mode 100644 src/apps/systemmanager/Utils.cpp + create mode 100644 src/apps/systemmanager/Utils.h + +diff --git a/src/apps/Jamfile b/src/apps/Jamfile +index c883cf7b07..232451f675 100644 +--- a/src/apps/Jamfile ++++ b/src/apps/Jamfile +@@ -60,3 +60,4 @@ HaikuSubInclude tracker ; + HaikuSubInclude tv ; + HaikuSubInclude webpositive ; + HaikuSubInclude workspaces ; ++HaikuSubInclude systemmanager ; +diff --git a/src/apps/systemmanager/Errors.cpp b/src/apps/systemmanager/Errors.cpp +new file mode 100644 +index 0000000000..2168fc0895 +--- /dev/null ++++ b/src/apps/systemmanager/Errors.cpp +@@ -0,0 +1,26 @@ ++#include "Errors.h" ++ ++#include ++ ++#include ++#include ++ ++ ++StatusError::StatusError(status_t res, const char *msg): ++ res(res), msg(msg) ++{} ++ ++void ShowError(const StatusError &err) ++{ ++ BString msg, buf; ++ ++ if (err.msg != NULL) { ++ buf.SetToFormat("%s\n\n", err.msg); ++ msg += buf; ++ } ++ buf.SetToFormat("Error code: 0x%08" B_PRIx32 " (%s).", err.res, strerror(err.res)); ++ msg += buf; ++ ++ BAlert *alert = new BAlert("Error", msg, "OK", NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT); ++ alert->Go(NULL); ++} +diff --git a/src/apps/systemmanager/Errors.h b/src/apps/systemmanager/Errors.h +new file mode 100644 +index 0000000000..769bd588c8 +--- /dev/null ++++ b/src/apps/systemmanager/Errors.h +@@ -0,0 +1,39 @@ ++#ifndef _ERRORS_H_ ++#define _ERRORS_H_ ++ ++#include ++ ++#include ++ ++ ++class StatusError ++{ ++public: ++ status_t res; ++ const char *msg; ++ ++ StatusError(status_t res, const char *msg); ++}; ++ ++void ShowError(const StatusError &err); ++ ++static inline status_t Check(status_t res, const char *msg = NULL, bool fatal = true) ++{ ++ if ((res < B_OK) && fatal) ++ throw StatusError(res, msg); ++ return res; ++} ++ ++static inline status_t CheckErrno(status_t res, const char *msg = NULL, bool fatal = true) ++{ ++ if ((res < 0) && fatal) ++ throw StatusError(errno, msg); ++ return res; ++} ++ ++#define CheckRet(err) {status_t _err = (err); if (_err < B_OK) return _err;} ++ ++#define CheckRetVoid(err) {status_t _err = (err); if (_err < B_OK) return;} ++ ++ ++#endif // _ERRORS_H_ +diff --git a/src/apps/systemmanager/Jamfile b/src/apps/systemmanager/Jamfile +new file mode 100644 +index 0000000000..439e0bd2d9 +--- /dev/null ++++ b/src/apps/systemmanager/Jamfile +@@ -0,0 +1,15 @@ ++SubDir HAIKU_TOP src apps systemmanager ; ++ ++UsePrivateHeaders interface shared ; ++UsePrivateKernelHeaders ; ++ ++Application SystemManager : ++ SystemManager.cpp ++ TeamWindow.cpp ++ StackWindow.cpp ++ Errors.cpp ++ Utils.cpp ++ UIUtils.cpp ++ : be [ TargetLibstdc++ ] debug libcolumnlistview.a ++ : SystemManager.rdef ++; +diff --git a/src/apps/systemmanager/Old.cpp b/src/apps/systemmanager/Old.cpp +new file mode 100644 +index 0000000000..18d3f206b9 +--- /dev/null ++++ b/src/apps/systemmanager/Old.cpp +@@ -0,0 +1,121 @@ ++BLayoutItem *CreateTextControlLayoutItem(BTextControl *view) ++{ ++ BGroupLayout *layout; ++ BLayoutBuilder::Group<>(B_VERTICAL, 0) ++ .GetLayout(&layout) ++ .AddGroup(B_HORIZONTAL, 0) ++ .Add(view->CreateLabelLayoutItem()) ++ .AddGlue() ++ .End() ++ .Add(view->CreateTextViewLayoutItem()) ++ .End(); ++ return layout; ++} ++ ++BLayoutItem *CreateMenuFieldLayoutItem(BMenuField *view) ++{ ++ BGroupLayout *layout; ++ BLayoutBuilder::Group<>(B_VERTICAL, 0) ++ .GetLayout(&layout) ++ .AddGroup(B_HORIZONTAL, 0) ++ .Add(view->CreateLabelLayoutItem()) ++ .AddGlue() ++ .End() ++ .AddStrut(16) ++ .Add(view->CreateMenuBarLayoutItem()) ++ .End(); ++ return layout; ++} ++ ++BBox *NewLabelBox(const char *name, const char *label, BView *content) ++{ ++ BBox *box = new BBox(name); ++ if (label != NULL) ++ box->SetLabel(label); ++ if (content != NULL) ++ box->AddChild(content); ++ return box; ++} ++ ++static BView *NewColorView(const char *name, rgb_color color) ++{ ++ BView *view = new BView(name, B_SUPPORTS_LAYOUT); ++ view->SetViewColor(color); ++ if (color == B_TRANSPARENT_COLOR) ++ view->SetFlags(view->Flags() | B_TRANSPARENT_BACKGROUND); ++ return view; ++} ++ ++static BView *NewInfoView(TeamWindow *wnd) ++{ ++ BView *view = new BView("Info", B_TRANSPARENT_BACKGROUND); ++ view->SetViewColor(B_TRANSPARENT_COLOR); ++ ++ BTextControl *fTeam, *fPort, *fToken; ++ BTextControl *fLeftView, *fTopView, *fRightView, *fBottomView; ++ BMenuField *fMenuField; ++ ++ fTeam = new BTextControl("team", "Team:", "0", NULL); fTeam->SetEnabled(false); ++ fPort = new BTextControl("port", "Port:", "0", NULL); fPort->SetEnabled(false); ++ fToken = new BTextControl("token", "Token:", "0", NULL); fToken->SetEnabled(false); ++ ++ fLeftView = new BTextControl("left", "User:", "0", NULL); ++ fTopView = new BTextControl("top", "Group:", "0", NULL); ++ fRightView = new BTextControl("right", "Right:", "255", NULL); ++ fBottomView = new BTextControl("bottom", "Bottom:", "255", NULL); ++ ++ BMenu *menu = new BPopUpMenu("menu"); ++ menu->AddItem(new BMenuItem("Item 1", NULL)); ++ menu->AddItem(new BMenuItem("Item 2", NULL)); ++ menu->AddItem(new BMenuItem("Item 3", NULL)); ++ menu->AddItem(new BMenuItem("Item 4", NULL)); ++ fMenuField = new BMenuField("menuField", "Menu field:", menu); ++ ++ BLayoutBuilder::Group<>(view, B_VERTICAL, B_USE_SMALL_SPACING) ++ .SetInsets(B_USE_SMALL_SPACING) ++/* ++ .Add( ++ BLayoutBuilder::Group<>(NewLabelBox("frame", "Frame", NULL), B_HORIZONTAL, B_USE_SMALL_SPACING) ++ .SetInsets(padding, 2*padding, padding, padding) ++ .Add(CreateTextControlLayoutItem(fLeftView)) ++ .Add(CreateTextControlLayoutItem(fTopView)) ++ .Add(CreateTextControlLayoutItem(fRightView)) ++ .Add(CreateTextControlLayoutItem(fBottomView)) ++ .View() ++ ) ++*/ ++ .Add( ++ NewLabelBox("box1", NULL, ++ BLayoutBuilder::Group<>(NewColorView("content", B_TRANSPARENT_COLOR), B_HORIZONTAL, B_USE_SMALL_SPACING) ++ .SetInsets(B_USE_SMALL_SPACING) ++ .Add(CreateTextControlLayoutItem(fTeam)) ++ .Add(CreateTextControlLayoutItem(fPort)) ++ .Add(CreateTextControlLayoutItem(fToken)) ++ .View() ++ ) ++ ) ++ ++ .Add( ++ NewLabelBox("frame", "Effective", ++ BLayoutBuilder::Group<>(NewColorView("content", B_TRANSPARENT_COLOR), B_HORIZONTAL, B_USE_SMALL_SPACING) ++ .SetInsets(B_USE_SMALL_SPACING, 0, B_USE_SMALL_SPACING, B_USE_SMALL_SPACING) ++ .Add(CreateTextControlLayoutItem(new BTextControl("euid", "User:", "0", NULL))) ++ .Add(CreateTextControlLayoutItem(new BTextControl("egid", "Group:", "0", NULL))) ++ .View() ++ ) ++ ) ++ .Add( ++ NewLabelBox("frame", "Actual", ++ BLayoutBuilder::Group<>(NewColorView("content", B_TRANSPARENT_COLOR), B_HORIZONTAL, B_USE_SMALL_SPACING) ++ .SetInsets(B_USE_SMALL_SPACING, 0, B_USE_SMALL_SPACING, B_USE_SMALL_SPACING) ++ .Add(CreateTextControlLayoutItem(new BTextControl("uid", "User:", "0", NULL))) ++ .Add(CreateTextControlLayoutItem(new BTextControl("gid", "Group:", "0", NULL))) ++ .View() ++ ) ++ ) ++ .Add(CreateMenuFieldLayoutItem(fMenuField)) ++ .AddGlue() ++ .End(); ++ ++ return view; ++} +diff --git a/src/apps/systemmanager/StackWindow.cpp b/src/apps/systemmanager/StackWindow.cpp +new file mode 100644 +index 0000000000..930d3fd926 +--- /dev/null ++++ b/src/apps/systemmanager/StackWindow.cpp +@@ -0,0 +1,286 @@ ++#include "StackWindow.h" ++ ++#include ++#include ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++ ++#include ++#include ++ ++#include "Errors.h" ++#include "UIUtils.h" ++ ++ ++enum { ++ frameFpCol = 0, ++ frameIpCol, ++ frameImageCol, ++ frameFunctionCol, ++}; ++ ++ ++static char *CppDemangle(const char *abiName) ++{ ++ int status; ++ char *ret = abi::__cxa_demangle(abiName, 0, 0, &status); ++ return ret; ++} ++ ++static void LookupSymbolAddress( ++ StackWindow *wnd, ++ debug_symbol_lookup_context *lookupContext, const void *address, ++ BString &imageStr, BString &symbolStr) ++{ ++ // lookup the symbol ++ void *baseAddress; ++ char symbolName[1024]; ++ char imagePath[B_PATH_NAME_LENGTH], imageNameBuf[B_PATH_NAME_LENGTH], *imageName; ++ bool exactMatch; ++ bool lookupSucceeded = false; ++ if (lookupContext) { ++ status_t error = debug_lookup_symbol_address(lookupContext, address, ++ &baseAddress, symbolName, sizeof(symbolName), imagePath, ++ sizeof(imagePath), &exactMatch); ++ lookupSucceeded = (error == B_OK); ++ } ++ ++ if (lookupSucceeded) { ++ strcpy(imageNameBuf, imagePath); ++ imageName = basename(imageNameBuf); ++ ++ // we were able to look something up ++ if (strlen(symbolName) > 0) { ++ char *demangledName = CppDemangle(symbolName); ++ if (demangledName != NULL) { ++ strcpy(symbolName, demangledName); ++ free(demangledName); ++ } ++ ++ // we even got a symbol ++ imageStr.SetTo(imageName); ++ symbolStr.SetToFormat("%s + %ld%s", ++ symbolName, ++ (addr_t)address - (addr_t)baseAddress, ++ exactMatch ? "" : " (closest symbol)" ++ ); ++ } else { ++ // no symbol: image relative address ++ imageStr.SetTo(imageName); ++ symbolStr.SetToFormat("%ld", (addr_t)address - (addr_t)baseAddress); ++ } ++ ++ } else { ++ // lookup failed: find area containing the IP ++ bool useAreaInfo = false; ++ area_info info; ++ ssize_t cookie = 0; ++ while (get_next_area_info(wnd->fTeam, &cookie, &info) == B_OK) { ++ if ((addr_t)info.address <= (addr_t)address && ++ (addr_t)info.address + info.size > (addr_t)address ++ ) { ++ useAreaInfo = true; ++ break; ++ } ++ } ++ ++ if (useAreaInfo) { ++ imageStr.SetToFormat("", info.name); ++ symbolStr.SetToFormat("%#lx", (addr_t)address - (addr_t)info.address); ++ } else { ++ imageStr.SetTo(""); ++ symbolStr.SetTo(""); ++ } ++ } ++} ++ ++static void WriteStackTrace(StackWindow *wnd) ++{ ++ status_t error; ++ void *ip = NULL, *fp = NULL; ++ ++ error = debug_get_instruction_pointer(&wnd->fDebugContext, wnd->fId, &ip, &fp); ++ ++ debug_symbol_lookup_context *lookupContext = NULL; ++ Check(debug_create_symbol_lookup_context(wnd->fTeam, -1, &lookupContext), "can't create symbol lookup context", false); ++ ++ BString imageStr, symbolStr; ++ LookupSymbolAddress(wnd, lookupContext, ip, imageStr, symbolStr); ++ ++ BRow *row; ++ BString str; ++ ++ row = new BRow(); ++ row->SetField(new Int64Field((addr_t)fp), frameFpCol); ++ row->SetField(new Int64Field((addr_t)ip), frameIpCol); ++ row->SetField(new BStringField(imageStr), frameImageCol); ++ row->SetField(new BStringField(symbolStr), frameFunctionCol); ++ wnd->fView->AddRow(row); ++ ++ for (int32 i = 0; i < 400; i++) { ++ debug_stack_frame_info stackFrameInfo; ++ ++ error = debug_get_stack_frame(&wnd->fDebugContext, fp, &stackFrameInfo); ++ if (error < B_OK) ++ break; ++ ++ ip = stackFrameInfo.return_address; ++ fp = stackFrameInfo.parent_frame; ++ ++ LookupSymbolAddress(wnd, lookupContext, ip, imageStr, symbolStr); ++ ++ row = new BRow(); ++ row->SetField(new Int64Field((addr_t)fp), frameFpCol); ++ row->SetField(new Int64Field((addr_t)ip), frameIpCol); ++ row->SetField(new BStringField(imageStr), frameImageCol); ++ row->SetField(new BStringField(symbolStr), frameFunctionCol); ++ wnd->fView->AddRow(row); ++ ++ if (fp == NULL) ++ break; ++ } ++ ++ if (lookupContext) ++ debug_delete_symbol_lookup_context(lookupContext); ++} ++ ++static status_t DebugThread(void *arg) ++{ ++ StackWindow *wnd = (StackWindow*)arg; ++ status_t res; ++ bool run = true; ++ try { ++ while (run) { ++ int32 code; ++ debug_debugger_message_data message; ++ res = read_port(wnd->fDebuggerPort, &code, &message, sizeof(message)); ++ if (res == B_INTERRUPTED) continue; ++ Check(res, "read port failed"); ++ // printf("debug msg: %d\n", code); ++ switch (code) { ++ case B_DEBUGGER_MESSAGE_THREAD_DEBUGGED: { ++ run = false; ++ break; ++ } ++ } ++ } ++ } catch (StatusError &err) { ++ ShowError(err); ++ return err.res; ++ } ++ return B_OK; ++} ++ ++ ++static void ListFrames(StackWindow *wnd, BColumnListView *view) ++{ ++ thread_info threadInfo; ++ status_t res; ++ ++ Check(get_thread_info(wnd->fId, &threadInfo), "thread not found"); ++ wnd->fTeam = threadInfo.team; ++ ++ wnd->fDebuggerPort = Check(create_port(10, "debugger port")); ++ HandleDeleter portDeleter(wnd->fDebuggerPort); ++ ++ wnd->fNubPort = Check(install_team_debugger(wnd->fTeam, wnd->fDebuggerPort), "can't install debugger"); ++ HandleDeleter teamDebuggerDeleter(wnd->fTeam); ++ ++ Check(init_debug_context(&wnd->fDebugContext, wnd->fTeam, wnd->fNubPort)); ++ CObjectDeleter debugContextDeleter(&wnd->fDebugContext); ++ ++ Check(debug_thread(wnd->fId)); ++ ++ thread_id debugThread = spawn_thread(DebugThread, "debug thread", B_NORMAL_PRIORITY, wnd); ++ wait_for_thread(debugThread, &res); Check(res); ++ ++ WriteStackTrace(wnd); ++} ++ ++static void NewFramesView(StackWindow *wnd) ++{ ++ BColumnListView *view; ++ view = new BColumnListView("Frames", B_NAVIGABLE); ++ view->AddColumn(new HexIntegerColumn("FP", 128, 50, 500, B_ALIGN_RIGHT), frameFpCol); ++ view->AddColumn(new HexIntegerColumn("IP", 128, 50, 500, B_ALIGN_RIGHT), frameIpCol); ++ view->AddColumn(new BStringColumn("Image", 150, 50, 500, B_TRUNCATE_END), frameImageCol); ++ view->AddColumn(new BStringColumn("Function", 512, 50, 1024, B_TRUNCATE_END), frameFunctionCol); ++ wnd->fView = view; ++ ListFrames(wnd, view); ++} ++ ++ ++std::map stacks; ++BLocker stacksLocker; ++ ++void OpenStackWindow(team_id id, BPoint center) ++{ ++ AutoLocker locker(stacksLocker); ++ auto it = stacks.find(id); ++ if (it != stacks.end()) { ++ it->second->Activate(); ++ } else { ++ StackWindow *wnd = new StackWindow(id); ++ stacks[id] = wnd; ++ BRect frame = wnd->Frame(); ++ wnd->MoveTo(center.x - frame.Width()/2, center.y - frame.Height()/2); ++ wnd->Show(); ++ } ++} ++ ++StackWindow::StackWindow(thread_id id): BWindow(BRect(0, 0, 800, 480), "Thread", B_DOCUMENT_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS), ++ fId(id) ++{ ++ BMenuBar *menuBar; ++ ++ BString title; ++ title.SetToFormat("Thread %" B_PRId32, fId); ++ SetTitle(title.String()); ++ ++ menuBar = new BMenuBar("menu", B_ITEMS_IN_ROW, true); ++ BLayoutBuilder::Menu<>(menuBar) ++ .AddMenu(new BMenu("File")) ++ .AddItem(new BMenuItem("Close", new BMessage(B_QUIT_REQUESTED), 'W')) ++ .End() ++ .End() ++ ; ++ ++ try { ++ NewFramesView(this); ++ } catch (StatusError &err) { ++ ShowError(err); ++ PostMessage(B_QUIT_REQUESTED); ++ } ++ ++ BLayoutBuilder::Group<>(this, B_VERTICAL, 0) ++ .Add(menuBar) ++ .AddGroup(B_VERTICAL, 0) ++ .Add(fView) ++ .SetInsets(-1) ++ .End() ++ .End() ++ ; ++} ++ ++StackWindow::~StackWindow() ++{ ++ printf("-StackWindow\n"); ++ AutoLocker locker(stacksLocker); ++ stacks.erase(fId); ++} +diff --git a/src/apps/systemmanager/StackWindow.h b/src/apps/systemmanager/StackWindow.h +new file mode 100644 +index 0000000000..853c1072dd +--- /dev/null ++++ b/src/apps/systemmanager/StackWindow.h +@@ -0,0 +1,28 @@ ++#ifndef _STACKWINDOW_H_ ++#define _STACKWINDOW_H_ ++ ++#include ++#include ++#include ++#include ++ ++class BColumnListView; ++ ++class StackWindow: public BWindow ++{ ++public: ++ BColumnListView *fView; ++ ++ ++ thread_id fId; ++ team_id fTeam; ++ port_id fDebuggerPort, fNubPort; ++ debug_context fDebugContext; ++ ++ StackWindow(thread_id id); ++ ~StackWindow(); ++}; ++ ++void OpenStackWindow(thread_id id, BPoint center); ++ ++#endif // _STACKWINDOW_H_ +diff --git a/src/apps/systemmanager/SystemManager.cpp b/src/apps/systemmanager/SystemManager.cpp +new file mode 100644 +index 0000000000..1111ca42ff +--- /dev/null ++++ b/src/apps/systemmanager/SystemManager.cpp +@@ -0,0 +1,796 @@ ++#include ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++#include ++ ++#include "TeamWindow.h" ++#include "Errors.h" ++#include "Utils.h" ++#include "UIUtils.h" ++ ++enum { ++ invokeMsg = 1, ++ selectMsg, ++ updateMsg, ++ ++ setLayoutMsg, ++ ++ terminateMsg, ++ suspendMsg, ++ resumeMsg, ++ sendSignalMsg, ++ debugMsg, ++ ++ showLocationMsg, ++}; ++ ++enum { ++ nameCol = 0, ++ idCol, ++ parentIdCol, ++ sidCol, ++ gidCol, ++ memSizeCol, ++ memAllocCol, ++ userCol, ++ pathCol, ++}; ++ ++enum { ++ statNameCol = 0, ++ statValueCol, ++}; ++ ++enum ViewLayout { ++ flatLayout = 0, ++ treeLayout = 1, ++ sessionsLayout = 2, ++}; ++ ++ ++struct RowTree ++{ ++ ObjectDeleter next, down; ++ ObjectDeleter row; ++}; ++ ++ ++static void BuildRowTree(ObjectDeleter &tree, BColumnListView *view, BRow *row) ++{ ++ tree.SetTo(new RowTree()); ++ tree->row.SetTo(row); ++ RowTree *last = NULL; ++ ObjectDeleter newNode; ++ int32 count = view->CountRows(row); ++ for (int32 i = 0; i < count; i++) { ++ BuildRowTree(newNode, view, view->RowAt(i, row)); ++ if (last == NULL) { ++ tree->down.SetTo(newNode.Detach()); ++ last = tree->down.Get(); ++ } else { ++ last->next.SetTo(newNode.Detach()); ++ last = last->next.Get(); ++ } ++ } ++} ++ ++static void RemoveRow(BColumnListView *view, BRow *row, ObjectDeleter &tree) ++{ ++ BuildRowTree(tree, view, row); ++ view->RemoveRow(row); ++} ++ ++static void InsertRow(BColumnListView *view, BRow *parent, ObjectDeleter &tree) ++{ ++ if (tree.Get() == NULL) return; ++ ++ BRow *row = tree->row.Detach(); ++ view->AddRow(row, parent); ++ if (parent != NULL) ++ view->ExpandOrCollapse(parent, true); ++ ObjectDeleter list(tree->down.Detach()); ++ while (list.Get() != NULL) { ++ ObjectDeleter next(list->next.Detach()); ++ InsertRow(view, row, list); ++ list.SetTo(next.Detach()); ++ } ++ tree.Unset(); ++} ++ ++static void SetRowParent(BColumnListView *view, BRow *row, BRow *newParent) ++{ ++ BRow *oldParent; ++ view->FindParent(row, &oldParent, NULL); ++ if (newParent != oldParent) { ++ ObjectDeleter tree; ++ RemoveRow(view, row, tree); ++ InsertRow(view, newParent, tree); ++ } ++} ++ ++static BRow *FindIntRow(BColumnListView *view, BRow *parent, int32 val) ++{ ++ BRow *row, *row2; ++ BString name; ++ for (int32 i = 0; i < view->CountRows(parent); i++) { ++ row = view->RowAt(i, parent); ++ if (((BIntegerField*)row->GetField(idCol))->Value() == val) ++ return row; ++ row2 = FindIntRow(view, row, val); ++ if (row2 != NULL) ++ return row2; ++ } ++ return NULL; ++} ++ ++static BRow *FindIntRowList(BList &list, int32 val) ++{ ++ for (int32 i = 0; i < list.CountItems(); i++) { ++ BRow *row = (BRow*)list.ItemAt(i); ++ if (((BIntegerField*)row->GetField(idCol))->Value() == val) ++ return row; ++ } ++ return NULL; ++} ++ ++static void CollectRowList(BList &list, BColumnListView *view, BRow *parent = NULL) ++{ ++ for (int32 i = 0; i < view->CountRows(parent); i++) { ++ BRow *row = view->RowAt(i, parent); ++ list.AddItem(row); ++ CollectRowList(list, view, row); ++ } ++} ++ ++static void RelayoutTeams(BColumnListView *view, ViewLayout layout) ++{ ++ BList list; ++ CollectRowList(list, view); ++ ++ switch (layout) { ++ case flatLayout: { ++ for (int32 i = 0; i < list.CountItems(); i++) { ++ BRow *row = (BRow*)list.ItemAt(i); ++ SetRowParent(view, row, NULL); ++ } ++ break; ++ } ++ case treeLayout: { ++ for (int32 i = 0; i < list.CountItems(); i++) { ++ BRow *row = (BRow*)list.ItemAt(i); ++ BRow *parent = FindIntRowList(list, ((BIntegerField*)row->GetField(parentIdCol))->Value()); ++ SetRowParent(view, row, parent); ++ } ++ break; ++ } ++ case sessionsLayout: { ++ break; ++ } ++ } ++ ++} ++ ++static void GetTeamMemory(size_t &size, size_t &alloc, team_id team) ++{ ++ area_info info; ++ ssize_t cookie = 0; ++ ++ // TODO: limit max enumerated area count to prevent freezes ++ size = 0; alloc = 0; ++ while (get_next_area_info(team, &cookie, &info) >= B_OK) { ++ size += info.size; ++ alloc += info.ram_size; ++ } ++} ++ ++static void ListTeams(BColumnListView *view, ViewLayout layout) { ++ status_t status; ++ team_info info; ++ int32 cookie; ++ BRow *row; ++ cookie = 0; ++ BList prevRows; ++ BString str; ++ ++ CollectRowList(prevRows, view); ++ ++ while (get_next_team_info(&cookie, &info) == B_OK) { ++ int32 uid = -1, gid = -1; ++ KMessage extInfo; ++ if (get_extended_team_info(info.team, B_TEAM_INFO_BASIC, extInfo) >= B_OK) { ++ if (extInfo.FindInt32("uid", &uid) < B_OK) uid = -1; ++ if (extInfo.FindInt32("gid", &gid) < B_OK) gid = -1; ++ } ++ ++ int32 imageCookie = 0; ++ image_info imageInfo; ++ status = get_next_image_info(info.team, &imageCookie, &imageInfo); ++ if (status < B_OK) strcpy(imageInfo.name, ""); ++ BPath path(imageInfo.name); ++ ++ BBitmap* icon = new BBitmap(BRect(0, 0, B_MINI_ICON - 1, B_MINI_ICON - 1), B_RGBA32); ++ BEntry entry; ++ entry_ref ref; ++ if (status == B_OK) { ++ entry.SetTo(imageInfo.name); ++ status = entry.GetRef(&ref); ++ } ++ if (status == B_OK) ++ status = BNodeInfo::GetTrackerIcon(&ref, icon, B_MINI_ICON); ++ if (status != B_OK) { ++ BMimeType genericAppType(B_APP_MIME_TYPE); ++ status = genericAppType.GetIcon(icon, B_MINI_ICON); ++ } ++ ++ row = FindIntRowList(prevRows, info.team); ++ if (row == NULL) { ++ row = new BRow(); ++ view->AddRow(row); ++ } else { ++ prevRows.RemoveItem(row); ++ } ++ row->SetField(new IconStringField(icon, path.Leaf()), nameCol); ++ row->SetField(new BIntegerField(info.team), idCol); ++ row->SetField(new BIntegerField(_kern_process_info(info.team, PARENT_ID)), parentIdCol); ++ row->SetField(new BIntegerField(_kern_process_info(info.team, SESSION_ID)), sidCol); ++ row->SetField(new BIntegerField(_kern_process_info(info.team, GROUP_ID)), gidCol); ++ size_t memSize, memAlloc; ++ GetTeamMemory(memSize, memAlloc, info.team); ++ GetSizeString(str, memSize); row->SetField(new BStringField(str), memSizeCol); ++ GetSizeString(str, memAlloc); row->SetField(new BStringField(str), memAllocCol); ++ GetUserGroupString(str, uid, gid); ++ row->SetField(new BStringField(str), userCol); ++ row->SetField(new BStringField(imageInfo.name), pathCol); ++ } ++ ++ for (int32 i = 0; i < prevRows.CountItems(); i++) { ++ row = (BRow*)prevRows.ItemAt(i); ++ view->RemoveRow(row); ++ delete row; ++ } ++ ++ RelayoutTeams(view, layout); ++ ++#if 0 ++ switch (treeLayout) { ++ case flatLayout: ++ break; ++ case treeLayout: { ++ int32 count = view->CountRows(), i = 0; ++ while (i < count) { ++ row = view->RowAt(i); ++ BRow *parent = FindIntRow(view, NULL, ((BIntegerField*)row->GetField(parentIdCol))->Value()); ++ if (parent != NULL) { ++ SetRowParent(view, row, parent); ++ i = 0; count = view->CountRows(); ++ } else { ++ i++; ++ } ++ } ++ break; ++ } ++ case sessionsLayout: { ++ { ++ int32 count = view->CountRows(), i = 0; ++ while (i < count) { ++ row = view->RowAt(i); ++ int32 gid = ((BIntegerField*)row->GetField(gidCol))->Value(); ++ BRow *parent = FindIntRow(view, NULL, gid); ++ if ((parent != NULL) && (parent != row)) { ++ SetRowParent(view, row, parent); ++ i = 0; count = view->CountRows(); ++ } else { ++ i++; ++ } ++ } ++ } ++ { ++ int32 count = view->CountRows(), i = 0; ++ while (i < count) { ++ row = view->RowAt(i); ++ int32 sid = ((BIntegerField*)row->GetField(sidCol))->Value(); ++ BRow *parent = FindIntRow(view, NULL, sid); ++ if ((parent != NULL) && (parent != row)) { ++ SetRowParent(view, row, parent); ++ i = 0; count = view->CountRows(); ++ } else { ++ i++; ++ } ++ } ++ } ++ break; ++ } ++ } ++#endif ++} ++ ++static BColumnListView* NewTeamsView() ++{ ++ BColumnListView *view; ++ view = new BColumnListView("Teams", B_NAVIGABLE); ++ view->SetInvocationMessage(new BMessage(invokeMsg)); ++ view->AddColumn(new IconStringColumn("Name", 256 - 32, 50, 500, B_TRUNCATE_MIDDLE), nameCol); ++ view->AddColumn(new BIntegerColumn("ID", 64, 32, 128, B_ALIGN_RIGHT), idCol); ++ view->AddColumn(new BIntegerColumn("Parent", 64, 32, 128, B_ALIGN_RIGHT), parentIdCol); ++ view->AddColumn(new BIntegerColumn("Session", 64, 32, 128, B_ALIGN_RIGHT), sidCol); ++ view->AddColumn(new BIntegerColumn("Group", 64, 32, 128, B_ALIGN_RIGHT), gidCol); ++ view->AddColumn(new BStringColumn("Mapped", 64 + 16, 32, 256, B_TRUNCATE_END), memSizeCol); ++ view->AddColumn(new BStringColumn("Alloc", 64 + 16, 32, 256, B_TRUNCATE_END), memAllocCol); ++ view->AddColumn(new BStringColumn("User", 64 + 16, 32, 128, B_TRUNCATE_END), userCol); ++ view->AddColumn(new BStringColumn("Path", 512, 50, 1024, B_TRUNCATE_MIDDLE), pathCol); ++ view->SetColumnVisible(parentIdCol, false); ++ return view; ++} ++ ++ ++static void ListStats(BColumnListView *view) ++{ ++ int32 rowId = 0; ++ BString str; ++ ++ system_info info; ++ ++ if (get_system_info(&info) >= B_OK) { ++ time_t unixTime = info.boot_time/1000000; ++ struct tm *tm = localtime(&unixTime); ++ str.SetToFormat("%04d.%02d.%02d %02d:%02d:%02d.%06d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, (int)(info.boot_time%1000000)); ++ view->RowAt(rowId++)->SetField(new BStringField(str), statValueCol); ++ ++ str.SetToFormat("%" B_PRIu32, info.cpu_count); ++ view->RowAt(rowId++)->SetField(new BStringField(str), statValueCol); ++ ++ GetUsedMaxSize(str, info.used_pages * B_PAGE_SIZE, info.max_pages * B_PAGE_SIZE); ++ view->RowAt(rowId++)->SetField(new BStringField(str), statValueCol); ++ ++ GetSizeString(str, info.cached_pages * B_PAGE_SIZE); ++ view->RowAt(rowId++)->SetField(new BStringField(str), statValueCol); ++ ++ GetSizeString(str, info.block_cache_pages * B_PAGE_SIZE); ++ view->RowAt(rowId++)->SetField(new BStringField(str), statValueCol); ++ ++ GetSizeString(str, info.ignored_pages * B_PAGE_SIZE); ++ view->RowAt(rowId++)->SetField(new BStringField(str), statValueCol); ++ ++ GetSizeString(str, info.needed_memory); ++ view->RowAt(rowId++)->SetField(new BStringField(str), statValueCol); ++ ++ uint64 totalMemory = info.max_pages * B_PAGE_SIZE; ++ GetUsedMaxSize(str, totalMemory - info.free_memory, totalMemory); ++ view->RowAt(rowId++)->SetField(new BStringField(str), statValueCol); ++ ++ GetUsedMaxSize(str, (info.max_swap_pages - info.free_swap_pages) * B_PAGE_SIZE, info.max_swap_pages * B_PAGE_SIZE); ++ view->RowAt(rowId++)->SetField(new BStringField(str), statValueCol); ++ ++ str.SetToFormat("%" B_PRIu32, info.page_faults); ++ view->RowAt(rowId++)->SetField(new BStringField(str), statValueCol); ++ ++ GetUsedMax(str, info.used_sems, info.max_sems); ++ view->RowAt(rowId++)->SetField(new BStringField(str), statValueCol); ++ ++ GetUsedMax(str, info.used_ports, info.max_ports); ++ view->RowAt(rowId++)->SetField(new BStringField(str), statValueCol); ++ ++ GetUsedMax(str, info.used_threads, info.max_threads); ++ view->RowAt(rowId++)->SetField(new BStringField(str), statValueCol); ++ ++ GetUsedMax(str, info.used_teams, info.max_teams); ++ view->RowAt(rowId++)->SetField(new BStringField(str), statValueCol); ++ ++ view->RowAt(rowId++)->SetField(new BStringField(info.kernel_name), statValueCol); ++ ++ str.SetToFormat("%s %s", info.kernel_build_date, info.kernel_build_time); ++ view->RowAt(rowId++)->SetField(new BStringField(str), statValueCol); ++ } ++} ++ ++static void NewInfoRow(BColumnListView *view, const char *name) ++{ ++ BRow *row = new BRow(); ++ row->SetField(new BStringField(name), statNameCol); ++ view->AddRow(row); ++} ++ ++static BColumnListView *NewStatsView() ++{ ++ BColumnListView *view; ++ view = new BColumnListView("Stats", B_NAVIGABLE); ++ view->AddColumn(new BStringColumn("Name", 150, 50, 500, B_TRUNCATE_END), statNameCol); ++ view->AddColumn(new BStringColumn("Value", 256, 50, 1024, B_TRUNCATE_END, B_ALIGN_RIGHT), statValueCol); ++ ++ NewInfoRow(view, "Boot time"); ++ NewInfoRow(view, "CPU count"); ++ NewInfoRow(view, "Pages"); ++ NewInfoRow(view, "Cached pages"); ++ NewInfoRow(view, "Block cache pages"); ++ NewInfoRow(view, "Ignored pages"); ++ NewInfoRow(view, "Needed memory"); ++ NewInfoRow(view, "Memory"); ++ NewInfoRow(view, "Swap pages"); ++ NewInfoRow(view, "Page faults"); ++ NewInfoRow(view, "Semaphores"); ++ NewInfoRow(view, "Ports"); ++ NewInfoRow(view, "Threads"); ++ NewInfoRow(view, "Teams"); ++ NewInfoRow(view, "Kernel name"); ++ NewInfoRow(view, "Kernel build timestamp"); ++ ++ ListStats(view); ++ return view; ++} ++ ++ ++static BMessage *NewSetLayoutMsg(int32 layout) ++{ ++ BMessage *msg = new BMessage(setLayoutMsg); ++ msg->SetInt32("val", layout); ++ return msg; ++} ++ ++class TestWindow: public BWindow ++{ ++private: ++ BTabView *fTabView; ++ BColumnListView *fTeamsView; ++ BColumnListView *fStatsView; ++ ViewLayout fLayout; ++ BMessageRunner fListUpdater; ++ ++public: ++ TestWindow(BRect frame): BWindow(frame, "SystemManager", B_DOCUMENT_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS), ++ fLayout(treeLayout), ++ fListUpdater(BMessenger(this), BMessage(updateMsg), 1000000) ++ { ++ BMenuBar *menuBar; ++ BMenu *signalMenu; ++ BTab *tab; ++ ++ menuBar = new BMenuBar("menu", B_ITEMS_IN_ROW, true); ++ BLayoutBuilder::Menu<>(menuBar) ++/* ++ .AddMenu(new BMenu("File")) ++ .AddItem(new BMenuItem("New", new BMessage('item'), 'N')) ++ .AddItem(new BMenuItem("Open...", new BMessage('item'), 'O')) ++ .AddItem(new BMenuItem("Close", new BMessage(B_QUIT_REQUESTED), 'W')) ++ .AddSeparator() ++ .AddItem(new BMenuItem("Save", new BMessage('item'), 'S')) ++ .AddItem(new BMenuItem("Save as...", new BMessage('item'), 'S', B_SHIFT_KEY)) ++ .AddSeparator() ++ .AddItem(new BMenuItem("Quit", new BMessage(B_QUIT_REQUESTED), 'Q')) ++ .End() ++*/ ++ .AddMenu(new BMenu("View")) ++ .AddMenu(new BMenu("Layout")) ++ .AddItem(new BMenuItem("Flat", NewSetLayoutMsg(flatLayout))) ++ .AddItem(new BMenuItem("Tree", NewSetLayoutMsg(treeLayout))) ++ .AddItem(new BMenuItem("Sessions and groups", NewSetLayoutMsg(sessionsLayout))) ++ .End() ++ .End() ++ .AddMenu(new BMenu("Action")) ++/* ++ .AddItem(new BMenuItem("Update", new BMessage(updateMsg), 'R')) ++ .AddSeparator() ++*/ ++ .AddItem(new BMenuItem("Terminate", new BMessage(terminateMsg), 'T')) ++ .AddItem(new BMenuItem("Suspend", new BMessage(suspendMsg))) ++ .AddItem(new BMenuItem("Resume", new BMessage(resumeMsg))) ++ .AddMenu(signalMenu = new BMenu("Send signal")) ++ .End() ++ .AddItem(new BMenuItem("Debug" B_UTF8_ELLIPSIS, new BMessage(debugMsg))) ++ .AddSeparator() ++ .AddItem(new BMenuItem("Show location", new BMessage(showLocationMsg))) ++ .End() ++ .End() ++ ; ++ ++ for (size_t i = 0; i < sizeof(signals)/sizeof(signals[0]); i++) { ++ BMessage *msg = new BMessage(sendSignalMsg); ++ msg->AddInt32("val", signals[i].val); ++ signalMenu->AddItem(new BMenuItem(signals[i].name, msg)); ++ } ++ ++ fTabView = new BTabView("tab_view", B_WIDTH_FROM_LABEL); ++ fTabView->SetBorder(B_NO_BORDER); ++ ++ //tab = new BTab(); fTabView->AddTab(NewTeamsView("Apps"), tab); ++ tab = new BTab(); fTabView->AddTab(fTeamsView = NewTeamsView(), tab); ++ //tab = new BTab(); fTabView->AddTab(new TestView(BRect(0, 0, -1, -1), "Services", B_FOLLOW_NONE), tab); ++ //tab = new BTab(); fTabView->AddTab(new TestView(BRect(0, 0, -1, -1), "Sockets", B_FOLLOW_NONE), tab); ++ tab = new BTab(); fTabView->AddTab(fStatsView = NewStatsView(), tab); ++ ++ ListTeams(fTeamsView, fLayout); ++ ++ BLayoutBuilder::Group<>(this, B_VERTICAL, 0) ++ .Add(menuBar) ++ .AddGroup(B_VERTICAL, 0) ++ .Add(fTabView) ++ .SetInsets(-1, 0, -1, -1) ++ .End() ++ .End() ++ ; ++ } ++ ++ team_id SelectedTeam(const char **name = NULL) ++ { ++ BRow *row = fTeamsView->CurrentSelection(NULL); ++ if (row == NULL) return -1; ++ if (name != NULL) *name = ((IconStringField*)row->GetField(nameCol))->String(); ++ return ((BIntegerField*)row->GetField(idCol))->Value(); ++ } ++ ++ void MessageReceived(BMessage *msg) ++ { ++ try { ++ switch (msg->what) { ++ case invokeMsg: { ++ team_id team = SelectedTeam(); ++ if (team < B_OK) return; ++ BPoint center((Frame().left + Frame().right)/2, (Frame().top + Frame().bottom)/2); ++ OpenTeamWindow(team, center); ++ return; ++ } ++ case updateMsg: { ++ BTab *tab = fTabView->TabAt(fTabView->Selection()); ++ if (tab == NULL) return; ++ BView *view = tab->View(); ++ if (view == fTeamsView) ++ ListTeams(fTeamsView, fLayout); ++ else if (view == fStatsView) ++ ListStats(fStatsView); ++ return; ++ } ++ case setLayoutMsg: { ++ int32 layout; ++ CheckRetVoid(msg->FindInt32("val", &layout)); ++ fLayout = (ViewLayout)layout; ++ RelayoutTeams(fTeamsView, fLayout); ++ return; ++ } ++ case terminateMsg: { ++ team_id team; ++ int32 which; ++ BInvoker *invoker = NULL; ++ if (msg->FindInt32("which", &which) < B_OK) { ++ const char *name; ++ team = SelectedTeam(&name); ++ if (team < B_OK) return; ++ Check(msg->AddInt32("team", team)); ++ BString str; ++ str.SetToFormat("Are you sure you want to terminate team \"%s\" (%" B_PRId32 ")?", name, team); ++ BAlert *alert = new BAlert("SystemManager", str, "No", "Yes", NULL, B_WIDTH_AS_USUAL, B_WARNING_ALERT); ++ invoker = new BInvoker(new BMessage(*msg), this); ++ invoker->Message()->SetPointer("invoker", invoker); ++ alert->Go(invoker); ++ return; ++ } ++ if (msg->FindPointer("invoker", &(void*&)invoker) >= B_OK) { ++ delete invoker; invoker = NULL; ++ } ++ if (which != 1) return; ++ CheckRetVoid(msg->FindInt32("team", &team)); ++ if (team < B_OK) return; ++ Check(kill_team(team), "Can't terminate team."); ++ return; ++ } ++ case suspendMsg: { ++ team_id team = SelectedTeam(); ++ if (team < B_OK) return; ++ CheckErrno(kill(team, SIGSTOP), "Can't suspend team."); ++ return; ++ } ++ case resumeMsg: { ++ team_id team = SelectedTeam(); ++ if (team < B_OK) return; ++ CheckErrno(kill(team, SIGCONT), "Can't resume team."); ++ return; ++ } ++ case sendSignalMsg: { ++ int32 signal; ++ CheckRetVoid(msg->FindInt32("val", &signal)); ++ team_id team = SelectedTeam(); ++ if (team < B_OK) return; ++ CheckErrno(kill(team, signal), "Can't send signal."); ++ return; ++ } ++ case debugMsg: { ++ team_id team = SelectedTeam(); ++ if (team < B_OK) return; ++ BPath debuggerPath; ++ BString teamStr; ++ Check(find_directory(B_SYSTEM_APPS_DIRECTORY, &debuggerPath), "(1)"); ++ Check(debuggerPath.Append("Debugger"), "(2)"); ++ teamStr.SetToFormat("%" B_PRId32, team); ++ int argc = 0; ++ const char *argv[4]; ++ argv[argc++] = debuggerPath.Path(); ++ argv[argc++] = "--team"; ++ argv[argc++] = teamStr.String(); ++ argv[argc] = NULL; ++ thread_id thread = Check(load_image(argc, argv, (const char**)environ), "(3)"); ++ resume_thread(thread); ++ return; ++ } ++ case showLocationMsg: { ++ BRow *row = fTeamsView->CurrentSelection(NULL); ++ if (row == NULL) return; ++ ShowLocation(((BStringField*)row->GetField(pathCol))->String()); ++ } ++ } ++ } catch (StatusError &err) { ++ ShowError(err); ++ } ++ BWindow::MessageReceived(msg); ++ } ++}; ++ ++ ++static property_info gProperties[] = { ++ {"Team", {B_EXECUTE_PROPERTY, 0}, {B_INDEX_SPECIFIER, 0}}, ++ {"Image", {B_EXECUTE_PROPERTY, 0}, {B_INDEX_SPECIFIER, 0}}, ++ {"Thread", {B_EXECUTE_PROPERTY, 0}, {B_INDEX_SPECIFIER, 0}}, ++ {"Area", {B_EXECUTE_PROPERTY, 0}, {B_INDEX_SPECIFIER, 0}}, ++ {"Port", {B_EXECUTE_PROPERTY, 0}, {B_INDEX_SPECIFIER, 0}}, ++ {"Sem", {B_EXECUTE_PROPERTY, 0}, {B_INDEX_SPECIFIER, 0}}, ++ {0} ++}; ++ ++class TestApplication: public BApplication ++{ ++private: ++ BWindow *fWnd; ++ ++public: ++ TestApplication(): BApplication("application/x-vnd.Test-SystemManager") ++ { ++ fWnd = new TestWindow(BRect(0, 0, 640, 480)); ++ fWnd->SetFlags(fWnd->Flags() | B_QUIT_ON_WINDOW_CLOSE); ++ fWnd->CenterOnScreen(); ++ fWnd->Show(); ++ } ++ ++ BHandler *ResolveSpecifier(BMessage* message, int32 index, BMessage* specifier, int32 what, const char* property) ++ { ++ printf("TestApplication::ResolveSpecifier()\n"); ++ BPropertyInfo propInfo(gProperties); ++ printf("specifier: "); specifier->PrintToStream(); ++ if (propInfo.FindMatch(message, 0, specifier, what, property) >= 0) ++ return this; ++ return BApplication::ResolveSpecifier(message, index, specifier, what, property); ++ } ++ ++ status_t GetSupportedSuites(BMessage *data) ++ { ++ printf("TestApplication::GetSupportedSuites()\n"); ++ if (data == NULL) return B_BAD_VALUE; ++ CheckRet(data->AddString("suites", "suite/vnd.Test-SystemMangager")); ++ BPropertyInfo propertyInfo(gProperties); ++ CheckRet(data->AddFlat("messages", &propertyInfo)); ++ return BApplication::GetSupportedSuites(data); ++ } ++ ++ status_t HandleScript(BMessage &message, BMessage &reply, int32 index, BMessage &specifier, int32 what, const char* property) ++ { ++ BPropertyInfo propInfo(gProperties); ++ int32 propIdx = propInfo.FindMatch(&message, index, &specifier, what, property); ++ switch (propIdx) { ++ case 0: // Team: Execute ++ case 1: // Image: Execute ++ case 2: // Thread: Execute ++ case 3: // Area: Execute ++ case 4: // Port: Execute ++ case 5: // Sem: Execute ++ switch (what) { ++ case B_INDEX_SPECIFIER: { ++ CheckRet(specifier.FindInt32("index", &index)); ++ BRect frame = fWnd->Frame(); ++ BPoint center((frame.left + frame.right)/2, (frame.top + frame.bottom)/2); ++ switch (propIdx) { ++ case 0: { ++ OpenTeamWindow(index, center); ++ return B_OK; ++ } ++ case 2: { ++ thread_info info; ++ CheckRet(get_thread_info(index, &info)); ++ BWindow *wnd = OpenTeamWindow(info.team, center); ++ BMessage wndMsg(teamWindowShowThreadMsg); ++ wndMsg.AddInt32("val", index); ++ BMessenger(wnd).SendMessage(&wndMsg); ++ return B_OK; ++ } ++ case 3: { ++ area_info info; ++ CheckRet(get_area_info(index, &info)); ++ BWindow *wnd = OpenTeamWindow(info.team, center); ++ BMessage wndMsg(teamWindowShowAreaMsg); ++ wndMsg.AddInt32("val", index); ++ BMessenger(wnd).SendMessage(&wndMsg); ++ return B_OK; ++ } ++ case 4: { ++ port_info info; ++ CheckRet(get_port_info(index, &info)); ++ BWindow *wnd = OpenTeamWindow(info.team, center); ++ BMessage wndMsg(teamWindowShowPortMsg); ++ wndMsg.AddInt32("val", index); ++ BMessenger(wnd).SendMessage(&wndMsg); ++ return B_OK; ++ } ++ case 5: { ++ sem_info info; ++ CheckRet(get_sem_info(index, &info)); ++ BWindow *wnd = OpenTeamWindow(info.team, center); ++ BMessage wndMsg(teamWindowShowSemMsg); ++ wndMsg.AddInt32("val", index); ++ BMessenger(wnd).SendMessage(&wndMsg); ++ return B_OK; ++ } ++ } ++ } ++ } ++ break; ++ } ++ return B_BAD_SCRIPT_SYNTAX; ++ } ++ ++ void MessageReceived(BMessage *msg) ++ { ++ int32 index; ++ BMessage specifier; ++ int32 what; ++ const char* property; ++ ++ if (msg->HasSpecifiers() && msg->GetCurrentSpecifier(&index, &specifier, &what, &property) >= B_OK) { ++ BMessage reply(B_REPLY); ++ status_t res = HandleScript(*msg, reply, index, specifier, what, property); ++ if (res != B_OK) { ++ reply.what = B_MESSAGE_NOT_UNDERSTOOD; ++ reply.AddString("message", strerror(res)); ++ } ++ reply.AddInt32("error", res); ++ msg->SendReply(&reply); ++ return; ++ } ++ ++ switch (msg->what) { ++ case B_SILENT_RELAUNCH: ++ fWnd->Activate(); ++ return; ++ } ++ ++ BApplication::MessageReceived(msg); ++ } ++ ++}; ++ ++ ++int main() ++{ ++ (new TestApplication())->Run(); ++ return 0; ++} +diff --git a/src/apps/systemmanager/SystemManager.rdef b/src/apps/systemmanager/SystemManager.rdef +new file mode 100644 +index 0000000000..df71d766f9 +--- /dev/null ++++ b/src/apps/systemmanager/SystemManager.rdef +@@ -0,0 +1,41 @@ ++resource app_signature "application/x-vnd.Test-SystemManager"; ++ ++resource app_flags B_SINGLE_LAUNCH; ++ ++resource app_version { ++ major = 0, ++ middle = 0, ++ minor = 0, ++ ++ variety = B_APPV_DEVELOPMENT, ++ internal = 0, ++ ++ short_info = "SystemManager", ++ long_info = "List running teams and its objects." ++}; ++ ++resource vector_icon { ++ $"6E6369660E03010000020002023980000000000000004000004BE00008908100" ++ $"010000FFFF01000000020016023CC7EE389BC0BA16573E39B04977C842ADC700" ++ $"FFFFD3020006023C529D3753A2B8966F3D9D084B6044496AAF00474747FFA5A0" ++ $"A002001602BC4E76BC411B3C90DABCA00D47587D4ABA850090FFD40200160238" ++ $"313C3B5CF0BFCD963C7AAC4C13943FCAF901ECFFC3054B04017E020006033E2F" ++ $"99387F17BA42DB3FF5B94A0E32482C90001D1E2C3D454658FF01010102000602" ++ $"3879063B8224BE2CC83B10DB4A1F6F49B894FF9A9A9A00242222020006033C69" ++ $"A60000000000003E186148800049800058F3F3F300D4CECEFFD9D9D902000603" ++ $"3C1F1A33E78CB7ACC03FFE4F48BB3EBD7B6C0078D905818CFF05FF7ADD050200" ++ $"1602349C2E37B5FABA1F6036FC624A3E004B320001D3FF910200160235777837" ++ $"0A67B7E8CE363A844A1D684B45D800F3FF2E0D0A04486050605C51544E04033E" ++ $"5349594856475C49604B5C4E604B0A06262A264C485E5252523030240A04262A" ++ $"4838523030240A044838485E525252300A04262A264C485E48380A04453A4553" ++ $"2844282E0A04B6F9C0F42845282EB701B8EC0A044550455328452AC0F30A0445" ++ $"3A45502A43B701B8EC0408AEBAB6BCBCC32FBD4F2E3930BDA8B9ACC0A5BA9EBC" ++ $"03BB1EBFD937BF0DBD4FC072BCC3C019BDDBC0CB46460204BF23C726BF91C70D" ++ $"BEB5C73FBE9FC87EBE7AC7D9BEC5C922BFAAC97BBF3CC994C018C962C02DC823" ++ $"C053C8C8C008C77F0204BFCEC6FBC042C6E0BF5BC715BF48C85ABF1FC7B3BF71" ++ $"C902C063C95ABFF0C974C0D7C93FC0EAC7FAC113C8A2C0C1C7530E0A07010000" ++ $"0A0101011001178300040A0001021001178400040A020103000A080109000A0B" ++ $"010A1001178120040A030104000A04020506000A090107000A0A0108000A0D01" ++ $"0C0815FF0A0C010B0815FF0A0D010C0A3FEAF70000000000003FEAF7C573B4C2" ++ $"770615FF0A0C010B0A3FEAF70000000000003FEAF7C573B4C2770615FF" ++}; +diff --git a/src/apps/systemmanager/TeamWindow.cpp b/src/apps/systemmanager/TeamWindow.cpp +new file mode 100644 +index 0000000000..d96d4a555c +--- /dev/null ++++ b/src/apps/systemmanager/TeamWindow.cpp +@@ -0,0 +1,930 @@ ++#include "TeamWindow.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++ ++#include ++ ++#include "StackWindow.h" ++#include "Errors.h" ++#include "Utils.h" ++#include "UIUtils.h" ++ ++ ++enum { ++ imageIdCol = 0, ++ imageTextCol, ++ imageDataCol, ++ imageNameCol, ++ imagePathCol, ++}; ++ ++enum { ++ threadIdCol = 0, ++ threadNameCol, ++ threadStateCol, ++ threadPriorityCol, ++ threadSemCol, ++ threadUserTimeCol, ++ threadKernelTimeCol, ++ threadStackBaseCol, ++ threadStackEndCol, ++}; ++ ++enum { ++ areaIdCol = 0, ++ areaNameCol, ++ areaAdrCol, ++ areaSizeCol, ++ areaAllocCol, ++ areaProtCol, ++ areaLockCol, ++}; ++ ++enum { ++ portIdCol = 0, ++ portNameCol, ++ portCapacityCol, ++ portQueuedCol, ++ portTotalCol, ++}; ++ ++enum { ++ semIdCol = 0, ++ semNameCol, ++ semCountCol, ++ semLatestHolderCol, ++}; ++ ++enum { ++ fileNameCol, ++ fileIdCol, ++ fileModeCol, ++ fileDevCol, ++ fileNodeCol, ++ fileDevNameCol, ++ fileVolNameCol, ++ fileFsNameCol ++}; ++ ++enum { ++ infoNameCol = 0, ++ infoValueCol, ++}; ++ ++enum { ++ updateMsg = teamWindowPrivateMsgBase, ++ infoShowWorkDirMsg, ++ imagesShowLocationMsg, ++ threadsInvokeMsg, ++ threadsTerminateMsg, ++ threadsSendSignalMsg, ++ threadsShowSemMsg, ++ threadsShowStackAreaMsg, ++ semsShowThreadMsg, ++}; ++ ++ ++static const char *GetFileName(const char *path) ++{ ++ const char *name = path; ++ for (const char *it = name; *it != '\0'; it++) { ++ if (*it == '/') name = it + 1; ++ } ++ return name; ++} ++ ++static BRow *FindIntRow(BColumnListView *view, int32 col, BRow *parent, int32 val) ++{ ++ BRow *row; ++ BString name; ++ for (int32 i = 0; i < view->CountRows(parent); i++) { ++ row = view->RowAt(i, parent); ++ if (((BIntegerField*)row->GetField(col))->Value() == val) ++ return row; ++ } ++ return NULL; ++} ++ ++ ++//#pragma mark Lists ++ ++static void ListInfo(TeamWindow *wnd, BColumnListView *view) ++{ ++ int32 rowId = 0; ++ int32 int32Val = -1; ++ BString str; ++ const char *strPtr; ++ int32 uid = -1, gid = -1; ++ ++ KMessage extInfo; ++ ++ if (get_extended_team_info(wnd->fId, B_TEAM_INFO_BASIC, extInfo) >= B_OK) { ++ if (extInfo.FindInt32("id", &int32Val) >= B_OK) { ++ str.SetToFormat("%" B_PRId32, int32Val); ++ view->RowAt(rowId++)->SetField(new BStringField(str), infoValueCol); ++ } ++ if (extInfo.FindString("name", &strPtr) >= B_OK) { ++ view->RowAt(rowId++)->SetField(new BStringField(strPtr), infoValueCol); ++ } ++ ++ if (extInfo.FindInt32("process group", &int32Val) >= B_OK) { ++ str.SetToFormat("%" B_PRId32, int32Val); ++ view->RowAt(rowId++)->SetField(new BStringField(str), infoValueCol); ++ } ++ ++ if (extInfo.FindInt32("session", &int32Val) >= B_OK) { ++ str.SetToFormat("%" B_PRId32, int32Val); ++ view->RowAt(rowId++)->SetField(new BStringField(str), infoValueCol); ++ } ++ ++ if (extInfo.FindInt32("uid", &uid) < B_OK) uid = -1; ++ if (extInfo.FindInt32("gid", &gid) < B_OK) gid = -1; ++ GetUserGroupString(str, uid, gid, true); ++ view->RowAt(rowId++)->SetField(new BStringField(str), infoValueCol); ++ ++ if (extInfo.FindInt32("euid", &uid) < B_OK) uid = -1; ++ if (extInfo.FindInt32("egid", &gid) < B_OK) gid = -1; ++ GetUserGroupString(str, uid, gid, true); ++ view->RowAt(rowId++)->SetField(new BStringField(str), infoValueCol); ++ ++ entry_ref ref; ++ if ( ++ extInfo.FindInt32("cwd device", &ref.device) >= B_OK && ++ extInfo.FindInt64("cwd directory", &ref.directory) >= B_OK ++ ) { ++ ref.set_name("."); ++ BPath path(&ref); ++ view->RowAt(rowId++)->SetField(new BStringField(path.Path()), infoValueCol); ++ } ++ } ++} ++ ++static void NewInfoRow(BColumnListView *view, const char *name) ++{ ++ BRow *row = new BRow(); ++ row->SetField(new BStringField(name), infoNameCol); ++ view->AddRow(row); ++} ++ ++static BColumnListView *NewInfoView(TeamWindow *wnd) ++{ ++ BColumnListView *view; ++ view = new BColumnListView("Info", B_NAVIGABLE); ++ view->AddColumn(new BStringColumn("Name", 150, 50, 500, B_TRUNCATE_END), infoNameCol); ++ view->AddColumn(new BStringColumn("Value", 512, 50, 1024, B_TRUNCATE_END), infoValueCol); ++ ++ NewInfoRow(view, "ID"); ++ NewInfoRow(view, "Name"); ++ NewInfoRow(view, "Process group"); ++ NewInfoRow(view, "Session"); ++ NewInfoRow(view, "User"); ++ NewInfoRow(view, "Effective user"); ++ NewInfoRow(view, "Working directory"); ++ ++ ListInfo(wnd, view); ++ return view; ++} ++ ++ ++static void ListImages(TeamWindow *wnd, BColumnListView *view) ++{ ++ int32 cookie = 0; ++ image_info info; ++ BString str; ++ BRow *row; ++ BList prevRows; ++ ++ for (int32 i = 0; i < view->CountRows(); i++) { ++ row = view->RowAt(i); ++ prevRows.AddItem((void*)(addr_t)(((BIntegerField*)row->GetField(imageIdCol))->Value())); ++ } ++ ++ while (get_next_image_info(wnd->fId, &cookie, &info) >= B_OK) { ++ prevRows.RemoveItem((void*)(addr_t)info.id); ++ row = FindIntRow(view, imageIdCol, NULL, info.id); ++ if (row == NULL) { ++ row = new BRow(); ++ view->AddRow(row); ++ } ++ ++ row->SetField(new BIntegerField(info.id), imageIdCol); ++ row->SetField(new Int64Field((uintptr_t)info.text), imageTextCol); ++ row->SetField(new Int64Field((uintptr_t)info.data), imageDataCol); ++ row->SetField(new BStringField(GetFileName(info.name)), imageNameCol); ++ row->SetField(new BStringField(info.name), imagePathCol); ++ } ++ ++ for (int32 i = 0; i < prevRows.CountItems(); i++) { ++ row = FindIntRow(view, imageIdCol, NULL, (int32)(addr_t)prevRows.ItemAt(i)); ++ view->RemoveRow(row); ++ delete row; ++ } ++} ++ ++static BColumnListView *NewImagesView(TeamWindow *wnd) ++{ ++ BColumnListView *view; ++ view = new BColumnListView("Images", B_NAVIGABLE); ++ view->AddColumn(new BIntegerColumn("ID", 64, 32, 128, B_ALIGN_RIGHT), imageIdCol); ++ view->AddColumn(new HexIntegerColumn("Text", 128, 50, 500, B_ALIGN_RIGHT), imageTextCol); ++ view->AddColumn(new HexIntegerColumn("Data", 128, 50, 500, B_ALIGN_RIGHT), imageDataCol); ++ view->AddColumn(new BStringColumn("Name", 150, 50, 500, B_TRUNCATE_END), imageNameCol); ++ view->AddColumn(new BStringColumn("Path", 500, 50, 1000, B_TRUNCATE_MIDDLE), imagePathCol); ++ ListImages(wnd, view); ++ return view; ++} ++ ++static void ListThreads(TeamWindow *wnd, BColumnListView *view) ++{ ++ int32 cookie = 0; ++ thread_info info; ++ BString str; ++ BRow *row; ++ BList prevRows; ++ ++ for (int32 i = 0; i < view->CountRows(); i++) { ++ row = view->RowAt(i); ++ prevRows.AddItem((void*)(addr_t)(((BIntegerField*)row->GetField(threadIdCol))->Value())); ++ } ++ ++ while (get_next_thread_info(wnd->fId, &cookie, &info) >= B_OK) { ++ prevRows.RemoveItem((void*)(addr_t)info.thread); ++ row = FindIntRow(view, threadIdCol, NULL, info.thread); ++ if (row == NULL) { ++ row = new BRow(); ++ view->AddRow(row); ++ } ++ ++ row->SetField(new BIntegerField(info.thread), threadIdCol); ++ row->SetField(new BStringField(info.name), threadNameCol); ++ ++ switch (info.state) { ++ case B_THREAD_RUNNING: str = "running"; break; ++ case B_THREAD_READY: str = "ready"; break; ++ case B_THREAD_RECEIVING: str = "receiving"; break; ++ case B_THREAD_ASLEEP: str = "asleep"; break; ++ case B_THREAD_SUSPENDED: str = "suspended"; break; ++ case B_THREAD_WAITING: str = "waiting"; break; ++ default: ++ str.SetToFormat("? (%d)", info.state); ++ } ++ row->SetField(new BStringField(str), threadStateCol); ++ ++ row->SetField(new BIntegerField(info.priority), threadPriorityCol); ++ GetSemString(str, info.sem); ++ row->SetField(new BStringField(str), threadSemCol); ++ row->SetField(new BIntegerField(info.user_time), threadUserTimeCol); ++ row->SetField(new BIntegerField(info.kernel_time), threadKernelTimeCol); ++ row->SetField(new Int64Field((addr_t)info.stack_base), threadStackBaseCol); ++ row->SetField(new Int64Field((addr_t)info.stack_end), threadStackEndCol); ++ } ++ ++ for (int32 i = 0; i < prevRows.CountItems(); i++) { ++ row = FindIntRow(view, threadIdCol, NULL, (int32)(addr_t)prevRows.ItemAt(i)); ++ view->RemoveRow(row); ++ delete row; ++ } ++} ++ ++static BColumnListView *NewThreadsView(TeamWindow *wnd) ++{ ++ BColumnListView *view; ++ view = new BColumnListView("Threads", B_NAVIGABLE); ++ view->AddColumn(new BIntegerColumn("ID", 64, 32, 128, B_ALIGN_RIGHT), threadIdCol); ++ view->AddColumn(new BStringColumn("Name", 150, 50, 500, B_TRUNCATE_END), threadNameCol); ++ view->AddColumn(new BStringColumn("State", 150, 50, 500, B_TRUNCATE_END), threadStateCol); ++ view->AddColumn(new BIntegerColumn("Priority", 96, 32, 128, B_ALIGN_RIGHT), threadPriorityCol); ++ view->AddColumn(new BStringColumn("Sem", 96, 32, 512, B_TRUNCATE_END), threadSemCol); ++ view->AddColumn(new BIntegerColumn("User time", 96, 32, 128, B_ALIGN_RIGHT), threadUserTimeCol); ++ view->AddColumn(new BIntegerColumn("Kernel time", 96, 32, 128, B_ALIGN_RIGHT), threadKernelTimeCol); ++ view->AddColumn(new HexIntegerColumn("Stack base", 128, 50, 500, B_ALIGN_RIGHT), threadStackBaseCol); ++ view->AddColumn(new HexIntegerColumn("Stack end", 128, 50, 500, B_ALIGN_RIGHT), threadStackEndCol); ++ view->SetInvocationMessage(new BMessage(threadsInvokeMsg)); ++ ListThreads(wnd, view); ++ return view; ++} ++ ++static void ListAreas(TeamWindow *wnd, BColumnListView *view) ++{ ++ ssize_t cookie = 0; ++ area_info info; ++ BString str, str2; ++ BRow *row; ++ BList prevRows; ++ ++ for (int32 i = 0; i < view->CountRows(); i++) { ++ row = view->RowAt(i); ++ prevRows.AddItem((void*)(addr_t)(((BIntegerField*)row->GetField(areaIdCol))->Value())); ++ } ++ ++ while (get_next_area_info(wnd->fId, &cookie, &info) >= B_OK) { ++ prevRows.RemoveItem((void*)(addr_t)info.area); ++ row = FindIntRow(view, areaIdCol, NULL, info.area); ++ if (row == NULL) { ++ row = new BRow(); ++ view->AddRow(row); ++ } ++ ++ row->SetField(new BIntegerField(info.area), areaIdCol); ++ row->SetField(new BStringField(info.name), areaNameCol); ++ row->SetField(new Int64Field((addr_t)info.address), areaAdrCol); ++ row->SetField(new Int64Field(info.size), areaSizeCol); ++ row->SetField(new Int64Field(info.ram_size), areaAllocCol); ++ ++ str = ""; ++ if (B_READ_AREA & info.protection) str += "R"; ++ if (B_WRITE_AREA & info.protection) str += "W"; ++ if (B_EXECUTE_AREA & info.protection) str += "X"; ++ if (B_STACK_AREA & info.protection) str += "S"; ++ if (B_KERNEL_READ_AREA & info.protection) str += "r"; ++ if (B_KERNEL_WRITE_AREA & info.protection) str += "w"; ++ if (B_KERNEL_EXECUTE_AREA & info.protection) str += "x"; ++ if (B_KERNEL_STACK_AREA & info.protection) str += "s"; ++ if (B_CLONEABLE_AREA & info.protection) str += "C"; ++ row->SetField(new BStringField(str), areaProtCol); ++ ++ switch (info.lock) { ++ case B_NO_LOCK: str = "no"; break; ++ case B_LAZY_LOCK: str = "lazy"; break; ++ case B_FULL_LOCK: str = "full"; break; ++ case B_CONTIGUOUS: str = "contiguous"; break; ++ case B_LOMEM: str = "lomem"; break; ++ case B_32_BIT_FULL_LOCK: str = "32 bit full"; break; ++ case B_32_BIT_CONTIGUOUS: str = "32 bit contiguous"; break; ++ default: ++ str.SetToFormat("? (%" B_PRIu32 ")", info.lock); ++ } ++ row->SetField(new BStringField(str), areaLockCol); ++ } ++ ++ for (int32 i = 0; i < prevRows.CountItems(); i++) { ++ row = FindIntRow(view, areaIdCol, NULL, (int32)(addr_t)prevRows.ItemAt(i)); ++ view->RemoveRow(row); ++ delete row; ++ } ++} ++ ++static BColumnListView *NewAreasView(TeamWindow *wnd) ++{ ++ BColumnListView *view; ++ view = new BColumnListView("Areas", B_NAVIGABLE); ++ view->AddColumn(new BIntegerColumn("ID", 64, 32, 128, B_ALIGN_RIGHT), areaIdCol); ++ view->AddColumn(new BStringColumn("Name", 150, 50, 500, B_TRUNCATE_END), areaNameCol); ++ view->AddColumn(new HexIntegerColumn("Address", 128, 50, 500, B_ALIGN_RIGHT), areaAdrCol); ++ view->AddColumn(new HexIntegerColumn("Size", 128, 50, 500, B_ALIGN_RIGHT), areaSizeCol); ++ view->AddColumn(new HexIntegerColumn("Alloc", 128, 50, 500, B_ALIGN_RIGHT), areaAllocCol); ++ view->AddColumn(new BStringColumn("Prot", 64, 50, 500, B_TRUNCATE_END, B_ALIGN_RIGHT), areaProtCol); ++ view->AddColumn(new BStringColumn("lock", 64, 50, 500, B_TRUNCATE_END, B_ALIGN_RIGHT), areaLockCol); ++ ListAreas(wnd, view); ++ return view; ++} ++ ++static void ListPorts(TeamWindow *wnd, BColumnListView *view) ++{ ++ int32 cookie = 0; ++ port_info info; ++ BString str, str2; ++ BRow *row; ++ BList prevRows; ++ ++ for (int32 i = 0; i < view->CountRows(); i++) { ++ row = view->RowAt(i); ++ prevRows.AddItem((void*)(addr_t)(((BIntegerField*)row->GetField(portIdCol))->Value())); ++ } ++ ++ while (get_next_port_info(wnd->fId, &cookie, &info) >= B_OK) { ++ prevRows.RemoveItem((void*)(addr_t)info.port); ++ row = FindIntRow(view, portIdCol, NULL, info.port); ++ if (row == NULL) { ++ row = new BRow(); ++ view->AddRow(row); ++ } ++ ++ row->SetField(new BIntegerField(info.port), portIdCol); ++ row->SetField(new BStringField(info.name), portNameCol); ++ row->SetField(new BIntegerField(info.capacity), portCapacityCol); ++ row->SetField(new BIntegerField(info.queue_count), portQueuedCol); ++ row->SetField(new BIntegerField(info.total_count), portTotalCol); ++ } ++ ++ for (int32 i = 0; i < prevRows.CountItems(); i++) { ++ row = FindIntRow(view, portIdCol, NULL, (int32)(addr_t)prevRows.ItemAt(i)); ++ view->RemoveRow(row); ++ delete row; ++ } ++} ++ ++static BColumnListView *NewPortsView(TeamWindow *wnd) ++{ ++ BColumnListView *view; ++ view = new BColumnListView("Ports", B_NAVIGABLE); ++ view->AddColumn(new BIntegerColumn("ID", 64, 32, 128, B_ALIGN_RIGHT), portIdCol); ++ view->AddColumn(new BStringColumn("Name", 150, 50, 500, B_TRUNCATE_END), portNameCol); ++ view->AddColumn(new BIntegerColumn("Capacity", 64, 32, 128, B_ALIGN_RIGHT), portCapacityCol); ++ view->AddColumn(new BIntegerColumn("Queued", 64, 32, 128, B_ALIGN_RIGHT), portQueuedCol); ++ view->AddColumn(new BIntegerColumn("Total", 96, 32, 256, B_ALIGN_RIGHT), portTotalCol); ++ ListPorts(wnd, view); ++ return view; ++} ++ ++static void ListSems(TeamWindow *wnd, BColumnListView *view) ++{ ++ int32 cookie = 0; ++ sem_info info; ++ BRow *row; ++ BList prevRows; ++ BString str; ++ ++ for (int32 i = 0; i < view->CountRows(); i++) { ++ row = view->RowAt(i); ++ prevRows.AddItem((void*)(addr_t)(((BIntegerField*)row->GetField(semIdCol))->Value())); ++ } ++ ++ while (get_next_sem_info(wnd->fId, &cookie, &info) >= B_OK) { ++ prevRows.RemoveItem((void*)(addr_t)info.sem); ++ row = FindIntRow(view, semIdCol, NULL, info.sem); ++ if (row == NULL) { ++ row = new BRow(); ++ view->AddRow(row); ++ } ++ ++ row->SetField(new BIntegerField(info.sem), semIdCol); ++ row->SetField(new BStringField(info.name), semNameCol); ++ row->SetField(new BIntegerField(info.count), semCountCol); ++ GetThreadString(str, info.latest_holder); ++ row->SetField(new BStringField(str), semLatestHolderCol); ++ } ++ ++ for (int32 i = 0; i < prevRows.CountItems(); i++) { ++ row = FindIntRow(view, semIdCol, NULL, (int32)(addr_t)prevRows.ItemAt(i)); ++ view->RemoveRow(row); ++ delete row; ++ } ++} ++ ++static BColumnListView *NewSemsView(TeamWindow *wnd) ++{ ++ BColumnListView *view; ++ view = new BColumnListView("Semaphores", B_NAVIGABLE); ++ view->AddColumn(new BIntegerColumn("ID", 64, 32, 128, B_ALIGN_RIGHT), semIdCol); ++ view->AddColumn(new BStringColumn("Name", 150, 50, 500, B_TRUNCATE_END), semNameCol); ++ view->AddColumn(new BIntegerColumn("Count", 64, 32, 128, B_ALIGN_RIGHT), semCountCol); ++ view->AddColumn(new BStringColumn("Latest holder", 96, 32, 1024, B_TRUNCATE_END), semLatestHolderCol); ++ ListSems(wnd, view); ++ return view; ++} ++ ++static void ListFiles(TeamWindow *wnd, BColumnListView *view) ++{ ++ uint32 cookie = 0; ++ fd_info info; ++ fs_info fsInfo; ++ BRow *row; ++ BList prevRows; ++ BString buf; ++ char path[B_OS_NAME_LENGTH]; ++ ++ for (int32 i = 0; i < view->CountRows(); i++) { ++ row = view->RowAt(i); ++ prevRows.AddItem((void*)(addr_t)(((BIntegerField*)row->GetField(fileIdCol))->Value())); ++ } ++ ++ while (_kern_get_next_fd_info(wnd->fId, &cookie, &info, sizeof(fd_info)) >= B_OK) { ++ prevRows.RemoveItem((void*)(addr_t)info.number); ++ row = FindIntRow(view, fileIdCol, NULL, info.number); ++ if (row == NULL) { ++ row = new BRow(); ++ view->AddRow(row); ++ } ++ ++ if (_kern_entry_ref_to_path(info.device, info.node, NULL, path, B_OS_NAME_LENGTH) == B_OK) ++ row->SetField(new BStringField(path), fileNameCol); ++ else ++ row->SetField(new BStringField("?"), fileNameCol); ++ ++ row->SetField(new BIntegerField(info.number), fileIdCol); ++ ++ if ((info.open_mode & O_RWMASK) == O_RDONLY) {buf = "R";} ++ if ((info.open_mode & O_RWMASK) == O_WRONLY) {buf = "W";} ++ if ((info.open_mode & O_RWMASK) == O_RDWR ) {buf = "RW";} ++ row->SetField(new BStringField(buf), fileModeCol); ++ row->SetField(new BIntegerField(info.device), fileDevCol); ++ row->SetField(new BIntegerField(info.node), fileNodeCol); ++ ++ fs_stat_dev(info.device, &fsInfo); ++ row->SetField(new BStringField(fsInfo.device_name), fileDevNameCol); ++ row->SetField(new BStringField(fsInfo.volume_name), fileVolNameCol); ++ row->SetField(new BStringField(fsInfo.fsh_name), fileFsNameCol); ++ } ++ ++ for (int32 i = 0; i < prevRows.CountItems(); i++) { ++ row = FindIntRow(view, fileIdCol, NULL, (int32)(addr_t)prevRows.ItemAt(i)); ++ view->RemoveRow(row); ++ delete row; ++ } ++} ++ ++static BColumnListView *NewFilesView(TeamWindow *wnd) ++{ ++ BColumnListView *view; ++ view = new BColumnListView("Files", B_NAVIGABLE); ++ view->AddColumn(new BStringColumn("Name", 250, 50, 512, B_TRUNCATE_MIDDLE), fileNameCol); ++ view->AddColumn(new BIntegerColumn("ID", 64, 32, 128, B_ALIGN_RIGHT), fileIdCol); ++ view->AddColumn(new BStringColumn("Mode", 48, 32, 128, B_TRUNCATE_MIDDLE, B_ALIGN_LEFT), fileModeCol); ++ view->AddColumn(new BIntegerColumn("Dev", 64, 32, 128, B_ALIGN_RIGHT), fileDevCol); ++ view->AddColumn(new BIntegerColumn("Node", 64, 32, 128, B_ALIGN_RIGHT), fileNodeCol); ++ view->AddColumn(new BStringColumn("Device", 96, 32, 512, B_TRUNCATE_MIDDLE, B_ALIGN_LEFT), fileDevNameCol); ++ view->AddColumn(new BStringColumn("Volume", 96, 32, 512, B_TRUNCATE_MIDDLE, B_ALIGN_LEFT), fileVolNameCol); ++ view->AddColumn(new BStringColumn("FS", 96, 32, 512, B_TRUNCATE_MIDDLE, B_ALIGN_LEFT), fileFsNameCol); ++ ListFiles(wnd, view); ++ return view; ++} ++ ++ ++class TabView: public BTabView ++{ ++private: ++ TeamWindow *fWnd; ++ ++public: ++ TabView(TeamWindow *wnd): BTabView("tabView", B_WIDTH_FROM_LABEL), fWnd(wnd) {} ++ ++ void Select(int32 index) ++ { ++ BTabView::Select(index); ++ fWnd->TabChanged(); ++ } ++ ++}; ++ ++ ++//#pragma mark TeamWindow ++ ++std::map teamWindows; ++BLocker teamWindowsLocker; ++ ++TeamWindow *OpenTeamWindow(team_id id, BPoint center) ++{ ++ AutoLocker locker(teamWindowsLocker); ++ auto it = teamWindows.find(id); ++ if (it != teamWindows.end()) { ++ it->second->Activate(); ++ return it->second; ++ } else { ++ TeamWindow *wnd = new TeamWindow(id); ++ teamWindows[id] = wnd; ++ BRect frame = wnd->Frame(); ++ wnd->MoveTo(center.x - frame.Width()/2, center.y - frame.Height()/2); ++ wnd->Show(); ++ return wnd; ++ } ++} ++ ++static BMessage *NewSignalMsg(int32 signal) ++{ ++ BMessage *msg = new BMessage(threadsSendSignalMsg); ++ msg->AddInt32("val", signal); ++ return msg; ++} ++ ++TeamWindow::TeamWindow(team_id id): BWindow(BRect(0, 0, 800, 480), "Team", B_DOCUMENT_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS), ++ fListUpdater(BMessenger(this), BMessage(updateMsg), 1000000), ++ fCurMenu(NULL), ++ fId(id) ++{ ++ BTab *tab; ++ BMenu *menu; ++ ++ try { ++ int32 cookie = 0; ++ image_info imageInfo; ++ Check(get_next_image_info(fId, &cookie, &imageInfo), "Invalid team id."); ++ BString title; ++ title.SetToFormat("%s (%" B_PRId32 ")", GetFileName(imageInfo.name), fId); ++ SetTitle(title.String()); ++ } catch (StatusError &err) { ++ ShowError(err); ++ PostMessage(B_QUIT_REQUESTED); ++ } ++ ++ fMenuBar = new BMenuBar("menu", B_ITEMS_IN_ROW, true); ++ BLayoutBuilder::Menu<>(fMenuBar) ++ .AddMenu(new BMenu("File")) ++ .AddItem(new BMenuItem("Close", new BMessage(B_QUIT_REQUESTED), 'W')) ++ .End() ++ .End() ++ ; ++ ++ menu = new BMenu("Info"); ++ BLayoutBuilder::Menu<>(menu) ++ .AddItem(new BMenuItem("Show working directory", new BMessage(infoShowWorkDirMsg))) ++ .End() ++ ; ++ fInfoMenu = new BMenuItem(menu); ++ ++ menu = new BMenu("Image"); ++ BLayoutBuilder::Menu<>(menu) ++ .AddItem(new BMenuItem("Show location", new BMessage(imagesShowLocationMsg))) ++ .End() ++ ; ++ fImagesMenu = new BMenuItem(menu); ++ ++ BMenu *signalMenu; ++ menu = new BMenu("Thread"); ++ BLayoutBuilder::Menu<>(menu) ++ .AddItem(new BMenuItem("Terminate", new BMessage(threadsTerminateMsg), 'T')) ++ .AddItem(new BMenuItem("Suspend", NewSignalMsg(SIGSTOP))) ++ .AddItem(new BMenuItem("Resume", NewSignalMsg(SIGCONT))) ++ .AddMenu(signalMenu = new BMenu("Send signal")) ++ .End() ++ .AddSeparator() ++ .AddItem(new BMenuItem("Show semaphore", new BMessage(threadsShowSemMsg))) ++ .AddItem(new BMenuItem("Show stack area", new BMessage(threadsShowStackAreaMsg))) ++ .End() ++ ; ++ fThreadsMenu = new BMenuItem(menu); ++ for (size_t i = 0; i < sizeof(signals)/sizeof(signals[0]); i++) ++ signalMenu->AddItem(new BMenuItem(signals[i].name, NewSignalMsg(signals[i].val))); ++ ++ menu = new BMenu("Semaphore"); ++ BLayoutBuilder::Menu<>(menu) ++ .AddItem(new BMenuItem("Show holder thread", new BMessage(semsShowThreadMsg))) ++ .End() ++ ; ++ fSemsMenu = new BMenuItem(menu); ++ ++ fTabView = new TabView(this); ++ fTabView->SetBorder(B_NO_BORDER); ++ ++ tab = new BTab(); fTabView->AddTab(fInfoView = NewInfoView(this), tab); ++ tab = new BTab(); fTabView->AddTab(fImagesView = NewImagesView(this), tab); ++ tab = new BTab(); fTabView->AddTab(fThreadsView = NewThreadsView(this), tab); ++ tab = new BTab(); fTabView->AddTab(fAreasView = NewAreasView(this), tab); ++ tab = new BTab(); fTabView->AddTab(fPortsView = NewPortsView(this), tab); ++ tab = new BTab(); fTabView->AddTab(fSemsView = NewSemsView(this), tab); ++ tab = new BTab(); fTabView->AddTab(fFilesView = NewFilesView(this), tab); ++ ++ BLayoutBuilder::Group<>(this, B_VERTICAL, 0) ++ .Add(fMenuBar) ++ .AddGroup(B_VERTICAL, 0) ++ .Add(fTabView) ++ .SetInsets(-1, 0, -1, -1) ++ .End() ++ .End() ++ ; ++ ++ TabChanged(); ++} ++ ++TeamWindow::~TeamWindow() ++{ ++ printf("-TeamWindow\n"); ++ AutoLocker locker(teamWindowsLocker); ++ teamWindows.erase(fId); ++} ++ ++void TeamWindow::TabChanged() ++{ ++ BMenuItem *newMenu = NULL; ++ BTab *tab = fTabView->TabAt(fTabView->Selection()); ++ if (tab != NULL) { ++ BView *view = tab->View(); ++ if (view == fInfoView) ++ newMenu = fInfoMenu; ++ else if (view == fImagesView) ++ newMenu = fImagesMenu; ++ else if (view == fThreadsView) ++ newMenu = fThreadsMenu; ++ else if (view == fSemsView) ++ newMenu = fSemsMenu; ++ } ++ SetMenu(newMenu); ++} ++ ++void TeamWindow::SetMenu(BMenuItem *menu) ++{ ++ if (fCurMenu == menu) return; ++ if (fCurMenu != NULL) fMenuBar->RemoveItem(fCurMenu); ++ fCurMenu = menu; ++ if (fCurMenu != NULL) fMenuBar->AddItem(fCurMenu); ++} ++ ++void TeamWindow::MessageReceived(BMessage *msg) ++{ ++ switch (msg->what) { ++ case updateMsg: { ++ BTab *tab = fTabView->TabAt(fTabView->Selection()); ++ if (tab != NULL) { ++ BView *view = tab->View(); ++ if (view == fInfoView) ++ ListInfo(this, fInfoView); ++ else if (view == fImagesView) ++ ListImages(this, fImagesView); ++ else if (view == fThreadsView) ++ ListThreads(this, fThreadsView); ++ else if (view == fAreasView) ++ ListAreas(this, fAreasView); ++ else if (view == fPortsView) ++ ListPorts(this, fPortsView); ++ else if (view == fSemsView) ++ ListSems(this, fSemsView); ++ else if (view == fFilesView) ++ ListFiles(this, fFilesView); ++ } ++ return; ++ } ++ ++ case infoShowWorkDirMsg: { ++ BRow *row = fInfoView->RowAt(6); // !!! ++ if (row == NULL) return; ++ ShowLocation(((BStringField*)row->GetField(infoValueCol))->String()); ++ return; ++ } ++ case imagesShowLocationMsg: { ++ BRow *row = fImagesView->CurrentSelection(NULL); ++ if (row == NULL) return; ++ ShowLocation(((BStringField*)row->GetField(imagePathCol))->String()); ++ return; ++ } ++ ++ case threadsInvokeMsg: { ++ BRow *row = fThreadsView->CurrentSelection(NULL); ++ if (row == NULL) return; ++ BPoint center((Frame().left + Frame().right)/2, (Frame().top + Frame().bottom)/2); ++ OpenStackWindow(((BIntegerField*)row->GetField(threadIdCol))->Value(), center); ++ return; ++ } ++ case threadsTerminateMsg: ++ case threadsSendSignalMsg: { ++ BTab *tab = fTabView->TabAt(fTabView->Selection()); ++ if (tab == NULL) return; ++ BView *view = tab->View(); ++ if (view != fThreadsView) return; ++ BRow *row = fThreadsView->CurrentSelection(NULL); ++ if (row == NULL) return; ++ thread_id thread = ((BIntegerField*)row->GetField(threadIdCol))->Value(); ++ if (thread < B_OK) return; ++ switch (msg->what) { ++ case threadsTerminateMsg: ++ CheckErrno(kill_thread(thread), "Can't terminate thread."); ++ break; ++ case threadsSendSignalMsg: ++ int32 signal; ++ if (msg->FindInt32("val", &signal) < B_OK) return; ++ CheckErrno(send_signal(thread, signal), "Can't send signal."); ++ break; ++ } ++ return; ++ } ++ case threadsShowSemMsg: { ++ BTab *tab = fTabView->TabAt(fTabView->Selection()); ++ if (tab == NULL) return; ++ BView *view = tab->View(); ++ if (view != fThreadsView) return; ++ BRow *row = fThreadsView->CurrentSelection(NULL); ++ if (row == NULL) return; ++ sem_id sem = atoi(((BStringField*)row->GetField(threadSemCol))->String()); ++ if (sem < B_OK) return; ++ BMessage showMsg(B_EXECUTE_PROPERTY); ++ showMsg.AddSpecifier("Sem", sem); ++ be_app_messenger.SendMessage(&showMsg); ++ return; ++ } ++ case threadsShowStackAreaMsg: { ++ BTab *tab = fTabView->TabAt(fTabView->Selection()); ++ if (tab == NULL) return; ++ BView *view = tab->View(); ++ if (view != fThreadsView) return; ++ BRow *row = fThreadsView->CurrentSelection(NULL); ++ if (row == NULL) return; ++ int64 stackBase = ((Int64Field*)row->GetField(threadStackBaseCol))->Value(); ++ ListAreas(this, fAreasView); ++ for (int32 i = 0; i < fAreasView->CountRows(); i++) { ++ BRow *areaRow = fAreasView->RowAt(i); ++ int64 areaAdr = ((Int64Field*)areaRow->GetField(areaAdrCol))->Value(); ++ int64 areaSize = ((Int64Field*)areaRow->GetField(areaSizeCol))->Value(); ++ if (stackBase >= areaAdr && stackBase < areaAdr + areaSize) { ++ int32 area = ((BIntegerField*)areaRow->GetField(areaIdCol))->Value(); ++ BMessage showMsg(teamWindowShowAreaMsg); ++ CheckRetVoid(showMsg.AddInt32("val", area)); ++ CheckRetVoid(showMsg.AddInt32("refresh", false)); ++ BMessenger(this).SendMessage(&showMsg); ++ } ++ } ++ } ++ case semsShowThreadMsg: { ++ BTab *tab = fTabView->TabAt(fTabView->Selection()); ++ if (tab == NULL) return; ++ BView *view = tab->View(); ++ if (view != fSemsView) return; ++ BRow *row = fSemsView->CurrentSelection(NULL); ++ if (row == NULL) return; ++ thread_id thread = atoi(((BStringField*)row->GetField(semLatestHolderCol))->String()); ++ if (thread < B_OK) return; ++ BMessage showMsg(B_EXECUTE_PROPERTY); ++ showMsg.AddSpecifier("Thread", thread); ++ be_app_messenger.SendMessage(&showMsg); ++ return; ++ } ++ ++ case teamWindowShowImageMsg: { ++ int32 id; ++ if (msg->FindInt32("val", &id) < B_OK) return; ++ fTabView->Select(1); // TODO: remove hard-coded constant ++ ListImages(this, fImagesView); ++ BRow *itemRow = FindIntRow(fImagesView, imageIdCol, NULL, id); ++ if (itemRow == NULL) return; ++ fImagesView->DeselectAll(); ++ fImagesView->SetFocusRow(itemRow, true); ++ fImagesView->ScrollTo(itemRow); ++ return; ++ } ++ case teamWindowShowThreadMsg: { ++ int32 id; ++ if (msg->FindInt32("val", &id) < B_OK) return; ++ fTabView->Select(2); // TODO: remove hard-coded constant ++ ListThreads(this, fThreadsView); ++ BRow *itemRow = FindIntRow(fThreadsView, threadIdCol, NULL, id); ++ if (itemRow == NULL) return; ++ fThreadsView->DeselectAll(); ++ fThreadsView->SetFocusRow(itemRow, true); ++ fThreadsView->ScrollTo(itemRow); ++ return; ++ } ++ case teamWindowShowAreaMsg: { ++ int32 id; ++ bool refresh; ++ if (msg->FindInt32("val", &id) < B_OK) return; ++ if (msg->FindBool("refresh", &refresh) < B_OK) refresh = true; ++ fTabView->Select(3); // TODO: remove hard-coded constant ++ if (refresh) ListAreas(this, fAreasView); ++ BRow *itemRow = FindIntRow(fAreasView, areaIdCol, NULL, id); ++ if (itemRow == NULL) return; ++ fAreasView->DeselectAll(); ++ fAreasView->SetFocusRow(itemRow, true); ++ fAreasView->ScrollTo(itemRow); ++ return; ++ } ++ case teamWindowShowPortMsg: { ++ int32 id; ++ if (msg->FindInt32("val", &id) < B_OK) return; ++ fTabView->Select(4); // TODO: remove hard-coded constant ++ ListPorts(this, fPortsView); ++ BRow *itemRow = FindIntRow(fPortsView, portIdCol, NULL, id); ++ if (itemRow == NULL) return; ++ fPortsView->DeselectAll(); ++ fPortsView->SetFocusRow(itemRow, true); ++ fPortsView->ScrollTo(itemRow); ++ return; ++ } ++ case teamWindowShowSemMsg: { ++ int32 id; ++ if (msg->FindInt32("val", &id) < B_OK) return; ++ fTabView->Select(5); // TODO: remove hard-coded constant ++ ListSems(this, fSemsView); ++ BRow *itemRow = FindIntRow(fSemsView, semIdCol, NULL, id); ++ if (itemRow == NULL) return; ++ fSemsView->DeselectAll(); ++ fSemsView->SetFocusRow(itemRow, true); ++ fSemsView->ScrollTo(itemRow); ++ return; ++ } ++ case teamWindowShowFileMsg: { ++ int32 id; ++ if (msg->FindInt32("val", &id) < B_OK) return; ++ fTabView->Select(6); // TODO: remove hard-coded constant ++ ListFiles(this, fFilesView); ++ BRow *itemRow = FindIntRow(fFilesView, fileIdCol, NULL, id); ++ if (itemRow == NULL) return; ++ fFilesView->DeselectAll(); ++ fFilesView->SetFocusRow(itemRow, true); ++ fFilesView->ScrollTo(itemRow); ++ return; ++ } ++ } ++ BWindow::MessageReceived(msg); ++} +diff --git a/src/apps/systemmanager/TeamWindow.h b/src/apps/systemmanager/TeamWindow.h +new file mode 100644 +index 0000000000..e5ad85b265 +--- /dev/null ++++ b/src/apps/systemmanager/TeamWindow.h +@@ -0,0 +1,54 @@ ++#ifndef _TEAMWINDOW_H_ ++#define _TEAMWINDOW_H_ ++ ++#include ++#include ++#include ++ ++class BTabView; ++class BColumnListView; ++ ++enum { ++ teamWindowShowImageMsg = 1, ++ teamWindowShowThreadMsg, ++ teamWindowShowAreaMsg, ++ teamWindowShowPortMsg, ++ teamWindowShowSemMsg, ++ teamWindowShowFileMsg, ++ ++ teamWindowPrivateMsgBase ++}; ++ ++class TeamWindow: public BWindow ++{ ++private: ++ BMessageRunner fListUpdater; ++ BTabView *fTabView; ++ BMenuBar *fMenuBar; ++ BMenuItem *fCurMenu; ++ BMenuItem *fInfoMenu; ++ BMenuItem *fImagesMenu; ++ BMenuItem *fThreadsMenu; ++ BMenuItem *fSemsMenu; ++ BColumnListView *fInfoView; ++ BColumnListView *fImagesView; ++ BColumnListView *fThreadsView; ++ BColumnListView *fAreasView; ++ BColumnListView *fPortsView; ++ BColumnListView *fSemsView; ++ BColumnListView *fFilesView; ++ ++public: ++ team_id fId; ++ ++ TeamWindow(team_id id); ++ ~TeamWindow(); ++ ++ void TabChanged(); ++ void SetMenu(BMenuItem *menu); ++ void MessageReceived(BMessage *msg); ++}; ++ ++TeamWindow *OpenTeamWindow(team_id id, BPoint center); ++ ++#endif // _TEAMWINDOW_H_ +diff --git a/src/apps/systemmanager/UIUtils.cpp b/src/apps/systemmanager/UIUtils.cpp +new file mode 100644 +index 0000000000..c8ea2c6924 +--- /dev/null ++++ b/src/apps/systemmanager/UIUtils.cpp +@@ -0,0 +1,95 @@ ++#include "UIUtils.h" ++ ++#include ++ ++ ++IconStringField::IconStringField(BBitmap *icon, const char *string): ++ BStringField(string), fIcon(icon) ++{} ++ ++ ++IconStringColumn::IconStringColumn( ++ const char* title, float width, ++ float minWidth, float maxWidth, uint32 truncate, ++ alignment align ++): BStringColumn(title, width, minWidth, maxWidth, truncate, align) ++{} ++ ++void IconStringColumn::DrawField(BField* _field, BRect rect, BView* parent) ++{ ++ IconStringField *field = (IconStringField*)_field; ++ ++ parent->PushState(); ++ parent->SetDrawingMode(B_OP_ALPHA); ++ parent->DrawBitmap(field->Icon(), rect.LeftTop() + BPoint(4, 0)); ++ parent->PopState(); ++ rect.left += field->Icon()->Bounds().Width() + 1; ++ ++ BStringColumn::DrawField(field, rect, parent); ++} ++ ++float IconStringColumn::GetPreferredWidth(BField* field, BView* parent) const ++{ ++ return BStringColumn::GetPreferredWidth(field, parent) + dynamic_cast(field)->Icon()->Bounds().Width() + 1; ++} ++ ++bool IconStringColumn::AcceptsField(const BField* field) const ++{ ++ return dynamic_cast(field) != NULL; ++} ++ ++ ++HexIntegerColumn::HexIntegerColumn( ++ const char* title, ++ float width, float minWidth, float maxWidth, ++ alignment align ++): BTitledColumn(title, width, minWidth, maxWidth, align) ++{} ++ ++void HexIntegerColumn::DrawField(BField *field, BRect rect, BView* parent) ++{ ++ float width = rect.Width() - (2 * 8); ++ BString string; ++ ++ if (dynamic_cast(field) != NULL) ++ string.SetToFormat("0x%" B_PRIx64, ((Int64Field*)field)->Value()); ++ else ++ string.SetToFormat("0x%x", (int)((BIntegerField*)field)->Value()); ++ ++ BFont oldFont; ++ parent->GetFont(&oldFont); ++ parent->SetFont(be_fixed_font); ++ parent->TruncateString(&string, B_TRUNCATE_MIDDLE, width + 2); ++ DrawString(string.String(), parent, rect); ++ parent->SetFont(&oldFont); ++} ++ ++int HexIntegerColumn::CompareFields(BField *field1, BField *field2) ++{ ++ if (dynamic_cast(field1) != NULL) { ++ if (((Int64Field*)field1)->Value() == ((Int64Field*)field2)->Value()) ++ return 0; ++ else if (((Int64Field*)field1)->Value() > ((Int64Field*)field2)->Value()) ++ return 1; ++ else ++ return -1; ++ } else ++ return (((BIntegerField*)field1)->Value() - ((BIntegerField*)field2)->Value()); ++} ++ ++ ++Int64Field::Int64Field(int64 value): fValue(value) ++{ ++} ++ ++ ++void Int64Field::SetValue(int64 value) ++{ ++ fValue = value; ++} ++ ++ ++int64 Int64Field::Value() ++{ ++ return fValue; ++} +diff --git a/src/apps/systemmanager/UIUtils.h b/src/apps/systemmanager/UIUtils.h +new file mode 100644 +index 0000000000..c5efad354e +--- /dev/null ++++ b/src/apps/systemmanager/UIUtils.h +@@ -0,0 +1,59 @@ ++#ifndef _UIUTILS_H_ ++#define _UIUTILS_H_ ++ ++ ++#include ++#include ++#include ++ ++ ++class IconStringField: public BStringField ++{ ++private: ++ ObjectDeleter fIcon; ++ ++public: ++ IconStringField(BBitmap *icon, const char *string); ++ inline BBitmap *Icon() {return fIcon.Get();} ++}; ++ ++class IconStringColumn: public BStringColumn ++{ ++public: ++ IconStringColumn( ++ const char* title, float width, ++ float minWidth, float maxWidth, uint32 truncate, ++ alignment align = B_ALIGN_LEFT ++ ); ++ ++ void DrawField(BField* _field, BRect rect, BView* parent); ++ float GetPreferredWidth(BField* field, BView* parent) const; ++ bool AcceptsField(const BField* field) const; ++}; ++ ++class HexIntegerColumn: public BTitledColumn ++{ ++public: ++ HexIntegerColumn( ++ const char* title, ++ float width, float minWidth, float maxWidth, ++ alignment align ++ ); ++ ++ void DrawField(BField *field, BRect rect, BView* parent); ++ int CompareFields(BField *field1, BField *field2); ++}; ++ ++class Int64Field: public BField ++{ ++public: ++ Int64Field(int64 value); ++ void SetValue(int64 value); ++ int64 Value(); ++ ++private: ++ int64 fValue; ++}; ++ ++ ++#endif // _UIUTILS_H_ +diff --git a/src/apps/systemmanager/Utils.cpp b/src/apps/systemmanager/Utils.cpp +new file mode 100644 +index 0000000000..b549d364b0 +--- /dev/null ++++ b/src/apps/systemmanager/Utils.cpp +@@ -0,0 +1,164 @@ ++#include "Utils.h" ++ ++#include ++#include ++ ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++ ++SignalRec signals[] = { ++ {"SIGHUP", 1}, ++ {"SIGINT", 2}, ++ {"SIGQUIT", 3}, ++ {"SIGILL", 4}, ++ {"SIGCHLD", 5}, ++ {"SIGABRT", 6}, ++ {"SIGPIPE", 7}, ++ {"SIGFPE", 8}, ++ {"SIGKILL", 9}, ++ {"SIGSTOP", 10}, ++ {"SIGSEGV", 11}, ++ {"SIGCONT", 12}, ++ {"SIGTSTP", 13}, ++ {"SIGALRM", 14}, ++ {"SIGTERM", 15}, ++ {"SIGTTIN", 16}, ++ {"SIGTTOU", 17}, ++ {"SIGUSR1", 18}, ++ {"SIGUSR2", 19}, ++ {"SIGWINCH", 20}, ++ {"SIGKILLTHR", 21}, ++ {"SIGTRAP", 22}, ++ {"SIGPOLL", 23}, ++ {"SIGPROF", 24}, ++ {"SIGSYS", 25}, ++ {"SIGURG", 26}, ++ {"SIGVTALRM", 27}, ++ {"SIGXCPU", 28}, ++ {"SIGXFSZ", 29}, ++ {"SIGBUS", 30}, ++ {"SIGRESERVED1", 31}, ++ {"SIGRESERVED2", 32}, ++}; ++ ++ ++void GetSizeString(BString &str, uint64 size) ++{ ++ const char* prefixes[] = {"", "K", "M", "G", "T"}; ++ unsigned pow = 0; ++ int fracSize = 0; ++ while ((size >= 1024) && (pow < sizeof(prefixes)/sizeof(prefixes[0]) - 1)) { ++ fracSize = size*100/1024%100; ++ size /= 1024; ++ pow++; ++ } ++ str.SetToFormat("%" B_PRIu64 ".%02d %sB", size, fracSize, prefixes[pow]); ++} ++ ++void GetUsedMax(BString &str, uint64 used, uint64 max) ++{ ++ int32 ratio = 100; ++ if (max > 0) { ++ ratio = int32(double(used)/double(max)*100.0); ++ } ++ str.SetToFormat("%" B_PRIu64 "/%" B_PRIu64 " (%" B_PRId32 "%%)", used, max, ratio); ++} ++ ++void GetUsedMaxSize(BString &str, uint64 used, uint64 max) ++{ ++ BString str2; ++ int32 ratio = 100; ++ if (max > 0) { ++ ratio = int32(double(used)/double(max)*100.0); ++ } ++ GetSizeString(str, used); ++ str += "/"; ++ GetSizeString(str2, max); ++ str += str2; ++ str2.SetToFormat(" (%" B_PRId32 "%%)", ratio); ++ str += str2; ++} ++ ++ ++void GetUserGroupString(BString &str, int32 uid, int32 gid, bool showId) ++{ ++ BString str2; ++ passwd *userRec = getpwuid(uid); ++ if (userRec == NULL) str.SetToFormat("%" B_PRId32, uid); ++ else str = userRec->pw_name; ++ str += ":"; ++ group *grpRec = getgrgid(gid); ++ if (grpRec == NULL) str2.SetToFormat("%" B_PRId32, gid); ++ else str2 = grpRec->gr_name; ++ str += str2; ++ if (showId) { ++ str2.SetToFormat(" (%" B_PRId32 ":%" B_PRId32 ")", uid, gid); ++ str += str2; ++ } ++} ++ ++void GetTeamString(BString &str, team_id team) ++{ ++ const char *name = NULL; ++ KMessage extInfo; ++ if ( ++ team >= B_OK && ++ get_extended_team_info(team, B_TEAM_INFO_BASIC, extInfo) >= B_OK && ++ extInfo.FindString("name", &name) >= B_OK ++ ) ++ str.SetToFormat("%" B_PRId32 " (%s)", team, name); ++ else ++ str.SetToFormat("%" B_PRId32, team); ++} ++ ++void GetThreadString(BString &str, thread_id thread) ++{ ++ thread_info info; ++ if ( ++ thread != 0 && ++ get_thread_info((thread >= 0)? thread: -thread, &info) >= B_OK ++ ) ++ str.SetToFormat("%" B_PRId32 " (%s)", thread, info.name); ++ else ++ str.SetToFormat("%" B_PRId32, thread); ++} ++ ++void GetSemString(BString &str, sem_id sem) ++{ ++ sem_info info; ++ if ( ++ sem >= B_OK && ++ get_sem_info(sem, &info) >= B_OK ++ ) ++ str.SetToFormat("%" B_PRId32 " (%s)", sem, info.name); ++ else ++ str.SetToFormat("%" B_PRId32, sem); ++} ++ ++ ++void ShowLocation(const char *path) ++{ ++ BEntry entry(path); ++ if (!entry.Exists()) return; ++ ++ node_ref node; ++ entry.GetNodeRef(&node); ++ ++ BEntry parent; ++ entry.GetParent(&parent); ++ entry_ref parentRef; ++ parent.GetRef(&parentRef); ++ ++ BMessage message(B_REFS_RECEIVED); ++ message.AddRef("refs", &parentRef); ++ message.AddData("nodeRefToSelect", B_RAW_TYPE, &node, sizeof(node_ref)); ++ ++ BMessenger("application/x-vnd.Be-TRAK").SendMessage(&message); ++} +diff --git a/src/apps/systemmanager/Utils.h b/src/apps/systemmanager/Utils.h +new file mode 100644 +index 0000000000..29c5804e8f +--- /dev/null ++++ b/src/apps/systemmanager/Utils.h +@@ -0,0 +1,29 @@ ++#ifndef _UTILS_H_ ++#define _UTILS_H_ ++ ++#include ++ ++class BString; ++ ++ ++struct SignalRec ++{ ++ const char *name; ++ int val; ++}; ++ ++extern SignalRec signals[32]; ++ ++ ++void GetSizeString(BString &str, uint64 size); ++void GetUsedMax(BString &str, uint64 used, uint64 max); ++void GetUsedMaxSize(BString &str, uint64 used, uint64 max); ++ ++void GetUserGroupString(BString &str, int32 uid, int32 gid, bool showId = false); ++void GetTeamString(BString &str, team_id team); ++void GetThreadString(BString &str, thread_id thread); ++void GetSemString(BString &str, sem_id sem); ++ ++void ShowLocation(const char *path); ++ ++#endif // _UTILS_H_ +-- +2.30.2 + diff --git a/patchset-hrev55144/0056-SlimDemo-add.patch b/patchset-hrev55144/0056-SlimDemo-add.patch new file mode 100644 index 0000000..faccb98 --- /dev/null +++ b/patchset-hrev55144/0056-SlimDemo-add.patch @@ -0,0 +1,770 @@ +From f3eafa18d76e8d58431375038ec691995415c50d Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 24 May 2021 04:14:29 +0900 +Subject: SlimDemo: add + +Change-Id: I658f0259b1f98238cedce7a19d4e8ffae991a8d3 +--- + src/tests/servers/app/Jamfile | 1 + + src/tests/servers/app/SlimDemo/Jamfile | 8 + + src/tests/servers/app/SlimDemo/LICENSE | 31 ++ + src/tests/servers/app/SlimDemo/article | 133 ++++++ + src/tests/servers/app/SlimDemo/main.c | 544 +++++++++++++++++++++++++ + 5 files changed, 717 insertions(+) + create mode 100644 src/tests/servers/app/SlimDemo/Jamfile + create mode 100644 src/tests/servers/app/SlimDemo/LICENSE + create mode 100644 src/tests/servers/app/SlimDemo/article + create mode 100644 src/tests/servers/app/SlimDemo/main.c + +diff --git a/src/tests/servers/app/Jamfile b/src/tests/servers/app/Jamfile +index bb6bd454db..50cf69b305 100644 +--- a/src/tests/servers/app/Jamfile ++++ b/src/tests/servers/app/Jamfile +@@ -289,3 +289,4 @@ SubInclude HAIKU_TOP src tests servers app window_creation ; + SubInclude HAIKU_TOP src tests servers app window_invalidation ; + SubInclude HAIKU_TOP src tests servers app workspace_activated ; + SubInclude HAIKU_TOP src tests servers app workspace_switcher ; ++SubInclude HAIKU_TOP src tests servers app SlimDemo ; +diff --git a/src/tests/servers/app/SlimDemo/Jamfile b/src/tests/servers/app/SlimDemo/Jamfile +new file mode 100644 +index 0000000000..80b4ce28ed +--- /dev/null ++++ b/src/tests/servers/app/SlimDemo/Jamfile +@@ -0,0 +1,8 @@ ++SubDir HAIKU_TOP src tests servers app SlimDemo ; ++ ++UseHeaders [ FDirName os app ] ; ++UseHeaders [ FDirName os interface ] ; ++ ++SimpleTest SlimDemo : ++ main.c ++ : be [ TargetLibstdc++ ] [ TargetLibsupc++ ] ; +diff --git a/src/tests/servers/app/SlimDemo/LICENSE b/src/tests/servers/app/SlimDemo/LICENSE +new file mode 100644 +index 0000000000..86a4268fa9 +--- /dev/null ++++ b/src/tests/servers/app/SlimDemo/LICENSE +@@ -0,0 +1,31 @@ ++---------------------- ++Be Sample Code License ++---------------------- ++ ++Copyright 1991-1999, Be Incorporated. ++All rights reserved. ++ ++Redistribution and use in source and binary forms, with or without ++modification, are permitted provided that the following conditions ++are met: ++ ++1. Redistributions of source code must retain the above copyright ++ notice, this list of conditions, and the following disclaimer. ++ ++2. Redistributions in binary form must reproduce the above copyright ++ notice, this list of conditions, and the following disclaimer in the ++ documentation and/or other materials provided with the distribution. ++ ++3. The name of the author may not be used to endorse or promote products ++ derived from this software without specific prior written permission. ++ ++THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR ++IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ++OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR ++PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ++DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ++(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ++LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED ++AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR ++TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ++OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +diff --git a/src/tests/servers/app/SlimDemo/article b/src/tests/servers/app/SlimDemo/article +new file mode 100644 +index 0000000000..907610218a +--- /dev/null ++++ b/src/tests/servers/app/SlimDemo/article +@@ -0,0 +1,133 @@ ++Just How Much BeOS Do You Really Need? ++by Trey Boudreau -- ++ ++As developers, you're probably aware that BeOS is a ++layered system. The kernel is at the bottom with its ++drivers and modules, followed by a few libraries (root, ++net, textencoding), various servers (app, input, ++registrar, net), a few more libraries (be, netdev, ++tracker) and finally, applications. The whole collection ++makes a wonderfully synergistic system. But just how ++much of that stack do you really need? ++ ++ ++It Dependsโ„ข ++ ++What do you want to do? Occasionally, a demo coder ++thread erupts on BeDevTalk. Invariably, someone laments ++about the overhead of this or that feature of the OS. ++Without commenting on the relative merits of these ++discussions, I can tell you how to get as close to the ++silicon as you can without writing your own drivers. ++But to do that, we have to decide what we don't need. ++ ++ ++R.I.P. app_server ++ ++If you want to get close to the hardware, you've got to ++go around the app_server. Or better yet, not run it at ++all. Once you take this step, every other server in the ++OS is useless, so they can go too. Because networking ++runs as a server (at least until BONE shows up), ++networking is right out. No servers means no libbe.so ++and friends. Just about the only thing left is libroot.so, ++but that's quite a bit. You still have just about all the ++POSIX we support, plus access to BeOS-specific features, ++such as loading add-ons and creating semaphores. This ++means any class of driver for which you know the ioctl() ++API is still usable. We'll get back to this in a bit. ++ ++ ++Booting BeOS ++ ++By systematic trial and error, you'd find that you need ++very few files to boot BeOS. I'll save you some time ++and tell you what you need for the loader to boot to a ++particular partition. You'll definitely need the kernel ++(and zbeos on x86 hardware), and whatever ++drivers/busses/modules support your particular hardware. ++You'll need the accelerant for your graphics card(s). ++And you'll need two other files: /boot/beos/bin/sh and ++/boot/beos/system/boot/Bootscript. Bootscript can be ++empty, but it must exist. sh is the program the OS ++executes to get things started. BASH is nice, as shells ++go, but not needed for this operation, so I decided to ++replace it with my application. For getting started, ++you can just replace sh with your own app, but for grins ++I removed (almost) everything that wasn't required for ++my particular hardware. 'du -k /test/beos' reports a ++measly 2493K. ++ ++ ++The Demo ++ ++NOTE: I Am Not A Demo Coder. Besides, this was not ++really an exercise of my demo coding skills. I'm just ++the point man, and I've discovered these two tips/traps: ++ ++* To aid debugging, you'd like to keep a log file ++ (and/or generate serial debug output). Calling ++ freopen("/boot/var/log/demo.out", "w", stdout) is ++ useful in this respect. You can do what you like with ++ the other standard file handles. In my program I get ++ stdin from /dev/null and freopen("/boot/var/log/demo.err", ++ "w", stderr) in case something I load as an add-on uses ++ it. You can also call disable_debugger(1) and arrange ++ for your app to get all the signals itself, but I ++ don't do that in the demo. ++ ++* Set the ADDON_PATH and LIBRARY_PATH environment ++ variables. If you don't, load_add_on() will fail -- ++ even if you specify a full path to the add-on. ++ ++The meager demo application can be found at: ++ ++ ++If you've ever looked into the test harness shipped in ++the R4 Graphic Driver Kit, chunks of the sample code ++would be eerily familiar. Programming at this level is ++fairly unexciting, and this code is no exception. The ++main() function initializes the standard file descriptors ++and environment variables mentioned above, and then ++spawns and waits on a thread to handle the display ++chores. ++ ++The spawned thread hunts down and opens a graphics ++device, and then attempts to load the corresponding ++accelerant (R4 graphics drivers are two-part beasts, as ++is common under BeOS). After the accelerant is loaded, ++the code sets the first reported display mode and then ++begins the cheesy (and short) "animation." I didn't ++bother to set up and use hardware acceleration, but ++it's easy to do, and the harness program in the driver ++kit will show you the way. When the animation finishes, ++the accelerant is uninitialized and unloaded, and the ++device is closed. The thread terminates, and shortly ++thereafter so does the application, leaving the kernel ++silently in charge of the machine. ++ ++ ++B_DONT_DO_THAT ++ ++A friendly DTS staff member pointed out that while you ++can run the sample code while the full BeOS is running, ++you won't like the results. The current driver model ++doesn't do anything in the way of preventing you from ++opening and initializing the graphics device if it's ++already running. If you have specific combinations of ++graphics cards in your machine (and a BIOS that isn't ++broken, but that's another story), you can open and ++control the other graphics card(s). You might also ++consider not replacing /boot/beos/bin/sh on your ++primary boot partition, but rather making yourself a ++tiny test partition to play with. Caveat Programmer. ++ ++ ++Now What? ++ ++That's pretty much up to you. Access to other devices ++is mostly a matter of issuing the right ioctl() calls. ++If you can't find them documented in the BeBook, in ++headers, or in some newsletter article, e-mail me. One ++of you d00dz write a l33t dem0, and show me just how ++lame my example really is. +diff --git a/src/tests/servers/app/SlimDemo/main.c b/src/tests/servers/app/SlimDemo/main.c +new file mode 100644 +index 0000000000..02c0b322c2 +--- /dev/null ++++ b/src/tests/servers/app/SlimDemo/main.c +@@ -0,0 +1,544 @@ ++// main.c ++// ------ ++// A bare-bones graphics demo that uses direct driver access. ++// This is intended to run on an absolute bare-bones install ++// of BeOS (w/o app_server). See the newsletter article for ++// details. ++// ++// Copyright 2000, Be Incorporated. All Rights Reserved. ++// This file may be used under the terms of the Be Sample Code License. ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++int pick_device(const char *apath) { ++ DIR *d; ++ struct dirent *e; ++ char name_buf[1024]; ++ int fd = -1; ++ ++ /* open directory apath */ ++ d = opendir(apath); ++ if (!d) return B_ERROR; ++ /* get a list of devices, filtering out ".", "..", and "stub" */ ++ /* the only reason stub is disabled is that I know stub (aka R3-style) drivers don't support wait for retrace */ ++ while ((e = readdir(d)) != NULL) { ++ if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..") || !strcmp(e->d_name, "stub")) ++ continue; ++ strcpy(name_buf, apath); ++ strcat(name_buf, "/"); ++ strcat(name_buf, e->d_name); ++ fd = open(name_buf, B_READ_WRITE); ++ if (fd >= 0) break; ++ } ++ closedir(d); ++ return fd; ++} ++ ++image_id load_accelerant(int fd, GetAccelerantHook *hook) { ++ status_t result; ++ image_id image = -1; ++ int i; ++ char ++ signature[1024], ++ path[PATH_MAX]; ++ struct stat st; ++ const static directory_which vols[] = { ++ B_USER_ADDONS_DIRECTORY, ++ B_SYSTEM_ADDONS_DIRECTORY ++ }; ++ ++ /* get signature from driver */ ++ result = ioctl(fd, B_GET_ACCELERANT_SIGNATURE, &signature, sizeof(signature)); ++ if (result != B_OK) goto done; ++ debug_printf("B_GET_ACCELERANT_SIGNATURE returned ->%s<-\n", signature); ++ ++ // note failure by default ++ for(i=0; i < sizeof (vols) / sizeof (vols[0]); i++) { ++ ++ /* --- ++ compute directory path to common or beos addon directory on ++ floppy or boot volume ++ --- */ ++ ++ debug_printf("attempting to get path for %d (%d)\n", i, vols[i]); ++ if (find_directory (vols[i], -1, false, path, PATH_MAX) != B_OK) { ++ debug_printf("find directory failed\n"); ++ continue; ++ } ++ ++ strcat (path, "/accelerants/"); ++ strcat (path, signature); ++ ++ debug_printf("about to stat(%s)\n", path); ++ // don't try to load non-existant files ++ if (stat(path, &st) != 0) continue; ++ debug_printf("Trying to load accelerant: %s\n", path); ++ // load the image ++ image = load_add_on(path); ++ if (image >= 0) { ++ debug_printf("Accelerant loaded!\n"); ++ // get entrypoint from accelerant ++ result = get_image_symbol(image, B_ACCELERANT_ENTRY_POINT, ++#if defined(__INTEL__) ++ B_SYMBOL_TYPE_ANY, ++#else ++ B_SYMBOL_TYPE_TEXT, ++#endif ++ (void **)hook); ++ if (result == B_OK) { ++ init_accelerant ia; ++ debug_printf("Entry point %s() found\n", B_ACCELERANT_ENTRY_POINT); ++ ia = (init_accelerant)(*hook)(B_INIT_ACCELERANT, NULL); ++ debug_printf("init_accelerant is 0x%08lx\n", (uint32)ia); ++ if (ia && ((result = ia(fd)) == B_OK)) { ++ // we have a winner! ++ debug_printf("Accelerant %s accepts the job!\n", path); ++ break; ++ } else { ++ debug_printf("init_accelerant refuses the the driver: %ld\n", result); ++ } ++ } else { ++ debug_printf("Couldn't find the entry point :-(\n"); ++ } ++ // unload the accelerant, as we must be able to init! ++ unload_add_on(image); ++ } ++ if (image < 0) debug_printf("image failed to load with reason %.8lx (%s)\n", image, strerror(image)); ++ // mark failure to load image ++ image = -1; ++ } ++ ++ debug_printf("Add-on image id: %ld\n", image); ++ ++done: ++ return image; ++} ++ ++static const char *spaceToString(uint32 cs) { ++ const char *s; ++ switch (cs) { ++#define s2s(a) case a: s = #a ; break ++ s2s(B_RGB32); ++ s2s(B_RGBA32); ++ s2s(B_RGB32_BIG); ++ s2s(B_RGBA32_BIG); ++ s2s(B_RGB16); ++ s2s(B_RGB16_BIG); ++ s2s(B_RGB15); ++ s2s(B_RGBA15); ++ s2s(B_RGB15_BIG); ++ s2s(B_RGBA15_BIG); ++ s2s(B_CMAP8); ++ s2s(B_GRAY8); ++ s2s(B_GRAY1); ++ s2s(B_YCbCr422); ++ s2s(B_YCbCr420); ++ s2s(B_YUV422); ++ s2s(B_YUV411); ++ s2s(B_YUV9); ++ s2s(B_YUV12); ++ default: ++ s = "unknown"; break; ++#undef s2s ++ } ++ return s; ++} ++ ++void dump_mode(display_mode *dm) { ++ display_timing *t = &(dm->timing); ++ debug_printf(" pixel_clock: %ldKHz\n", t->pixel_clock); ++ debug_printf(" H: %4d %4d %4d %4d\n", t->h_display, t->h_sync_start, t->h_sync_end, t->h_total); ++ debug_printf(" V: %4d %4d %4d %4d\n", t->v_display, t->v_sync_start, t->v_sync_end, t->v_total); ++ debug_printf(" timing flags:"); ++ if (t->flags & B_BLANK_PEDESTAL) debug_printf(" B_BLANK_PEDESTAL"); ++ if (t->flags & B_TIMING_INTERLACED) debug_printf(" B_TIMING_INTERLACED"); ++ if (t->flags & B_POSITIVE_HSYNC) debug_printf(" B_POSITIVE_HSYNC"); ++ if (t->flags & B_POSITIVE_VSYNC) debug_printf(" B_POSITIVE_VSYNC"); ++ if (t->flags & B_SYNC_ON_GREEN) debug_printf(" B_SYNC_ON_GREEN"); ++ if (!t->flags) debug_printf(" (none)\n"); ++ else debug_printf("\n"); ++ debug_printf(" refresh rate: %4.2f\n", ((double)t->pixel_clock * 1000) / ((double)t->h_total * (double)t->v_total)); ++ debug_printf(" color space: %s\n", spaceToString(dm->space)); ++ debug_printf(" virtual size: %dx%d\n", dm->virtual_width, dm->virtual_height); ++ debug_printf("dispaly start: %d,%d\n", dm->h_display_start, dm->v_display_start); ++ ++ debug_printf(" mode flags:"); ++ if (dm->flags & B_SCROLL) debug_printf(" B_SCROLL"); ++ if (dm->flags & B_8_BIT_DAC) debug_printf(" B_8_BIT_DAC"); ++ if (dm->flags & B_HARDWARE_CURSOR) debug_printf(" B_HARDWARE_CURSOR"); ++ if (dm->flags & B_PARALLEL_ACCESS) debug_printf(" B_PARALLEL_ACCESS"); ++// if (dm->flags & B_SUPPORTS_OVERLAYS) debug_printf(" B_SUPPORTS_OVERLAYS"); ++ if (!dm->flags) debug_printf(" (none)\n"); ++ else debug_printf("\n"); ++} ++ ++status_t get_and_set_mode(GetAccelerantHook gah, display_mode *dm) { ++ ++ accelerant_mode_count gmc; ++ uint32 mode_count; ++ get_mode_list gml; ++ display_mode *mode_list, target, high, low; ++ propose_display_mode pdm; ++ status_t result = B_ERROR; ++ set_display_mode sdm; ++ ++ /* find the propose mode hook */ ++ pdm = gah(B_PROPOSE_DISPLAY_MODE, NULL); ++ if (!pdm) { ++ debug_printf("No B_PROPOSE_DISPLAY_MODE\n"); ++ goto exit0; ++ } ++ /* and the set mode hook */ ++ sdm = gah(B_SET_DISPLAY_MODE, NULL); ++ if (!sdm) { ++ debug_printf("No B_SET_DISPLAY_MODE\n"); ++ goto exit0; ++ } ++ ++ /* how many modes does the driver support */ ++ gmc = gah(B_ACCELERANT_MODE_COUNT, NULL); ++ if (!gmc) { ++ debug_printf("No B_ACCELERANT_MODE_COUNT\n"); ++ goto exit0; ++ } ++ mode_count = gmc(); ++ debug_printf("mode_count = %lu\n", mode_count); ++ if (mode_count == 0) goto exit0; ++ ++ /* get a list of graphics modes from the driver */ ++ gml = gah(B_GET_MODE_LIST, NULL); ++ if (!gml) { ++ debug_printf("No B_GET_MODE_LIST\n"); ++ goto exit0; ++ } ++ mode_list = (display_mode *)calloc(sizeof(display_mode), mode_count); ++ if (!mode_list) { ++ debug_printf("Couldn't calloc() for mode list\n"); ++ goto exit0; ++ } ++ if (gml(mode_list) != B_OK) { ++ debug_printf("mode list retrieval failed\n"); ++ goto free_mode_list; ++ } ++ ++ /* take the first mode in the list */ ++ target = high = low = *mode_list; ++ /* make as tall a virtual height as possible */ ++ target.virtual_height = high.virtual_height = 0xffff; ++ /* propose the display mode */ ++ if (pdm(&target, &low, &high) == B_ERROR) { ++ debug_printf("propose_display_mode failed\n"); ++ goto free_mode_list; ++ } ++ debug_printf("Target display mode: \n"); ++ dump_mode(&target); ++ /* we got a display mode, now set it */ ++ if (sdm(&target) == B_ERROR) { ++ debug_printf("set display mode failed\n"); ++ goto free_mode_list; ++ } ++ /* note the mode and success */ ++ *dm = target; ++ result = B_OK; ++ ++free_mode_list: ++ free(mode_list); ++exit0: ++ return result; ++} ++ ++void get_frame_buffer(GetAccelerantHook gah, frame_buffer_config *fbc) { ++ get_frame_buffer_config gfbc; ++ gfbc = gah(B_GET_FRAME_BUFFER_CONFIG, NULL); ++ gfbc(fbc); ++} ++ ++sem_id get_sem(GetAccelerantHook gah) { ++ accelerant_retrace_semaphore ars; ++ ars = gah(B_ACCELERANT_RETRACE_SEMAPHORE, NULL); ++ return ars(); ++} ++ ++void set_palette(GetAccelerantHook gah) { ++ set_indexed_colors sic; ++ sic = gah(B_SET_INDEXED_COLORS, NULL); ++ if (sic) { ++ /* booring grey ramp for now */ ++ uint8 map[3 * 256]; ++ uint8 *p = map; ++ int i; ++ for (i = 0; i < 256; i++) { ++ *p++ = i; ++ *p++ = i; ++ *p++ = i; ++ } ++ sic(256, 0, map, 0); ++ } ++} ++ ++void paint_for_blit(display_mode *dm, frame_buffer_config *fbc) { ++ switch (dm->space & ~0x3000) { ++ case B_CMAP8: { ++ int16 x, y; ++ uint8 *fb = (uint8 *)fbc->frame_buffer; ++ debug_printf(" frame buffer is 8bpp\n"); ++ /* make a checkerboard pattern */ ++ for (y = 0; y < (dm->virtual_height >> 1); y++) { ++ for (x = 0; x < (dm->virtual_width >> 1); x++) { ++ fb[x] = 0; ++ } ++ for (; x < dm->virtual_width; x++) { ++ fb[x] = 0xff; ++ } ++ fb += fbc->bytes_per_row; ++ } ++ for (; y < dm->virtual_height; y++) { ++ for (x = 0; x < (dm->virtual_width >> 1); x++) { ++ fb[x] = 0xff; ++ } ++ for (; x < dm->virtual_width; x++) { ++ fb[x] = x; // 0 ++ } ++ fb += fbc->bytes_per_row; ++ } ++ fb = (uint8 *)(((uint8 *)fbc->frame_buffer) + fbc->bytes_per_row); ++ fb += 1; ++ for (y = 0; y < 40; y++) { ++ for (x = 0; x < 40; x++) { ++ fb[x] = 0x77; ++ } ++ fb = (uint8 *)(((uint8 *)fb) + fbc->bytes_per_row); ++ } ++ fb = (uint8 *)(((uint8 *)fbc->frame_buffer) + fbc->bytes_per_row * 11); ++ fb += 11; ++ for (y = 0; y < 20; y++) { ++ for (x = 0; x < 20; x++) { ++ fb[x] = 0; ++ } ++ fb = (uint8 *)(((uint8 *)fb) + fbc->bytes_per_row); ++ } ++ } break; ++ case B_RGB16_BIG: ++ case B_RGB16_LITTLE: { ++ int x, y; ++ uint16 *fb = (uint16 *)fbc->frame_buffer; ++ debug_printf(" frame buffer is 16bpp\n"); ++ /* make a checkerboard pattern */ ++ for (y = 0; y < (dm->virtual_height >> 1); y++) { ++ for (x = 0; x < (dm->virtual_width >> 1); x++) { ++ fb[x] = 0; ++ } ++ for (; x < dm->virtual_width; x++) { ++ fb[x] = 0xffff; ++ } ++ fb = (uint16 *)(((uint8 *)fb) + fbc->bytes_per_row); ++ } ++ for (; y < dm->virtual_height; y++) { ++ for (x = 0; x < (dm->virtual_width >> 1); x++) { ++ fb[x] = 0xffff; ++ } ++ for (; x < dm->virtual_width; x++) { ++ fb[x] = 0; ++ } ++ fb = (uint16 *)((uint8 *)fb + fbc->bytes_per_row); ++ } ++ fb = (uint16 *)(((uint8 *)fbc->frame_buffer) + fbc->bytes_per_row); ++ fb += 1; ++ for (y = 0; y < 40; y++) { ++ for (x = 0; x < 40; x++) { ++ fb[x] = 0x7777; ++ } ++ fb = (uint16 *)(((uint8 *)fb) + fbc->bytes_per_row); ++ } ++ fb = (uint16 *)(((uint8 *)fbc->frame_buffer) + fbc->bytes_per_row * 11); ++ fb += 11; ++ for (y = 0; y < 20; y++) { ++ for (x = 0; x < 20; x++) { ++ fb[x] = 0; ++ } ++ fb = (uint16 *)(((uint8 *)fb) + fbc->bytes_per_row); ++ } ++ } break; ++ case B_RGB15_BIG: ++ case B_RGBA15_BIG: ++ case B_RGB15_LITTLE: ++ case B_RGBA15_LITTLE: { ++ int x, y; ++ uint16 *fb = (uint16 *)fbc->frame_buffer; ++ uint16 pixel; ++ debug_printf(" frame buffer is 15bpp\n"); ++ /* make a checkerboard pattern */ ++ for (y = 0; y < (dm->virtual_height >> 1); y++) { ++ for (x = 0; x < (dm->virtual_width >> 1); x++) { ++ fb[x] = 0; ++ } ++ for (; x < dm->virtual_width; x++) { ++ fb[x] = 0x7fff; ++ } ++ fb = (uint16 *)(((uint8 *)fb) + fbc->bytes_per_row); ++ } ++ for (; y < dm->virtual_height; y++) { ++ for (x = 0; x < (dm->virtual_width >> 1); x++) { ++ fb[x] = 0x7fff; ++ } ++ for (; x < dm->virtual_width; x++) { ++ fb[x] = 0; ++ } ++ fb = (uint16 *)((uint8 *)fb + fbc->bytes_per_row); ++ } ++ fb = (uint16 *)(((uint8 *)fbc->frame_buffer) + fbc->bytes_per_row); ++ fb += 1; ++ for (y = 0; y < 42; y++) { ++ pixel = 0x7777; ++ if (y != 40) ++ for (x = 0; x < 42; x++) { ++ if (x != 40) fb[x] = pixel += 0x0011; ++ } ++ fb = (uint16 *)(((uint8 *)fb) + fbc->bytes_per_row); ++ } ++ fb = (uint16 *)(((uint8 *)fbc->frame_buffer) + fbc->bytes_per_row * 11); ++ fb += 11; ++ for (y = 0; y < 20; y++) { ++ for (x = 0; x < 20; x++) { ++ fb[x] = 0; ++ } ++ fb = (uint16 *)(((uint8 *)fb) + fbc->bytes_per_row); ++ } ++ } break; ++ case B_RGB32_BIG: ++ case B_RGBA32_BIG: ++ case B_RGB32_LITTLE: ++ case B_RGBA32_LITTLE: { ++ int x, y; ++ uint32 *fb = (uint32 *)fbc->frame_buffer; ++ debug_printf(" frame buffer is 32bpp\n"); ++ /* make a checkerboard pattern */ ++ for (y = 0; y < (dm->virtual_height >> 1); y++) { ++ for (x = 0; x < (dm->virtual_width >> 1); x++) { ++ fb[x] = 0; ++ } ++ for (; x < dm->virtual_width; x++) { ++ fb[x] = 0xffffffff; ++ } ++ fb = (uint32 *)((uint8 *)fb + fbc->bytes_per_row); ++ } ++ for (; y < dm->virtual_height; y++) { ++ for (x = 0; x < (dm->virtual_width >> 1); x++) { ++ fb[x] = 0xffffffff; ++ } ++ for (; x < dm->virtual_width; x++) { ++ fb[x] = 0; ++ } ++ fb = (uint32 *)((uint8 *)fb + fbc->bytes_per_row); ++ } ++ fb = (uint32 *)(((uint8 *)fbc->frame_buffer) + fbc->bytes_per_row); ++ fb += 1; ++ for (y = 0; y < 40; y++) { ++ for (x = 0; x < 40; x++) { ++ fb[x] = 0x77777777; ++ } ++ fb = (uint32 *)(((uint8 *)fb) + fbc->bytes_per_row); ++ } ++ fb = (uint32 *)(((uint8 *)fbc->frame_buffer) + fbc->bytes_per_row * 11); ++ fb += 11; ++ for (y = 0; y < 20; y++) { ++ for (x = 0; x < 20; x++) { ++ fb[x] = 0; ++ } ++ fb = (uint32 *)(((uint8 *)fb) + fbc->bytes_per_row); ++ } ++ } break; ++ default: ++ debug_printf("YIKES! frame buffer shape unknown!\n"); ++ } ++} ++ ++status_t animate(GetAccelerantHook gah, display_mode *dm) { ++ debug_printf("animate()\n"); ++ frame_buffer_config fbc; ++ sem_id retrace = get_sem(gah); ++ move_display_area mda = gah(B_MOVE_DISPLAY, NULL); ++ int i; ++ ++ /* set the palette if in an 8bpp indexed mode */ ++ if (dm->space == B_CMAP8) set_palette(gah); ++ /* find out about the frame buffer */ ++ get_frame_buffer(gah, &fbc); ++ debug_printf("framebuffer: %p\n", fbc.frame_buffer); ++ ++ /* paint the display */ ++ paint_for_blit(dm, &fbc); ++ /* wait a while */ ++ if (mda) ++ for (i = 0; i < dm->virtual_height - dm->timing.v_display; i++) { ++ mda(0, i); ++ if (retrace >= 0) acquire_sem(retrace); ++ else snooze(1000000 / 59); ++ } ++ else snooze(1000000 * 60); ++ ++ return B_OK; ++} ++ ++int32 render_func(void *arg) { ++ int fd; ++ GetAccelerantHook gah; ++ image_id image; ++ uninit_accelerant ua; ++ display_mode dm; ++ ++ /* find a graphic device to open */ ++ fd = pick_device("/dev/graphics"); ++ if (fd < 0) { ++ debug_printf("Can't open device: %s (%s)\n", strerror(fd), strerror(errno)); ++ return fd; ++ } ++ /* load the accelerant */ ++ image = load_accelerant(fd, &gah); ++ if (image < 0) goto close_driver; ++ ++ /* get and set a display mode */ ++ if (get_and_set_mode(gah, &dm) != B_OK) goto close_accelerant; ++ ++ /* do the animation */ ++ animate(gah, &dm); ++ ++close_accelerant: ++ /* shut down the accelerant */ ++ ua = gah(B_UNINIT_ACCELERANT, NULL); ++ if (ua) ua(); ++ ++ /* unload add-on */ ++ unload_add_on(image); ++ ++close_driver: ++ /* close the driver */ ++ close(fd); ++ return B_OK; ++} ++ ++int main(int argc, char **argv) ++{ ++ thread_id render; ++ status_t result; ++ ++ /* spawn the rendering thread */ ++ render = spawn_thread(render_func, "render", B_REAL_TIME_DISPLAY_PRIORITY, NULL); ++ /* wait for the threads to finish */ ++ if (render && (resume_thread(render) == B_OK)) ++ wait_for_thread(render, &result); ++ ++ /* all done */ ++ return B_OK; ++} +-- +2.30.2 + diff --git a/patchset-hrev55144/0057-AutoDeleter-add-VMAddressSpacePutter-DeviceNodePutte.patch b/patchset-hrev55144/0057-AutoDeleter-add-VMAddressSpacePutter-DeviceNodePutte.patch new file mode 100644 index 0000000..3713974 --- /dev/null +++ b/patchset-hrev55144/0057-AutoDeleter-add-VMAddressSpacePutter-DeviceNodePutte.patch @@ -0,0 +1,52 @@ +From 66186b443d6ffa6aa54911c34579e653f593938a Mon Sep 17 00:00:00 2001 +From: X512 +Date: Wed, 26 May 2021 22:23:38 +0900 +Subject: AutoDeleter: add VMAddressSpacePutter, DeviceNodePutter + +Change-Id: I705de24f6a87287943814e748d5a02e43b029e60 +--- + headers/private/shared/AutoDeleterDrivers.h | 14 ++++++++++++++ + 1 file changed, 14 insertions(+) + +diff --git a/headers/private/shared/AutoDeleterDrivers.h b/headers/private/shared/AutoDeleterDrivers.h +index c290ede37f..0d4b98b564 100644 +--- a/headers/private/shared/AutoDeleterDrivers.h ++++ b/headers/private/shared/AutoDeleterDrivers.h +@@ -11,6 +11,8 @@ + #if defined(_KERNEL_MODE) && !defined(_BOOT_MODE) + #include + #include ++#include ++#include + #endif + + +@@ -23,6 +25,14 @@ typedef CObjectDeleter DriverSettingsUnl + + typedef CObjectDeleter VnodePutter; + typedef CObjectDeleter DescriptorPutter; ++typedef MethodDeleter VMAddressSpacePutter; ++ ++#if __GNUC__ >= 4 ++ ++template ++using DeviceNodePutter = FieldFunctionDeleter; ++ ++#endif + + #endif + +@@ -36,6 +46,10 @@ using ::BPrivate::DriverSettingsUnloader; + + using ::BPrivate::VnodePutter; + using ::BPrivate::DescriptorPutter; ++using ::BPrivate::VMAddressSpacePutter; ++#if __GNUC__ >= 4 ++using ::BPrivate::DeviceNodePutter; ++#endif + + #endif + +-- +2.30.2 + diff --git a/patchset-hrev55144/0058-bus_managers-fdt-rewrite-to-support-device-manager-n.patch b/patchset-hrev55144/0058-bus_managers-fdt-rewrite-to-support-device-manager-n.patch new file mode 100644 index 0000000..217254d --- /dev/null +++ b/patchset-hrev55144/0058-bus_managers-fdt-rewrite-to-support-device-manager-n.patch @@ -0,0 +1,1345 @@ +From 80927c071db215c91104b59fd2e4be45f928eed6 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 24 May 2021 06:24:56 +0900 +Subject: bus_managers/fdt: rewrite to support device manager node tree + +Breaks previous fdt module clients. + +Change-Id: I8bfdca40a77c041ddef51488e1995e5d43edb340 +--- + headers/os/drivers/bus/FDT.h | 42 +- + src/add-ons/kernel/bus_managers/fdt/Jamfile | 6 +- + src/add-ons/kernel/bus_managers/fdt/fdt.cpp | 210 --------- + .../kernel/bus_managers/fdt/fdt_module.cpp | 441 ++++++++++++++++++ + .../kernel/bus_managers/fdt/fdt_serial.cpp | 194 -------- + .../kernel/bus_managers/fdt/fdt_serial.h | 19 - + .../kernel/bus_managers/fdt/fdt_support.cpp | 310 ------------ + .../kernel/bus_managers/fdt/fdt_support.h | 24 - + 8 files changed, 457 insertions(+), 789 deletions(-) + delete mode 100644 src/add-ons/kernel/bus_managers/fdt/fdt.cpp + create mode 100644 src/add-ons/kernel/bus_managers/fdt/fdt_module.cpp + delete mode 100644 src/add-ons/kernel/bus_managers/fdt/fdt_serial.cpp + delete mode 100644 src/add-ons/kernel/bus_managers/fdt/fdt_serial.h + delete mode 100644 src/add-ons/kernel/bus_managers/fdt/fdt_support.cpp + delete mode 100644 src/add-ons/kernel/bus_managers/fdt/fdt_support.h + +diff --git a/headers/os/drivers/bus/FDT.h b/headers/os/drivers/bus/FDT.h +index e391a653d3..a5a49b5cf7 100644 +--- a/headers/os/drivers/bus/FDT.h ++++ b/headers/os/drivers/bus/FDT.h +@@ -6,40 +6,26 @@ + #ifndef _DRIVERS_BUS_FDT_H + #define _DRIVERS_BUS_FDT_H + +-#include ++#include + +-#ifdef __cplusplus +-extern "C" { +-#endif + +-typedef int fdt_device_node; ++struct fdt_bus; ++struct fdt_device; + +-struct fdt_device_info { +- const char *compatible; +- status_t (*init)(struct fdt_module_info *fdt, fdt_device_node node, void *cookie); ++struct fdt_bus_module_info { ++ driver_module_info info; ++ device_node* (*node_by_phandle)(fdt_bus* bus, int phandle); + }; + +-struct fdt_module_info { +- bus_manager_info binfo; +- +- // basic call for triggering callbacks for supported devices +- // scans the whole FDT tree once and calls the info.init function +- // when a matching device is found. +- status_t (*setup_devices)(struct fdt_device_info *info, int count, void *cookie); +- +- // map physical "reg" range "index" of node "node", and return the virtual address in '*_address' +- // and return the area ID or error if not able to. +- area_id (*map_reg_range)(fdt_device_node node, int index, void **_address); +- +- // return entry "index" out of "interrupts" property for node "node", or a negative error code on failure. +- int (*get_interrupt)(fdt_device_node node, int index); ++struct fdt_device_module_info{ ++ driver_module_info info; ++ device_node* (*get_bus)(fdt_device* dev); ++ const char* (*get_name)(fdt_device* dev); ++ const void* (*get_prop)(fdt_device* dev, const char* name, int* len); ++ bool (*get_reg)(fdt_device* dev, uint32 ord, uint64* regs, uint64* len); ++ bool (*get_interrupt)(fdt_device* dev, uint32 ord, ++ device_node** interruptController, uint64* interrupt); + }; + +-#define B_FDT_MODULE_NAME "bus_managers/fdt/v1" +- +- +-#ifdef __cplusplus +-} +-#endif + + #endif // _DRIVERS_BUS_FDT_H +diff --git a/src/add-ons/kernel/bus_managers/fdt/Jamfile b/src/add-ons/kernel/bus_managers/fdt/Jamfile +index 92d5f99634..47688d218d 100644 +--- a/src/add-ons/kernel/bus_managers/fdt/Jamfile ++++ b/src/add-ons/kernel/bus_managers/fdt/Jamfile +@@ -19,17 +19,15 @@ local earlyFDTHelpers = + ; + + KernelAddon fdt : +- fdt.cpp +-# $(libFDTSources) ++ fdt_module.cpp ++ $(libFDTSources) + ; + + BootStaticLibrary boot_fdt : +- $(earlyFDTHelpers) + $(libFDTSources) + ; + + KernelStaticLibrary kernel_fdt : +- $(earlyFDTHelpers) + $(libFDTSources) + ; + +diff --git a/src/add-ons/kernel/bus_managers/fdt/fdt.cpp b/src/add-ons/kernel/bus_managers/fdt/fdt.cpp +deleted file mode 100644 +index 5a4fc2a9da..0000000000 +--- a/src/add-ons/kernel/bus_managers/fdt/fdt.cpp ++++ /dev/null +@@ -1,210 +0,0 @@ +-/* +- * Copyright 2014, Ithamar R. Adema +- * All rights reserved. Distributed under the terms of the MIT License. +- */ +- +-#include +-#include +-#include +- +-#include // isprint +-#include // snprintf +- +-extern "C" { +-#include +-#include +-#include +-}; +- +-extern void *gFDT; +- +-static status_t fdt_setup_devices(struct fdt_device_info *info, int count, void *cookie); +- +-static const char *sTabTab = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"; +-#define DS "%.*s" +-#define DA depth - 1, sTabTab +- +-static void +-fdt_dump_value(const char *data, int32 len, int depth) +-{ +- char str[128]; +- char astr[32]; +- char *p; +- int l; +- int i; +- +- for (i = 0; i < len; ) { +- p = str; +- l = sizeof(str); +- for (; i < len && (p == str || (i % 16 != 0)); i++) { +- snprintf(p, l - 1, "%02x ", data[i]); +- l -= strlen(p); +- p += strlen(p); +- astr[i % 16] = isprint(data[i]) ? data[i] : '.'; +- astr[i % 16] = isprint(data[i]) ? data[i] : '.'; +- astr[(i % 16) + 1] = '\0'; +- } +- dprintf(DS" %-48.48s %s\n", DA, str, astr); +- } +-} +- +-static int +-fdt_debug_tree(int argc, char **argv) +-{ +- bool dump_props = false, dump_values = false; +- +- if (gFDT == NULL) { +- dprintf("No fdt tree\n"); +- return 0; +- } +- +- dprintf("fdt tree:\n"); +- +- int node = -1; +- int depth = 0; +- while ((node = fdt_next_node(gFDT, node, &depth)) >= 0) { +- dprintf(DS"node at %d: '%s'\n", DA, node, +- fdt_get_name(gFDT, node, NULL)); +- +- if (dump_props) { +- int prop, len; +- const struct fdt_property *property; +- prop = fdt_first_property_offset(gFDT, node); +- while (prop >= 0) { +- property = fdt_get_property_by_offset(gFDT, prop, &len); +- if (property == NULL) { +- dprintf("getting prop at %d: %s\n", prop, fdt_strerror(len)); +- break; +- } +- dprintf(DS" prop at %d: '%s', len %d\n", DA, prop, +- fdt_string(gFDT, fdt32_to_cpu(property->nameoff)), +- fdt32_to_cpu(property->len)); +- +- if (dump_values) +- fdt_dump_value(property->data, fdt32_to_cpu(property->len), depth); +- +- prop = fdt_next_property_offset(gFDT, prop); +- } +- } +- } +- +- return 0; +-} +- +- +-static int32 +-bus_std_ops(int32 op, ...) +-{ +- switch (op) { +- case B_MODULE_INIT: +- if (gFDT == NULL || fdt_totalsize(gFDT) <= 0) +- return B_BAD_DATA; +- +- add_debugger_command("fdt", &fdt_debug_tree, "Show Flattened Device Tree"); +- break; +- +- case B_MODULE_UNINIT: +- // Nothing to free, gFDT allocation is managed by kernel +- break; +- +- default: +- return EINVAL; +- } +- +- return B_OK; +-} +- +-static int +-fdt_get_interrupt(fdt_device_node node, int index) +-{ +- const struct fdt_property *prop; +- int lenp; +- +- prop = fdt_get_property(gFDT, node, "interrupts", &lenp); +- if (prop == NULL) +- return B_NAME_NOT_FOUND; +- +- int numRanges = lenp / sizeof(uint32); +- if (index > numRanges) +- return B_BAD_INDEX; +- +- return fdt32_to_cpu(((uint32*)prop->data)[index]); +-} +- +-static area_id +-fdt_map_reg_range(fdt_device_node node, int index, void **_address) +-{ +- char name[B_OS_NAME_LENGTH] = "ingo_asked_me_to_name_this"; +- const struct fdt_property *prop; +- int lenp; +- +- prop = fdt_get_property(gFDT, node, "reg", &lenp); +- if (prop == NULL) +- return B_NAME_NOT_FOUND; +- +- int numRanges = lenp / (sizeof(uint32) * 2); +- if (index > numRanges) +- return B_BAD_INDEX; +- +- //snprintf(name, sizeof(name), "%s_reg_%d", fdt_get_name(gFDT, node, NULL), index); +- +- uint32* regs = (uint32*)prop->data; +- phys_addr_t rangeStart = (phys_addr_t)fdt32_to_cpu(regs[index*2]); +- uint32 rangeSize = fdt32_to_cpu(regs[index*2+1]); +- dprintf("fdt_map_reg_range: found reg range %p/%lu\n", (void*)rangeStart, rangeSize); +- +- return map_physical_memory(name, rangeStart, rangeSize, +- 0, B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA, (void**)_address); +-} +- +-static struct fdt_module_info sModuleInfo = { +- // First the bus_manager_info: +- { +- { +- "bus_managers/fdt/v1", +- B_KEEP_LOADED, // Keep loaded, even if no driver requires it +- bus_std_ops +- }, +- NULL // the rescan function +- }, +- +- fdt_setup_devices, +- fdt_map_reg_range, +- fdt_get_interrupt, +-}; +- +- +-module_info *modules[] = { +- (module_info *)&sModuleInfo, +- NULL +-}; +- +-static status_t +-fdt_setup_devices(struct fdt_device_info *info, int count, void *cookie) +-{ +- int numDevs = 0; +- +- if (gFDT == NULL) +- return B_NOT_INITIALIZED; +- +- int node = -1; +- int depth = 0; +- while ((node = fdt_next_node(gFDT, node, &depth)) >= 0) { +- for (int i=0; i < count; i++) { +- if (fdt_node_check_compatible(gFDT, node, info[i].compatible) == 0) { +- status_t result = info[i].init(&sModuleInfo, node, cookie); +- if (result != B_OK) { +- // TODO handle return value from init somehow? +- dprintf("fdt: device '%s' failed to initialize!\n", +- fdt_get_name(gFDT, node, NULL)); +- } else { +- ++numDevs; +- } +- } +- } +- } +- +- return (numDevs <= 0) ? B_ENTRY_NOT_FOUND : B_OK; +-} +- +- +diff --git a/src/add-ons/kernel/bus_managers/fdt/fdt_module.cpp b/src/add-ons/kernel/bus_managers/fdt/fdt_module.cpp +new file mode 100644 +index 0000000000..7e7f62e3bf +--- /dev/null ++++ b/src/add-ons/kernel/bus_managers/fdt/fdt_module.cpp +@@ -0,0 +1,441 @@ ++/* ++ * Copyright 2014, Ithamar R. Adema ++ * All rights reserved. Distributed under the terms of the MIT License. ++ */ ++ ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++#include ++ ++extern "C" { ++#include ++#include ++#include ++}; ++ ++//#define TRACE_FDT ++#ifdef TRACE_FDT ++#define TRACE(x...) dprintf(x) ++#else ++#define TRACE(x...) ++#endif ++ ++ ++extern void* gFDT; ++ ++device_manager_info* gDeviceManager; ++ ++extern fdt_bus_module_info gBusModule; ++extern fdt_device_module_info gDeviceModule; ++ ++//#pragma mark - ++ ++struct fdt_bus { ++ device_node* node; ++ HashMap, device_node*> phandles; ++}; ++ ++struct fdt_device { ++ device_node* node; ++ device_node* bus; ++}; ++ ++ ++static status_t ++RegisterNode(fdt_bus* bus, int node, device_node* parentDev, ++ device_node*& curDev) ++{ ++ TRACE("RegisterNode('%s', %p)\n", ++ fdt_get_name(gFDT, node, NULL), parentDev); ++ ++ const void* prop; int propLen; ++ device_attr attrs[8]; ++ device_attr* attr = attrs; ++ ++ const char *name = fdt_get_name(gFDT, node, NULL); ++ *attr++ = (device_attr){ ++ B_DEVICE_BUS, B_STRING_TYPE, {string: "fdt"}}; ++ *attr++ = (device_attr){ ++ B_DEVICE_PRETTY_NAME, B_STRING_TYPE, { ++ string: (strcmp(name, "") != 0) ? name : "Root"}}; ++ *attr++ = (device_attr){ ++ "fdt/node", B_UINT32_TYPE, {ui32: (uint32)node}}; ++ *attr++ = (device_attr){ ++ "fdt/name", B_STRING_TYPE, {string: name}}; ++ ++ prop = fdt_getprop(gFDT, node, "device_type", &propLen); ++ if (prop != NULL) ++ *attr++ = (device_attr){ ++ "fdt/device_type", B_STRING_TYPE, {string: (const char*)prop}}; ++ ++ prop = fdt_getprop(gFDT, node, "compatible", &propLen); ++ if (prop != NULL) ++ *attr++ = (device_attr){ ++ "fdt/compatible", B_STRING_TYPE, {string: (const char*)prop}}; ++ ++ *attr = {0}; ++ ++ status_t res = gDeviceManager->register_node( ++ parentDev, "bus_managers/fdt/driver_v1", attrs, NULL, &curDev); ++ if (res < B_OK) ++ return res; ++ ++ prop = fdt_getprop(gFDT, node, "phandle", &propLen); ++ if (prop != NULL) ++ bus->phandles.Put(fdt32_to_cpu(*(uint32_t*)prop), curDev); ++ ++ return B_OK; ++} ++ ++ ++static void ++TraverseFdt(fdt_bus* bus, int &node, int &depth, device_node* parentDev) ++{ ++ int curDepth = depth; ++#if 0 ++ for (int i = 0; i < depth; i++) dprintf(" "); ++ dprintf("node('%s')\n", fdt_get_name(gFDT, node, NULL)); ++#endif ++ device_node* curDev; ++ RegisterNode(bus, node, parentDev, curDev); ++ ++ node = fdt_next_node(gFDT, node, &depth); ++ while (node >= 0 && depth == curDepth + 1) { ++ TraverseFdt(bus, node, depth, curDev); ++ } ++} ++ ++ ++//#pragma mark bus ++ ++static int32 ++fdt_bus_std_ops(int32 op, ...) ++{ ++ switch (op) { ++ case B_MODULE_INIT: ++ TRACE("fdt root init\n"); ++ return B_OK; ++ ++ case B_MODULE_UNINIT: ++ TRACE("fdt root uninit\n"); ++ return B_OK; ++ } ++ ++ return B_BAD_VALUE; ++} ++ ++ ++ ++ ++static float ++fdt_bus_supports_device(device_node* parent) ++{ ++ TRACE("fdt_bus_supports_device\n"); ++ ++ // make sure parent is really device root ++ const char* bus; ++ if (gDeviceManager->get_attr_string(parent, B_DEVICE_BUS, &bus, false)) ++ return B_ERROR; ++ ++ if (strcmp(bus, "root")) ++ return 0.0; ++ ++ return 1.0; ++} ++ ++ ++static status_t ++fdt_bus_register_device(device_node* parent) ++{ ++ TRACE("+fdt_bus_register_device\n"); ++ struct ScopeExit { ++ ScopeExit() {TRACE("-fdt_bus_register_device\n");} ++ } scopeExit; ++ ++ device_attr attrs[] = { ++ {B_DEVICE_PRETTY_NAME, B_STRING_TYPE, {string: "FDT"}}, ++ {B_DEVICE_FLAGS, B_UINT32_TYPE, {ui32: B_KEEP_DRIVER_LOADED}}, ++ {} ++ }; ++ ++ return gDeviceManager->register_node( ++ parent, "bus_managers/fdt/root/driver_v1", attrs, NULL, NULL); ++} ++ ++ ++static status_t ++fdt_bus_init(device_node* node, void** cookie) ++{ ++ TRACE("fdt_bus_init\n"); ++ ++ ObjectDeleter bus(new(std::nothrow) fdt_bus()); ++ if (!bus.IsSet()) ++ return B_NO_MEMORY; ++ ++ bus->node = node; ++ *cookie = bus.Detach(); ++ return B_OK; ++} ++ ++ ++static void ++fdt_bus_uninit(void* cookie) ++{ ++ TRACE("fdt_bus_uninit\n"); ++ ++ ObjectDeleter bus((fdt_bus*)cookie); ++} ++ ++ ++static status_t ++fdt_bus_register_child_devices(void* cookie) ++{ ++ TRACE("fdt_bus_register_child_devices\n"); ++ ++ fdt_bus* bus = (fdt_bus*)cookie; ++ ++ int node = -1, depth = -1; ++ node = fdt_next_node(gFDT, node, &depth); ++ TraverseFdt(bus, node, depth, bus->node); ++ ++ return B_OK; ++} ++ ++ ++device_node* fdt_bus_node_by_phandle(fdt_bus* bus, int phandle) ++{ ++ ASSERT(bus != NULL); ++ ++ device_node** devNode; ++ if (!bus->phandles.Get(phandle, devNode)) ++ return NULL; ++ ++ return *devNode; ++} ++ ++ ++//#pragma mark device ++ ++static status_t ++fdt_device_std_ops(int32 op, ...) ++{ ++ switch (op) { ++ case B_MODULE_INIT: ++ case B_MODULE_UNINIT: ++ return B_OK; ++ } ++ ++ return B_BAD_VALUE; ++} ++ ++ ++static status_t ++fdt_device_init_driver(device_node* node, void** cookie) ++{ ++ TRACE("fdt_device_init_driver()\n"); ++ ++ ObjectDeleter dev(new(std::nothrow) fdt_device()); ++ if (!dev.IsSet()) ++ return B_NO_MEMORY; ++ ++ dev->node = node; ++ ++ // get bus from parent node ++ DeviceNodePutter<&gDeviceManager> parent( ++ gDeviceManager->get_parent_node(node)); ++ driver_module_info* parentModule; ++ void* parentDev; ++ ASSERT(gDeviceManager->get_driver( ++ parent.Get(), &parentModule, &parentDev) >= B_OK); ++ if (parentModule == (driver_module_info*)&gDeviceModule) ++ dev->bus = ((fdt_device*)parentDev)->bus; ++ else if (parentModule == (driver_module_info*)&gBusModule) ++ dev->bus = parent.Get(); ++ else ++ panic("bad parent node"); ++ ++ *cookie = dev.Detach(); ++ return B_OK; ++} ++ ++ ++static void ++fdt_device_uninit_driver(void* cookie) ++{ ++ TRACE("fdt_device_uninit_driver()\n"); ++ ObjectDeleter dev((fdt_device*)cookie); ++} ++ ++ ++static status_t ++fdt_device_register_child_devices(void* cookie) ++{ ++ TRACE("fdt_device_register_child_devices()\n"); ++ return B_OK; ++} ++ ++ ++static device_node* ++fdt_device_get_bus(fdt_device* dev) ++{ ++ ASSERT(dev != NULL); ++ return dev->bus; ++} ++ ++ ++static const char* ++fdt_device_get_name(fdt_device* dev) ++{ ++ ASSERT(dev != NULL); ++ ++ uint32 fdtNode; ++ ASSERT(gDeviceManager->get_attr_uint32( ++ dev->node, "fdt/node", &fdtNode, false) >= B_OK); ++ ++ return fdt_get_name(gFDT, (int)fdtNode, NULL); ++} ++ ++ ++static const void* ++fdt_device_get_prop(fdt_device* dev, const char* name, int* len) ++{ ++ ASSERT(dev != NULL); ++ ++ uint32 fdtNode; ++ ASSERT(gDeviceManager->get_attr_uint32( ++ dev->node, "fdt/node", &fdtNode, false) >= B_OK); ++ ++ return fdt_getprop(gFDT, (int)fdtNode, name, len); ++} ++ ++ ++static bool ++fdt_device_get_reg(fdt_device* dev, uint32 ord, uint64* regs, uint64* len) ++{ ++ ASSERT(dev != NULL); ++ ++ uint32 fdtNode; ++ ASSERT(gDeviceManager->get_attr_uint32( ++ dev->node, "fdt/node", &fdtNode, false) >= B_OK); ++ ++ int propLen; ++ const void* prop = fdt_getprop(gFDT, (int)fdtNode, "reg", &propLen); ++ if (prop == NULL) ++ return false; ++ ++ // TODO: use '#address-cells', '#size-cells' in parent node to identify ++ // field sizes ++ ++ if ((ord + 1)*16 > (uint32)propLen) ++ return false; ++ ++ if (regs != NULL) ++ *regs = fdt64_to_cpu(*(((uint64*)prop) + 2*ord)); ++ ++ if (len != NULL) ++ *len = fdt64_to_cpu(*(((uint64*)prop) + 2*ord + 1)); ++ ++ return true; ++} ++ ++ ++static bool ++fdt_device_get_interrupt(fdt_device* dev, uint32 ord, ++ device_node** interruptController, uint64* interrupt) ++{ ++ ASSERT(dev != NULL); ++ ++ uint32 fdtNode; ++ ASSERT(gDeviceManager->get_attr_uint32( ++ dev->node, "fdt/node", &fdtNode, false) >= B_OK); ++ ++ // TODO: handle other interrupt encodings ++ int propLen; ++ const void* prop = fdt_getprop(gFDT, (int)fdtNode, "interrupts-extended", ++ &propLen); ++ if (prop == NULL) ++ return false; ++ ++ // TODO: use '#interrupt-cells' to identify field sizes ++ ++ if ((ord + 1)*8 > (uint32)propLen) ++ return false; ++ ++ if (interruptController != NULL) { ++ uint32 phandle = fdt32_to_cpu(*(((uint32*)prop) + 2*ord)); ++ ++ fdt_bus* bus; ++ ASSERT(gDeviceManager->get_driver( ++ dev->bus, NULL, (void**)&bus) >= B_OK); ++ ++ *interruptController = fdt_bus_node_by_phandle(bus, phandle); ++ } ++ ++ if (interrupt != NULL) ++ *interrupt = fdt32_to_cpu(*(((uint32*)prop) + 2*ord + 1)); ++ ++ return true; ++} ++ ++ ++//#pragma mark - ++ ++fdt_bus_module_info gBusModule = { ++ { ++ { ++ "bus_managers/fdt/root/driver_v1", ++ 0, ++ fdt_bus_std_ops ++ }, ++ fdt_bus_supports_device, ++ fdt_bus_register_device, ++ fdt_bus_init, ++ fdt_bus_uninit, ++ fdt_bus_register_child_devices, ++ NULL, // rescan devices ++ NULL, // device removed ++ }, ++ fdt_bus_node_by_phandle, ++}; ++ ++ ++fdt_device_module_info gDeviceModule = { ++ { ++ { ++ "bus_managers/fdt/driver_v1", ++ 0, ++ fdt_device_std_ops ++ }, ++ ++ NULL, // supports device ++ NULL, // register device (our parent registered us) ++ fdt_device_init_driver, ++ fdt_device_uninit_driver, ++ fdt_device_register_child_devices, ++ NULL, // rescan devices ++ NULL, // device removed ++ }, ++ fdt_device_get_bus, ++ fdt_device_get_name, ++ fdt_device_get_prop, ++ fdt_device_get_reg, ++ fdt_device_get_interrupt, ++}; ++ ++ ++module_info* modules[] = { ++ (module_info*)&gBusModule, ++ (module_info*)&gDeviceModule, ++ NULL ++}; ++ ++module_dependency module_dependencies[] = { ++ {B_DEVICE_MANAGER_MODULE_NAME, (module_info**)&gDeviceManager}, ++ {} ++}; +diff --git a/src/add-ons/kernel/bus_managers/fdt/fdt_serial.cpp b/src/add-ons/kernel/bus_managers/fdt/fdt_serial.cpp +deleted file mode 100644 +index a2ba64832d..0000000000 +--- a/src/add-ons/kernel/bus_managers/fdt/fdt_serial.cpp ++++ /dev/null +@@ -1,194 +0,0 @@ +-/* +- * Copyright 2012, Franรงois Revol, revol@free.fr. +- * Distributed under the terms of the MIT License. +- * +- * Authors: +- * Franรงois Revol, revol@free.fr +- * Alexander von Gluck IV, kallisti5@unixzen.com +- */ +- +-#include "fdt_serial.h" +- +-#include +-#include +-#include +-#include +-#include +- +-#include +- +-#if defined(__arm__) +-#include +-#endif +- +-extern "C" { +-#include +-#include +-#include +-}; +- +-#include "fdt_support.h" +- +- +-//#define TRACE_SERIAL +-#ifdef TRACE_SERIAL +-# define TRACE(x...) dprintf("INIT: " x) +-#else +-# define TRACE(x...) ; +-#endif +- +- +-// If we dprintf before the UART is initalized there will be no output +- +-static DebugUART* +-debug_uart_from_node(const void *fdt, int node) +-{ +- int len; +- const void *prop; +- phys_addr_t regs; +- int32 clock = 0; +- int32 speed = 0; +- DebugUART *uart = NULL; +- +- if (node < 0 || fdt == NULL) +- return NULL; +- +- // determine the MMIO address +- regs = fdt_get_device_reg(fdt, node, false); +- +- if (regs == 0) { +- TRACE("%s: FDT UART regs not found!\n", __func__); +- return NULL; +- } +- +- TRACE("serial: checking '%s', node %d @ %" B_PRIxPHYSADDR "\n", +- name, node, regs); +- +- // get the UART clock rate +- prop = fdt_getprop(fdt, node, "clock-frequency", &len); +- if (prop && len == 4) { +- clock = fdt32_to_cpu(*(uint32_t *)prop); +- TRACE("serial: clock %ld\n", clock); +- } +- +- // get current speed (XXX: not yet passed over) +- prop = fdt_getprop(fdt, node, "current-speed", &len); +- if (prop && len == 4) { +- speed = fdt32_to_cpu(*(uint32_t *)prop); +- TRACE("serial: speed %ld\n", speed); +- } +- +- // fdt_node_check_compatible returns 0 on match. +- if (fdt_node_check_compatible(fdt, node, "ns16550a") == 0 +- || fdt_node_check_compatible(fdt, node, "ns16550") == 0 +- || fdt_node_check_compatible(fdt, node, "snps,dw-apb-uart") == 0) { +- TRACE("serial: Found 8250 serial UART!\n"); +- uart = arch_get_uart_8250(regs, clock); +- #if defined(__arm__) +- } else if (fdt_node_check_compatible(fdt, node, "ti,omap3-uart") == 0 +- || fdt_node_check_compatible(fdt, node, "ti,omap4-uart") == 0 +- || fdt_node_check_compatible(fdt, node, "ti,omap5-uart") == 0 +- || fdt_node_check_compatible(fdt, node, "ti,am3352-uart") == 0 +- || fdt_node_check_compatible(fdt, node, "ti,am4372-uart") == 0 +- || fdt_node_check_compatible(fdt, node, "ti,dra742-uart") == 0) { +- // TODO: ti,am* and ti,dr* have some special quirks. +- TRACE("serial: Found omap 8250 serial UART!\n"); +- uart = arch_get_uart_8250_omap(regs, clock); +- } else if (fdt_node_check_compatible(fdt, node, "arm,pl011") == 0 +- || fdt_node_check_compatible(fdt, node, "arm,primecell") == 0) { +- TRACE("serial: Found pl011 serial UART!\n"); +- uart = arch_get_uart_pl011(regs, clock); +- #endif +- } +- return uart; +-} +- +- +-DebugUART* +-debug_uart_from_fdt(const void *fdt) +-{ +- int chosen_node; +- int node; +- int len; +- const char *name; +- const void *prop; +- DebugUART *uart = NULL; +- +- if (fdt == NULL) { +- TRACE("%s: No FDT found!\n", __func__); +- return NULL; +- } +- +- chosen_node = fdt_path_offset(fdt, "/chosen"); +- if (chosen_node >= 0) { +- prop = fdt_getprop(fdt, chosen_node, "stdout-path", &len); +- if (prop && len > 0) { +- node = fdt_path_offset(fdt, (const char*)prop); +- uart = debug_uart_from_node(fdt, node); +- } +- if (uart == NULL) { +- prop = fdt_getprop(fdt, chosen_node, "linux,stdout-path", &len); +- if (prop && len > 0) { +- node = fdt_path_offset(fdt, (const char*)prop); +- uart = debug_uart_from_node(fdt, node); +- } +- } +- +- if (uart == NULL) { +- // From what i've seen, stdout is generally an alias. +- // we could check for "/..." in the prop, but not sure +- // it's needed. If we *did* check for a prop starting +- // with / we could make all three of these "the same" +- prop = fdt_getprop(fdt, chosen_node, "stdout", &len); +- if (prop && len > 0) { +- name = fdt_get_alias(fdt, (const char*)prop); +- if (name != NULL) { +- node = fdt_path_offset(fdt, name); +- uart = debug_uart_from_node(fdt, node); +- } +- } +- } +- +- // Whoo-hoo! Bail. +- if (uart != NULL) +- return uart; +- } +- +- // If we didn't find a /chosen serial device, lets search for some common aliases +- char aliases[][8] = { +- "serial", +- "serial0", +- "uart", +- "uart0", +- "serial1", +- "serial2", +- "serial3", +- "uart1", +- "uart2", +- "uart3" +- }; +- +- // For each known common serial alias, check it out and see if we have the +- // needed driver for it. uart0 seems most common. +- for (int index = 0; index < sizeof(aliases[0]) / sizeof(aliases); index++) { +- name = fdt_get_alias(fdt, aliases[index]); +- if (name == NULL) +- continue; +- +- node = fdt_path_offset(fdt, name); +- if (node < 0) { +- TRACE("%s: FDT node not found!\n", __func__); +- continue; +- } +- uart = debug_uart_from_node(fdt, node); +- +- // We found a valid serial device. bail. +- if (uart != NULL) +- break; +- } +- +- // It would be nice if we had *some* communication mechanism here if uart is still +- // NULL to warn the user that we couldn't find a serial port. +- +- return uart; +-} +diff --git a/src/add-ons/kernel/bus_managers/fdt/fdt_serial.h b/src/add-ons/kernel/bus_managers/fdt/fdt_serial.h +deleted file mode 100644 +index 18d6f98d63..0000000000 +--- a/src/add-ons/kernel/bus_managers/fdt/fdt_serial.h ++++ /dev/null +@@ -1,19 +0,0 @@ +-/* +- * Copyright 2012-2015, Haiku, Inc. +- * Distributed under the terms of the MIT License. +- * +- * Authors +- * Alexander von Gluck IV, kallisti5@unixzen.com +- */ +-#ifndef __FDT_SERIAL_H +-#define __FDT_SERIAL_H +- +- +-#include +-#include +- +- +-DebugUART * debug_uart_from_fdt(const void *fdt); +- +- +-#endif /*__FDT_SERIAL_H*/ +diff --git a/src/add-ons/kernel/bus_managers/fdt/fdt_support.cpp b/src/add-ons/kernel/bus_managers/fdt/fdt_support.cpp +deleted file mode 100644 +index 22ec0735b3..0000000000 +--- a/src/add-ons/kernel/bus_managers/fdt/fdt_support.cpp ++++ /dev/null +@@ -1,310 +0,0 @@ +-/* +- * Copyright 2012-2015 Haiku, Inc. All rights reserved. +- * Distributed under the terms of the MIT License. +- * +- * Authors: +- * Franรงois Revol, revol@free.fr +- * Alexander von Gluck IV, kallisti5@unixzen.com +- */ +- +- +-#include "fdt_support.h" +- +-#include +-#include +-#include +-#include +-#include +- +-extern "C" { +-#include +-#include +-#include +-}; +- +- +-#define TRACE_FDT +-#ifdef TRACE_FDT +-# define TRACE(x...) dprintf(x) +-#else +-# define TRACE(x...) ; +-#endif +- +-//#define FDT_DUMP_NODES +-//#define FDT_DUMP_PROPS +-//#define FDT_DUMP_PROP_VALUES +- +-#ifdef FDT_DUMP_NODES +-static const char *sTabTab = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"; +-#define DS "%.*s" +-#define DA depth - 1, sTabTab +-#endif +- +- +-#ifdef FDT_DUMP_PROP_VALUES +-static void dump_hex(const char *data, int32 len, int depth) +-{ +- char str[128]; +- char astr[32]; +- char *p; +- int l; +- int i; +- +- for (i = 0; i < len; ) { +- p = str; +- l = sizeof(str); +- for (; i < len && (p == str || (i % 16 != 0)); i++) { +- snprintf(p, l - 1, "%02x ", data[i]); +- l -= strlen(p); +- p += strlen(p); +- astr[i % 16] = isprint(data[i]) ? data[i] : '.'; +- astr[i % 16] = isprint(data[i]) ? data[i] : '.'; +- astr[(i % 16) + 1] = '\0'; +- } +- dprintf(DS" %-48.48s %s\n", DA, str, astr); +- } +-} +-#endif +- +- +-void dump_fdt(const void *fdt) +-{ +- int err; +- +- dprintf("FDT @ %p:\n", fdt); +- +- if (!fdt) +- return; +- +- err = fdt_check_header(fdt); +- if (err) { +- dprintf("fdt error: %s\n", fdt_strerror(err)); +- return; +- } +- +- dprintf("fdt_totalsize: %d\n", fdt_totalsize(fdt)); +- dprintf("fdt_off_dt_struct: %d\n", fdt_off_dt_struct(fdt)); +- dprintf("fdt_off_dt_strings: %d\n", fdt_off_dt_strings(fdt)); +- dprintf("fdt_off_mem_rsvmap: %d\n", fdt_off_mem_rsvmap(fdt)); +- dprintf("fdt_version: %d\n", fdt_version(fdt)); +- dprintf("fdt_last_comp_version: %d\n", fdt_last_comp_version(fdt)); +- dprintf("fdt_boot_cpuid_phys: %d\n", fdt_boot_cpuid_phys(fdt)); +- dprintf("fdt_size_dt_strings: %d\n", fdt_size_dt_strings(fdt)); +- dprintf("fdt_size_dt_struct: %d\n", fdt_size_dt_struct(fdt)); +- +-#ifdef FDT_DUMP_NODES +- dprintf("fdt tree:\n"); +- +- int node = -1; +- int depth = 0; +- while ((node = fdt_next_node(fdt, node, &depth)) >= 0) { +- dprintf(DS"node at %d: '%s'\n", DA, node, +- fdt_get_name(fdt, node, NULL)); +-#ifdef FDT_DUMP_PROPS +- int prop, len; +- const struct fdt_property *property; +- prop = fdt_first_property_offset(fdt, node); +- while (prop >= 0) { +- property = fdt_get_property_by_offset(fdt, prop, &len); +- if (property == NULL) { +- dprintf("getting prop at %d: %s\n", prop, fdt_strerror(len)); +- break; +- } +- dprintf(DS" prop at %d: '%s', len %d\n", DA, prop, +- fdt_string(fdt, fdt32_to_cpu(property->nameoff)), +- fdt32_to_cpu(property->len)); +-#ifdef FDT_DUMP_PROP_VALUES +- dump_hex(property->data, fdt32_to_cpu(property->len), depth); +-#endif +- prop = fdt_next_property_offset(fdt, prop); +- } +-#endif +- } +-#endif +-} +- +- +-static uint64 +-fdt_get_range_offset(const void* fdt, int32 node) +-{ +- // Obtain the offset of the device by searching +- // for the first ranges start in parents. +- +- // It could be possible that there are multiple +- // offset ranges in several parents + children. +- // Lets hope that no system designer is that insane. +- int depth = fdt_node_depth(fdt, node); +- int32 examineNode = node; +- uint64 pathOffset = 0x0; +- +- while (depth > 0) { +- int len; +- const void* prop; +- prop = fdt_getprop(fdt, examineNode, "ranges", &len); +- if (prop) { +- int32 regAddressCells = 1; +- int32 regSizeCells = 1; +- fdt_get_cell_count(fdt, examineNode, regAddressCells, regSizeCells); +- +- const uint32 *p = (const uint32 *)prop; +- // All we are interested in is the start offset +- if (regAddressCells == 2) +- pathOffset = fdt64_to_cpu(*(uint64_t *)p); +- else +- pathOffset = fdt32_to_cpu(*(uint32_t *)p); +- break; +- } +- int32 parentNode = fdt_parent_offset(fdt, examineNode); +- depth = fdt_node_depth(fdt, parentNode); +- examineNode = parentNode; +- } +- +- TRACE("%s: range offset: 0x%" B_PRIx64 "\n", __func__, pathOffset); +- +- return pathOffset; +-} +- +- +-status_t +-fdt_get_cell_count(const void* fdt, int node, +- int32 &addressCells, int32 &sizeCells) +-{ +- // It would be nice if libfdt provided this. +- +- // Memory base addresses are provided in 32 or 64 bit flavors +- // #address-cells and #size-cells matches the number of 32-bit 'cells' +- // representing the length of the base address and size fields +- +- // TODO: assert !fdt || !pathOffset? +- +- int len; +- if (node < 0) { +- TRACE("%s: Invalid FDT node id provided!\n", __func__); +- return B_ERROR; +- } +- +- const void *prop; +- prop = fdt_getprop(fdt, node, "#address-cells", &len); +- if (prop && len == sizeof(uint32)) +- addressCells = fdt32_to_cpu(*(uint32_t *)prop); +- prop = fdt_getprop(fdt, node, "#size-cells", &len); +- if (prop && len == sizeof(uint32)) +- sizeCells = fdt32_to_cpu(*(uint32_t *)prop); +- +- // NOTE : Cells over 2 is possible in theory... +- if (addressCells > 2 || sizeCells > 2) { +- panic("%s: Unsupported FDT cell count detected.\n" +- "Address Cells: %" B_PRId32 "; Size Cells: %" B_PRId32 +- " (CPU > 64bit?).\n", __func__, addressCells, sizeCells); +- return B_ERROR; +- } +- +- return B_OK; +-} +- +- +-phys_addr_t +-fdt_get_device_reg(const void* fdt, int node, bool physical) +-{ +- const void *prop = NULL; +- int len; +- uint64 baseDevice = 0x0; +- +- int32 regAddressCells = 1; +- int32 regSizeCells = 1; +- fdt_get_cell_count(fdt, node, regAddressCells, regSizeCells); +- +- // TODO: check for virtual-reg, and don't -= fdt_get_range_offset? +- +- // XXX: not sure #address-cells & #size-cells actually apply to virtual-reg +- if (!physical) { +- prop = fdt_getprop(fdt, node, "virtual-reg", &len); +- if (prop != NULL) { +- baseDevice = fdt32_to_cpu(*(uint32_t *)prop); +- return baseDevice; +- } +- } +- +- prop = fdt_getprop(fdt, node, "reg", &len); +- +- if (!prop) { +- dprintf("%s: reg property not found on node in FDT!\n", __func__); +- return 0; +- } +- +- const uint32 *p = (const uint32 *)prop; +- +- // soc base address cells +- if (regAddressCells == 2) +- baseDevice = fdt64_to_cpu(*(uint64_t *)p); +- else +- baseDevice = fdt32_to_cpu(*(uint32_t *)p); +- //p += regAddressCells; +- +- // subtract the range offset (X) on the parent node (ranges = X Y Z) +- baseDevice -= fdt_get_range_offset(fdt, node); +- +- // find the start of the parent (X) and add to base (regs = X Y) +- int parentNode = fdt_parent_offset(fdt, node); +- if (!parentNode) +- return baseDevice; +- +- fdt_get_cell_count(fdt, parentNode, regAddressCells, regSizeCells); +- prop = fdt_getprop(fdt, parentNode, "reg", &len); +- +- if (!prop) +- return baseDevice; +- p = (const uint32 *)prop; +- +- uint64 parentReg = 0x0; +- // soc base address cells +- if (regAddressCells == 2) +- parentReg = fdt64_to_cpu(*(uint64_t *)p); +- else +- parentReg = fdt32_to_cpu(*(uint32_t *)p); +- +- // add parent reg base to property +- baseDevice += parentReg; +- +- return baseDevice; +-} +- +- +-phys_addr_t +-fdt_get_device_reg_byname(const void* fdt, const char* name) +-{ +- // Find device in FDT +- int node = fdt_path_offset(fdt, name); +- +- if (node < 0) { +- dprintf("%s: %s not found in FDT!\n", __func__, name); +- return 0; +- } +- +- addr_t deviceReg = fdt_get_device_reg(fdt, node); +- if (deviceReg > 0) { +- //TRACE("%s: %s found @ 0x%" B_PRIx64 " , size: 0x%" B_PRIx64 "\n", +- // __func__, name, deviceReg, size); +- TRACE("%s: %s found @ 0x%" B_PRIxADDR "\n", __func__, name, deviceReg); +- } else { +- dprintf("%s: No valid reg entry on FDT device %s!\n", +- __func__, name); +- return 0; +- } +- return deviceReg; +-} +- +- +-phys_addr_t +-fdt_get_device_reg_byalias(const void* fdt, const char* alias) +-{ +- const char* name = fdt_get_alias(fdt, alias); +- +- if (name == NULL) { +- dprintf("%s: No alias found for %s!\n", __func__, alias); +- return 0; +- } +- +- phys_addr_t deviceReg = fdt_get_device_reg_byname(fdt, name); +- return deviceReg; +-} +diff --git a/src/add-ons/kernel/bus_managers/fdt/fdt_support.h b/src/add-ons/kernel/bus_managers/fdt/fdt_support.h +deleted file mode 100644 +index 2202bcda9a..0000000000 +--- a/src/add-ons/kernel/bus_managers/fdt/fdt_support.h ++++ /dev/null +@@ -1,24 +0,0 @@ +-/* +- * Copyright 2012-2015, Haiku, Inc. +- * Distributed under the terms of the MIT License. +- * +- * Authors +- * Alexander von Gluck IV, kallisti5@unixzen.com +- */ +-#ifndef __FDT_SUPPORT_H +-#define __FDT_SUPPORT_H +- +- +-#include +- +- +-void dump_fdt(const void *fdt); +-status_t fdt_get_cell_count(const void* fdt, int node, +- int32 &addressCells, int32 &sizeCells); +- +-phys_addr_t fdt_get_device_reg(const void* fdt, int node, bool physical=true); +-phys_addr_t fdt_get_device_reg_byname(const void* fdt, const char* name); +-phys_addr_t fdt_get_device_reg_byalias(const void* fdt, const char* alias); +- +- +-#endif /*__FDT_SUPPORT_H*/ +-- +2.30.2 + diff --git a/patchset-hrev55144/0059-input_server-virtio-add.patch b/patchset-hrev55144/0059-input_server-virtio-add.patch new file mode 100644 index 0000000..935a3b8 --- /dev/null +++ b/patchset-hrev55144/0059-input_server-virtio-add.patch @@ -0,0 +1,914 @@ +From b31e26f0ac5f38d846c2e3561121224d77faf8d8 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 24 May 2021 06:35:01 +0900 +Subject: input_server/virtio: add + +Change-Id: I9e55349717231a5b13f0bce351f349a54c1f643e +--- + src/add-ons/input_server/devices/Jamfile | 2 +- + .../input_server/devices/virtio/Jamfile | 7 + + .../devices/virtio/VirtioInputDevice.cpp | 710 ++++++++++++++++++ + .../devices/virtio/VirtioInputDevice.h | 148 ++++ + 4 files changed, 866 insertions(+), 1 deletion(-) + create mode 100644 src/add-ons/input_server/devices/virtio/Jamfile + create mode 100644 src/add-ons/input_server/devices/virtio/VirtioInputDevice.cpp + create mode 100644 src/add-ons/input_server/devices/virtio/VirtioInputDevice.h + +diff --git a/src/add-ons/input_server/devices/Jamfile b/src/add-ons/input_server/devices/Jamfile +index 0a6cc52f22..a5ba4da5ba 100644 +--- a/src/add-ons/input_server/devices/Jamfile ++++ b/src/add-ons/input_server/devices/Jamfile +@@ -5,6 +5,6 @@ SubInclude HAIKU_TOP src add-ons input_server devices keyboard ; + SubInclude HAIKU_TOP src add-ons input_server devices mouse ; + SubInclude HAIKU_TOP src add-ons input_server devices serial_mouse ; + SubInclude HAIKU_TOP src add-ons input_server devices tablet ; ++SubInclude HAIKU_TOP src add-ons input_server devices virtio ; + SubInclude HAIKU_TOP src add-ons input_server devices virtualkeyboard ; + SubInclude HAIKU_TOP src add-ons input_server devices wacom ; +- +diff --git a/src/add-ons/input_server/devices/virtio/Jamfile b/src/add-ons/input_server/devices/virtio/Jamfile +new file mode 100644 +index 0000000000..0badc9bcc9 +--- /dev/null ++++ b/src/add-ons/input_server/devices/virtio/Jamfile +@@ -0,0 +1,7 @@ ++SubDir HAIKU_TOP src add-ons input_server devices virtio ; ++ ++UsePrivateHeaders input virtio shared ; ++ ++Addon virtio : ++ VirtioInputDevice.cpp ++ : be input_server [ TargetLibsupc++ ] ; +diff --git a/src/add-ons/input_server/devices/virtio/VirtioInputDevice.cpp b/src/add-ons/input_server/devices/virtio/VirtioInputDevice.cpp +new file mode 100644 +index 0000000000..33bc78abf0 +--- /dev/null ++++ b/src/add-ons/input_server/devices/virtio/VirtioInputDevice.cpp +@@ -0,0 +1,710 @@ ++/* ++ * Copyright 2021, Haiku, Inc. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++#include "VirtioInputDevice.h" ++ ++#include ++#include ++ ++#include ++#include ++ ++#include ++#include ++ ++ ++enum { ++ kWatcherThreadPriority = B_FIRST_REAL_TIME_PRIORITY + 4, ++}; ++ ++ ++template ++inline static void SetBit(Type &val, int bit) {val |= Type(1) << bit;} ++ ++template ++inline static void ClearBit(Type &val, int bit) {val &= ~(Type(1) << bit);} ++ ++template ++inline static void InvertBit(Type &val, int bit) {val ^= Type(1) << bit;} ++ ++template ++inline static void SetBitTo(Type &val, int bit, bool isSet) { ++ val ^= ((isSet? -1: 0) ^ val) & (Type(1) << bit);} ++ ++template ++inline static bool IsBitSet(Type val, int bit) { ++ return (val & (Type(1) << bit)) != 0;} ++ ++ ++// Packet decoder for debugging, disabled to avoid unused function warning. ++#if 0 ++static void WriteInputPacket(const VirtioInputPacket &pkt) ++{ ++ switch (pkt.type) { ++ case kVirtioInputEvSyn: debug_printf("syn"); break; ++ case kVirtioInputEvKey: debug_printf("key"); ++ debug_printf(", "); ++ switch (pkt.code) { ++ case kVirtioInputBtnLeft: debug_printf("left"); break; ++ case kVirtioInputBtnRight: debug_printf("middle"); break; ++ case kVirtioInputBtnMiddle: debug_printf("right"); break; ++ case kVirtioInputBtnGearDown: debug_printf("gearDown"); break; ++ case kVirtioInputBtnGearUp: debug_printf("gearUp"); break; ++ default: debug_printf("%d", pkt.code); ++ } ++ break; ++ case kVirtioInputEvRel: debug_printf("rel"); ++ debug_printf(", "); ++ switch (pkt.code) { ++ case kVirtioInputRelX: debug_printf("relX"); break; ++ case kVirtioInputRelY: debug_printf("relY"); break; ++ case kVirtioInputRelZ: debug_printf("relZ"); break; ++ case kVirtioInputRelWheel: debug_printf("relWheel"); break; ++ default: debug_printf("%d", pkt.code); ++ } ++ break; ++ case kVirtioInputEvAbs: debug_printf("abs"); ++ debug_printf(", "); ++ switch (pkt.code) { ++ case kVirtioInputAbsX: debug_printf("absX"); break; ++ case kVirtioInputAbsY: debug_printf("absY"); break; ++ case kVirtioInputAbsZ: debug_printf("absZ"); break; ++ default: debug_printf("%d", pkt.code); ++ } ++ break; ++ case kVirtioInputEvRep: debug_printf("rep"); break; ++ default: debug_printf("?(%d)", pkt.type); ++ } ++ switch (pkt.type) { ++ case kVirtioInputEvSyn: ++ break; ++ case kVirtioInputEvKey: ++ debug_printf(", "); ++ if (pkt.value == 0) debug_printf("up"); ++ else if (pkt.value == 1) debug_printf("down"); ++ else debug_printf("%d", pkt.value); ++ break; ++ default: debug_printf(", "); debug_printf("%d", pkt.value); ++ } ++} ++#endif ++ ++ ++//#pragma mark VirtioInputDevice ++ ++VirtioInputDevice::VirtioInputDevice() ++{ ++} ++ ++VirtioInputDevice::~VirtioInputDevice() ++{ ++} ++ ++ ++status_t ++VirtioInputDevice::InitCheck() ++{ ++ static input_device_ref *devices[3]; ++ input_device_ref **devicesEnd = devices; ++ ++ FileDescriptorCloser fd; ++ ++ // TODO: dynamically scan and detect device type ++ ObjectDeleter tablet( ++ new TabletHandler(this, "VirtIO tablet")); ++ fd.SetTo(open("/dev/input/virtio/0/raw", O_RDWR)); ++ if(fd.IsSet()) { ++ tablet->SetFd(fd.Detach()); ++ *devicesEnd++ = tablet->Ref(); ++ tablet.Detach(); ++ } ++ ++ ObjectDeleter keyboard( ++ new KeyboardHandler(this, "VirtIO keyboard")); ++ fd.SetTo(open("/dev/input/virtio/1/raw", O_RDWR)); ++ if(fd.IsSet()) { ++ keyboard->SetFd(fd.Detach()); ++ *devicesEnd++ = keyboard->Ref(); ++ keyboard.Detach(); ++ } ++ ++ *devicesEnd = NULL; ++ ++ RegisterDevices(devices); ++ return B_OK; ++} ++ ++ ++status_t ++VirtioInputDevice::Start(const char* name, void* cookie) ++{ ++ return ((VirtioHandler*)cookie)->Start(); ++} ++ ++ ++status_t ++VirtioInputDevice::Stop(const char* name, void* cookie) ++{ ++ return ((VirtioHandler*)cookie)->Stop(); ++} ++ ++ ++status_t ++VirtioInputDevice::Control(const char* name, void* cookie, uint32 command, ++ BMessage* message) ++{ ++ return ((VirtioHandler*)cookie)->Control(command, message); ++} ++ ++ ++//#pragma mark VirtioHandler ++ ++VirtioHandler::VirtioHandler(VirtioInputDevice* dev, const char* name, ++ input_device_type type) ++ : ++ fDev(dev), ++ fWatcherThread(B_ERROR), ++ fRun(false) ++{ ++ fRef.name = (char*)name; // NOTE: name should be constant data ++ fRef.type = type; ++ fRef.cookie = this; ++} ++ ++ ++VirtioHandler::~VirtioHandler() ++{} ++ ++ ++void ++VirtioHandler::SetFd(int fd) ++{ ++ fDeviceFd.SetTo(fd); ++} ++ ++ ++status_t ++VirtioHandler::Start() ++{ ++ char threadName[B_OS_NAME_LENGTH]; ++ snprintf(threadName, B_OS_NAME_LENGTH, "%s watcher", fRef.name); ++ ++ if (fWatcherThread < 0) { ++ fWatcherThread = spawn_thread(Watcher, threadName, ++ kWatcherThreadPriority, this); ++ ++ if (fWatcherThread < B_OK) ++ return fWatcherThread; ++ ++ fRun = true; ++ resume_thread(fWatcherThread); ++ } ++ return B_OK; ++} ++ ++ ++status_t ++VirtioHandler::Stop() ++{ ++ if (fWatcherThread >= B_OK) { ++ // ioctl(fDeviceFd.Get(), virtioInputCancelIO, NULL, 0); ++ suspend_thread(fWatcherThread); ++ fRun = false; ++ status_t res; ++ wait_for_thread(fWatcherThread, &res); ++ fWatcherThread = B_ERROR; ++ } ++ return B_OK; ++} ++ ++ ++status_t ++VirtioHandler::Control(uint32 command, BMessage* message) ++{ ++ return B_OK; ++} ++ ++ ++int32 ++VirtioHandler::Watcher(void *arg) ++{ ++ VirtioHandler &handler = *((VirtioHandler*)arg); ++ handler.Reset(); ++ while (handler.fRun) { ++ VirtioInputPacket pkt; ++ status_t res = ioctl(handler.fDeviceFd.Get(), virtioInputRead, &pkt, ++ sizeof(pkt)); ++ // if (res == B_CANCELED) return B_OK; ++ if (res < B_OK) continue; ++ handler.PacketReceived(pkt); ++ } ++ return B_OK; ++} ++ ++ ++//#pragma mark KeyboardHandler ++ ++KeyboardHandler::KeyboardHandler(VirtioInputDevice* dev, const char* name): ++ VirtioHandler(dev, name, B_KEYBOARD_DEVICE), ++ fRepeatThread(-1), fRepeatThreadSem(-1) ++{ ++ debug_printf("+KeyboardHandler()\n"); ++ { ++ key_map *keyMap = NULL; ++ char *chars = NULL; ++ get_key_map(&keyMap, &chars); ++ fKeyMap.SetTo(keyMap); ++ fChars.SetTo(chars); ++ } ++ debug_printf(" fKeymap: %p\n", fKeyMap.Get()); ++ debug_printf(" fChars: %p\n", fChars.Get()); ++ get_key_repeat_delay(&fRepeatDelay); ++ get_key_repeat_rate (&fRepeatRate); ++ debug_printf(" fRepeatDelay: %" B_PRIdBIGTIME "\n", fRepeatDelay); ++ debug_printf(" fRepeatRate: % " B_PRId32 "\n", fRepeatRate); ++ if (fRepeatRate < 1) fRepeatRate = 1; ++} ++ ++ ++KeyboardHandler::~KeyboardHandler() ++{ ++ _StopRepeating(); ++} ++ ++ ++void ++KeyboardHandler::Reset() ++{ ++ memset(&fNewState, 0, sizeof(KeyboardState)); ++ memcpy(&fState, &fNewState, sizeof(KeyboardState)); ++ _StopRepeating(); ++} ++ ++ ++status_t ++KeyboardHandler::Control(uint32 command, BMessage* message) ++{ ++ switch (command) { ++ case B_KEY_MAP_CHANGED: { ++ key_map *keyMap = NULL; ++ char *chars = NULL; ++ get_key_map(&keyMap, &chars); ++ if (keyMap == NULL || chars == NULL) ++ return B_NO_MEMORY; ++ fKeyMap.SetTo(keyMap); ++ fChars.SetTo(chars); ++ return B_OK; ++ } ++ case B_KEY_REPEAT_DELAY_CHANGED: ++ get_key_repeat_delay(&fRepeatDelay); ++ debug_printf(" fRepeatDelay: %" B_PRIdBIGTIME "\n", fRepeatDelay); ++ return B_OK; ++ case B_KEY_REPEAT_RATE_CHANGED: ++ get_key_repeat_rate(&fRepeatRate); ++ debug_printf(" fRepeatRate: %" B_PRId32 "\n", fRepeatRate); ++ if (fRepeatRate < 1) fRepeatRate = 1; ++ return B_OK; ++ } ++ return VirtioHandler::Control(command, message); ++} ++ ++ ++void ++KeyboardHandler::PacketReceived(const VirtioInputPacket &pkt) ++{ ++ // debug_printf("keyboard: "); WriteInputPacket(pkt); debug_printf("\n"); ++ switch (pkt.type) { ++ case kVirtioInputEvKey: { ++ if (pkt.code < 256) ++ SetBitTo(fNewState.keys[pkt.code / 8], pkt.code % 8, ++ pkt.value != 0); ++ break; ++ } ++ case kVirtioInputEvSyn: { ++ fState.when = system_time(); ++ _StateChanged(); ++ } ++ } ++} ++ ++ ++bool ++KeyboardHandler::_IsKeyPressed(const KeyboardState &state, uint32 key) ++{ ++ return key < 256 && IsBitSet(state.keys[key / 8], key % 8); ++} ++ ++ ++void ++KeyboardHandler::_KeyString(uint32 code, char *str, size_t len) ++{ ++ uint32 i; ++ char *ch; ++ switch (fNewState.modifiers & ( ++ B_SHIFT_KEY | B_CONTROL_KEY | B_OPTION_KEY | B_CAPS_LOCK)) { ++ case B_OPTION_KEY | B_CAPS_LOCK | B_SHIFT_KEY: ++ ch = fChars.Get() + fKeyMap->option_caps_shift_map[code]; ++ break; ++ case B_OPTION_KEY | B_CAPS_LOCK: ++ ch = fChars.Get() + fKeyMap->option_caps_map[code]; ++ break; ++ case B_OPTION_KEY | B_SHIFT_KEY: ++ ch = fChars.Get() + fKeyMap->option_shift_map[code]; ++ break; ++ case B_OPTION_KEY: ++ ch = fChars.Get() + fKeyMap->option_map[code]; ++ break; ++ case B_CAPS_LOCK | B_SHIFT_KEY: ++ ch = fChars.Get() + fKeyMap->caps_shift_map[code]; ++ break; ++ case B_CAPS_LOCK: ++ ch = fChars.Get() + fKeyMap->caps_map[code]; ++ break; ++ case B_SHIFT_KEY: ++ ch = fChars.Get() + fKeyMap->shift_map[code]; ++ break; ++ default: ++ if (fNewState.modifiers & B_CONTROL_KEY) ++ ch = fChars.Get() + fKeyMap->control_map[code]; ++ else ++ ch = fChars.Get() + fKeyMap->normal_map[code]; ++ } ++ if (len > 0) { ++ for (i = 0; (i < (uint32)ch[0]) && (i < len-1); ++i) ++ str[i] = ch[i+1]; ++ str[i] = '\0'; ++ } ++} ++ ++ ++void ++KeyboardHandler::_StartRepeating(BMessage* msg) ++{ ++ if (fRepeatThread >= B_OK) _StopRepeating(); ++ ++ fRepeatMsg = *msg; ++ fRepeatThread = spawn_thread(_RepeatThread, "repeat thread", ++ B_REAL_TIME_PRIORITY, this); ++ fRepeatThreadSem = create_sem(0, "repeat thread sem"); ++ if (fRepeatThread >= B_OK) ++ resume_thread(fRepeatThread); ++} ++ ++ ++void ++KeyboardHandler::_StopRepeating() ++{ ++ if (fRepeatThread >= B_OK) { ++ status_t res; ++ release_sem(fRepeatThreadSem); ++ wait_for_thread(fRepeatThread, &res); fRepeatThread = -1; ++ delete_sem(fRepeatThreadSem); fRepeatThreadSem = -1; ++ } ++} ++ ++ ++status_t ++KeyboardHandler::_RepeatThread(void *arg) ++{ ++ status_t res; ++ KeyboardHandler *h = (KeyboardHandler*)arg; ++ int32 count; ++ ++ res = acquire_sem_etc(h->fRepeatThreadSem, 1, B_RELATIVE_TIMEOUT, ++ h->fRepeatDelay); ++ if (res >= B_OK) ++ return B_OK; ++ ++ while (true) { ++ h->fRepeatMsg.ReplaceInt64("when", system_time()); ++ h->fRepeatMsg.FindInt32("be:key_repeat", &count); ++ h->fRepeatMsg.ReplaceInt32("be:key_repeat", count + 1); ++ ++ ObjectDeleter msg(new(std::nothrow) BMessage(h->fRepeatMsg)); ++ if (msg.IsSet() && h->Device()->EnqueueMessage(msg.Get()) >= B_OK) ++ msg.Detach(); ++ ++ res = acquire_sem_etc(h->fRepeatThreadSem, 1, B_RELATIVE_TIMEOUT, ++ (bigtime_t)10000000 / h->fRepeatRate); ++ if (res >= B_OK) ++ return B_OK; ++ } ++} ++ ++ ++void ++KeyboardHandler::_StateChanged() ++{ ++ uint32 i, j; ++ ++ fNewState.modifiers = fState.modifiers ++ & (B_CAPS_LOCK | B_SCROLL_LOCK | B_NUM_LOCK); ++ if (_IsKeyPressed(fNewState, fKeyMap->left_shift_key)) ++ fNewState.modifiers |= B_SHIFT_KEY | B_LEFT_SHIFT_KEY; ++ if (_IsKeyPressed(fNewState, fKeyMap->right_shift_key)) ++ fNewState.modifiers |= B_SHIFT_KEY | B_RIGHT_SHIFT_KEY; ++ if (_IsKeyPressed(fNewState, fKeyMap->left_command_key)) ++ fNewState.modifiers |= B_COMMAND_KEY | B_LEFT_COMMAND_KEY; ++ if (_IsKeyPressed(fNewState, fKeyMap->right_command_key)) ++ fNewState.modifiers |= B_COMMAND_KEY | B_RIGHT_COMMAND_KEY; ++ if (_IsKeyPressed(fNewState, fKeyMap->left_control_key)) ++ fNewState.modifiers |= B_CONTROL_KEY | B_LEFT_CONTROL_KEY; ++ if (_IsKeyPressed(fNewState, fKeyMap->right_control_key)) ++ fNewState.modifiers |= B_CONTROL_KEY | B_RIGHT_CONTROL_KEY; ++ if (_IsKeyPressed(fNewState, fKeyMap->caps_key)) ++ fNewState.modifiers ^= B_CAPS_LOCK; ++ if (_IsKeyPressed(fNewState, fKeyMap->scroll_key)) ++ fNewState.modifiers ^= B_SCROLL_LOCK; ++ if (_IsKeyPressed(fNewState, fKeyMap->num_key)) ++ fNewState.modifiers ^= B_NUM_LOCK; ++ if (_IsKeyPressed(fNewState, fKeyMap->left_option_key)) ++ fNewState.modifiers |= B_OPTION_KEY | B_LEFT_OPTION_KEY; ++ if (_IsKeyPressed(fNewState, fKeyMap->right_option_key)) ++ fNewState.modifiers |= B_OPTION_KEY | B_RIGHT_OPTION_KEY; ++ if (_IsKeyPressed(fNewState, fKeyMap->menu_key)) ++ fNewState.modifiers |= B_MENU_KEY; ++ ++ if (fState.modifiers != fNewState.modifiers) { ++ ObjectDeleter msg( ++ new(std::nothrow) BMessage(B_MODIFIERS_CHANGED)); ++ if (msg.IsSet()) { ++ msg->AddInt64("when", system_time()); ++ msg->AddInt32("modifiers", fNewState.modifiers); ++ msg->AddInt32("be:old_modifiers", fState.modifiers); ++ msg->AddData("states", B_UINT8_TYPE, fNewState.keys, 16); ++ ++ if (Device()->EnqueueMessage(msg.Get()) >= B_OK) { ++ msg.Detach(); ++ fState.modifiers = fNewState.modifiers; ++ } ++ } ++ } ++ ++ ++ uint8 diff[16]; ++ char rawCh; ++ char str[5]; ++ ++ for (i = 0; i < 16; ++i) ++ diff[i] = fState.keys[i] ^ fNewState.keys[i]; ++ ++ for (i = 0; i < 128; ++i) { ++ if (diff[i/8] & (1 << (i % 8))) { ++ ObjectDeleter msg(new(std::nothrow) BMessage()); ++ if (msg.IsSet()) { ++ _KeyString(i, str, sizeof(str)); ++ ++ msg->AddInt64("when", system_time()); ++ msg->AddInt32("key", i); ++ msg->AddInt32("modifiers", fNewState.modifiers); ++ msg->AddData("states", B_UINT8_TYPE, fNewState.keys, 16); ++ ++ if (str[0] != '\0') { ++ if (fChars.Get()[fKeyMap->normal_map[i]] != 0) ++ rawCh = fChars.Get()[fKeyMap->normal_map[i] + 1]; ++ else ++ rawCh = str[0]; ++ ++ for (j = 0; str[j] != '\0'; ++j) ++ msg->AddInt8("byte", str[j]); ++ ++ msg->AddString("bytes", str); ++ msg->AddInt32("raw_char", rawCh); ++ } ++ ++ if (fNewState.keys[i / 8] & (1 << (i % 8))) { ++ if (str[0] != '\0') ++ msg->what = B_KEY_DOWN; ++ else ++ msg->what = B_UNMAPPED_KEY_DOWN; ++ ++ msg->AddInt32("be:key_repeat", 1); ++ _StartRepeating(msg.Get()); ++ } else { ++ if (str[0] != '\0') ++ msg->what = B_KEY_UP; ++ else ++ msg->what = B_UNMAPPED_KEY_UP; ++ ++ _StopRepeating(); ++ } ++ ++ if (Device()->EnqueueMessage(msg.Get()) >= B_OK) { ++ msg.Detach(); ++ for (j = 0; j < 16; ++j) ++ fState.keys[j] = fNewState.keys[j]; ++ } ++ } ++ } ++ } ++} ++ ++ ++//#pragma mark TabletHandler ++ ++TabletHandler::TabletHandler(VirtioInputDevice* dev, const char* name): ++ VirtioHandler(dev, name, B_POINTING_DEVICE) ++{} ++ ++ ++void ++TabletHandler::Reset() ++{ ++ memset(&fNewState, 0, sizeof(TabletState)); ++ fNewState.x = 0.5f; ++ fNewState.y = 0.5f; ++ memcpy(&fState, &fNewState, sizeof(TabletState)); ++ fLastClick = -1; ++ fLastClickBtn = -1; ++ ++ get_click_speed(&fClickSpeed); ++ debug_printf(" fClickSpeed: %" B_PRIdBIGTIME "\n", fClickSpeed); ++} ++ ++ ++status_t ++TabletHandler::Control(uint32 command, BMessage* message) ++{ ++ switch (command) { ++ case B_CLICK_SPEED_CHANGED: { ++ get_click_speed(&fClickSpeed); ++ debug_printf(" fClickSpeed: %" B_PRIdBIGTIME "\n", fClickSpeed); ++ return B_OK; ++ } ++ } ++ return VirtioHandler::Control(command, message); ++} ++ ++ ++void ++TabletHandler::PacketReceived(const VirtioInputPacket &pkt) ++{ ++ switch (pkt.type) { ++ case kVirtioInputEvAbs: { ++ switch (pkt.code) { ++ case kVirtioInputAbsX: ++ fNewState.x = float(pkt.value)/32768.0f; ++ break; ++ case kVirtioInputAbsY: ++ fNewState.y = float(pkt.value)/32768.0f; ++ break; ++ } ++ break; ++ } ++ case kVirtioInputEvRel: { ++ switch (pkt.code) { ++ case kVirtioInputRelWheel: ++ fNewState.wheelY -= pkt.value; ++ break; ++ } ++ break; ++ } ++ case kVirtioInputEvKey: { ++ switch (pkt.code) { ++ case kVirtioInputBtnLeft: ++ SetBitTo(fNewState.buttons, 0, pkt.value != 0); ++ break; ++ case kVirtioInputBtnRight: ++ SetBitTo(fNewState.buttons, 1, pkt.value != 0); ++ break; ++ case kVirtioInputBtnMiddle: ++ SetBitTo(fNewState.buttons, 2, pkt.value != 0); ++ break; ++ } ++ break; ++ } ++ case kVirtioInputEvSyn: { ++ fState.when = system_time(); ++ ++ // update pos ++ if (fState.x != fNewState.x || fState.y != fNewState.y ++ || fState.pressure != fNewState.pressure) { ++ fState.x = fNewState.x; ++ fState.y = fNewState.y; ++ fState.pressure = fNewState.pressure; ++ ObjectDeleter msg( ++ new(std::nothrow) BMessage(B_MOUSE_MOVED)); ++ if (!msg.IsSet() || !_FillMessage(*msg.Get(), fState)) ++ return; ++ ++ if (Device()->EnqueueMessage(msg.Get()) >= B_OK) ++ msg.Detach(); ++ } ++ ++ // update buttons ++ for (int i = 0; i < 32; i++) { ++ if ((IsBitSet(fState.buttons, i) ++ != IsBitSet(fNewState.buttons, i))) { ++ InvertBit(fState.buttons, i); ++ ObjectDeleter msg(new(std::nothrow) BMessage()); ++ if (!msg.IsSet() || !_FillMessage(*msg.Get(), fState)) ++ return; ++ ++ if (IsBitSet(fState.buttons, i)) { ++ msg->what = B_MOUSE_DOWN; ++ if (i == fLastClickBtn ++ && fState.when - fLastClick <= fClickSpeed) ++ fState.clicks++; ++ else ++ fState.clicks = 1; ++ fLastClickBtn = i; ++ fLastClick = fState.when; ++ msg->AddInt32("clicks", fState.clicks); ++ } else ++ msg->what = B_MOUSE_UP; ++ ++ if (Device()->EnqueueMessage(msg.Get()) >= B_OK) ++ msg.Detach(); ++ } ++ } ++ ++ // update wheel ++ if (fState.wheelX != fNewState.wheelX ++ || fState.wheelY != fNewState.wheelY) { ++ ObjectDeleter msg( ++ new(std::nothrow) BMessage(B_MOUSE_WHEEL_CHANGED)); ++ if ( ++ !msg.IsSet() ++ || msg->AddInt64("when", fState.when) < B_OK ++ || msg->AddFloat("be:wheel_delta_x", ++ fNewState.wheelX - fState.wheelX) < B_OK ++ || msg->AddFloat("be:wheel_delta_y", ++ fNewState.wheelY - fState.wheelY) < B_OK) ++ return; ++ ++ fState.wheelX = fNewState.wheelX; ++ fState.wheelY = fNewState.wheelY; ++ if (Device()->EnqueueMessage(msg.Get()) >= B_OK) ++ msg.Detach(); ++ } ++ break; ++ } ++ } ++} ++ ++ ++bool ++TabletHandler::_FillMessage(BMessage &msg, const TabletState &s) ++{ ++ if (msg.AddInt64("when", s.when) < B_OK ++ || msg.AddInt32("buttons", s.buttons) < B_OK ++ || msg.AddFloat("x", s.x) < B_OK ++ || msg.AddFloat("y", s.y) < B_OK) { ++ return false; ++ } ++ msg.AddFloat("be:tablet_x", s.x); ++ msg.AddFloat("be:tablet_y", s.y); ++ msg.AddFloat("be:tablet_pressure", s.pressure); ++ return true; ++} ++ ++ ++//#pragma mark - ++ ++extern "C" BInputServerDevice* ++instantiate_input_device() ++{ ++ return new(std::nothrow) VirtioInputDevice(); ++} +diff --git a/src/add-ons/input_server/devices/virtio/VirtioInputDevice.h b/src/add-ons/input_server/devices/virtio/VirtioInputDevice.h +new file mode 100644 +index 0000000000..8d976feb82 +--- /dev/null ++++ b/src/add-ons/input_server/devices/virtio/VirtioInputDevice.h +@@ -0,0 +1,148 @@ ++/* ++ * Copyright 2021, Haiku, Inc. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++#ifndef _VIRTIOINPUTDEVICE_H_ ++#define _VIRTIOINPUTDEVICE_H_ ++ ++#include ++#include ++#include ++#include ++#include ++ ++ ++struct VirtioInputPacket; ++ ++ ++struct KeyboardState { ++ bigtime_t when; ++ uint8 keys[256 / 8]; ++ uint32 modifiers; ++}; ++ ++struct TabletState { ++ bigtime_t when; ++ float x, y; ++ float pressure; ++ uint32 buttons; ++ int32 clicks; ++ int32 wheelX, wheelY; ++}; ++ ++ ++class VirtioInputDevice : public BInputServerDevice ++{ ++public: ++ VirtioInputDevice(); ++ virtual ~VirtioInputDevice(); ++ ++ virtual status_t InitCheck(); ++ ++ virtual status_t Start(const char* name, void* cookie); ++ virtual status_t Stop(const char* name, void* cookie); ++ ++ virtual status_t Control(const char* name, void* cookie, ++ uint32 command, BMessage* message); ++}; ++ ++ ++class VirtioHandler ++{ ++public: ++ VirtioHandler(VirtioInputDevice* dev, ++ const char* name, input_device_type type); ++ virtual ~VirtioHandler(); ++ inline VirtioInputDevice* ++ Device() ++ {return fDev;} ++ inline input_device_ref* ++ Ref() ++ {return &fRef;} ++ void SetFd(int fd); ++ ++ status_t Start(); ++ status_t Stop(); ++ ++ static status_t Watcher(void* arg); ++ ++ virtual void Reset() = 0; ++ virtual status_t Control(uint32 command, BMessage* message); ++ virtual void PacketReceived(const VirtioInputPacket &pkt) = 0; ++ ++private: ++ VirtioInputDevice* ++ fDev; ++ input_device_ref ++ fRef; ++ FileDescriptorCloser ++ fDeviceFd; ++ thread_id fWatcherThread; ++ bool fRun; ++}; ++ ++ ++class KeyboardHandler : public VirtioHandler ++{ ++public: ++ KeyboardHandler(VirtioInputDevice* dev, ++ const char* name); ++ virtual ~KeyboardHandler(); ++ ++ virtual void Reset(); ++ virtual status_t Control(uint32 command, BMessage* message); ++ virtual void PacketReceived(const VirtioInputPacket &pkt); ++ ++private: ++ static bool _IsKeyPressed(const KeyboardState& state, ++ uint32 key); ++ void _KeyString(uint32 code, char* str, size_t len); ++ void _StartRepeating(BMessage* msg); ++ void _StopRepeating(); ++ static status_t _RepeatThread(void* arg); ++ void _StateChanged(); ++ ++private: ++ KeyboardState fState; ++ KeyboardState fNewState; ++ BPrivate::AutoDeleter ++ fKeyMap; ++ BPrivate::AutoDeleter ++ fChars; ++ ++ bigtime_t fRepeatDelay; ++ int32 fRepeatRate; ++ thread_id fRepeatThread; ++ sem_id fRepeatThreadSem; ++ BMessage fRepeatMsg; ++}; ++ ++ ++class TabletHandler : public VirtioHandler ++{ ++public: ++ TabletHandler(VirtioInputDevice* dev, ++ const char* name); ++ ++ virtual void Reset(); ++ virtual status_t Control(uint32 command, BMessage* message); ++ virtual void PacketReceived(const VirtioInputPacket &pkt); ++ ++private: ++ static bool _FillMessage(BMessage& msg, const TabletState& s); ++ ++private: ++ TabletState fState; ++ TabletState fNewState; ++ bigtime_t fLastClick; ++ int fLastClickBtn; ++ ++ bigtime_t fClickSpeed; ++}; ++ ++ ++extern "C" _EXPORT BInputServerDevice* instantiate_input_device(); ++ ++ ++#endif // _VIRTIOINPUTDEVICE_H_ +-- +2.30.2 + diff --git a/patchset-hrev55144/0060-virtio_mmio-add.patch b/patchset-hrev55144/0060-virtio_mmio-add.patch new file mode 100644 index 0000000..3d606d0 --- /dev/null +++ b/patchset-hrev55144/0060-virtio_mmio-add.patch @@ -0,0 +1,948 @@ +From 521dafc53418fe8bf3e2b2581fd2b0a0db7e8bb7 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 24 May 2021 06:38:26 +0900 +Subject: virtio_mmio: add + +Change-Id: I2ca51d98e337d1e69a8e68d78ef0cfe33dc0d308 +--- + src/add-ons/kernel/busses/virtio/Jamfile | 11 +- + .../kernel/busses/virtio/virtio_mmio/Jamfile | 11 + + .../virtio/virtio_mmio/VirtioDevice.cpp | 267 ++++++++++ + .../busses/virtio/virtio_mmio/VirtioDevice.h | 88 ++++ + .../busses/virtio/virtio_mmio/virtio_mmio.cpp | 491 ++++++++++++++++++ + .../kernel/busses/virtio/virtio_pci/Jamfile | 9 + + .../virtio/{ => virtio_pci}/virtio_pci.cpp | 0 + .../virtio/{ => virtio_pci}/virtio_pci.h | 0 + 8 files changed, 869 insertions(+), 8 deletions(-) + create mode 100644 src/add-ons/kernel/busses/virtio/virtio_mmio/Jamfile + create mode 100644 src/add-ons/kernel/busses/virtio/virtio_mmio/VirtioDevice.cpp + create mode 100644 src/add-ons/kernel/busses/virtio/virtio_mmio/VirtioDevice.h + create mode 100644 src/add-ons/kernel/busses/virtio/virtio_mmio/virtio_mmio.cpp + create mode 100644 src/add-ons/kernel/busses/virtio/virtio_pci/Jamfile + rename src/add-ons/kernel/busses/virtio/{ => virtio_pci}/virtio_pci.cpp (100%) + rename src/add-ons/kernel/busses/virtio/{ => virtio_pci}/virtio_pci.h (100%) + +diff --git a/src/add-ons/kernel/busses/virtio/Jamfile b/src/add-ons/kernel/busses/virtio/Jamfile +index 650b1fe414..aacceb96d9 100644 +--- a/src/add-ons/kernel/busses/virtio/Jamfile ++++ b/src/add-ons/kernel/busses/virtio/Jamfile +@@ -1,9 +1,4 @@ +-SubDir HAIKU_TOP src add-ons kernel busses virtio ; ++SubDir HAIKU_TOP src add-ons kernel busses virio ; + +-SubDirC++Flags -fno-rtti ; +- +-UsePrivateHeaders kernel virtio ; +- +-KernelAddon virtio_pci : +- virtio_pci.cpp +-; ++SubInclude HAIKU_TOP src add-ons kernel busses virtio virtio_pci ; ++SubInclude HAIKU_TOP src add-ons kernel busses virtio virtio_mmio ; +diff --git a/src/add-ons/kernel/busses/virtio/virtio_mmio/Jamfile b/src/add-ons/kernel/busses/virtio/virtio_mmio/Jamfile +new file mode 100644 +index 0000000000..8cc4dda6b7 +--- /dev/null ++++ b/src/add-ons/kernel/busses/virtio/virtio_mmio/Jamfile +@@ -0,0 +1,11 @@ ++SubDir HAIKU_TOP src add-ons kernel busses virtio virtio_mmio ; ++ ++SubDirC++Flags -fno-rtti ; ++ ++UsePrivateKernelHeaders ; ++UsePrivateHeaders kernel virtio ; ++ ++KernelAddon virtio_mmio : ++ virtio_mmio.cpp ++ VirtioDevice.cpp ++; +diff --git a/src/add-ons/kernel/busses/virtio/virtio_mmio/VirtioDevice.cpp b/src/add-ons/kernel/busses/virtio/virtio_mmio/VirtioDevice.cpp +new file mode 100644 +index 0000000000..491c8aa4ad +--- /dev/null ++++ b/src/add-ons/kernel/busses/virtio/virtio_mmio/VirtioDevice.cpp +@@ -0,0 +1,267 @@ ++#include "VirtioDevice.h" ++ ++#include ++#include ++#include ++ ++#include ++#include ++#include ++ ++ ++static inline void SetLowHi(uint32 &low, uint32 &hi, uint64 val) ++{ ++ low = (uint32)val; ++ hi = (uint32)(val >> 32); ++} ++ ++ ++//#pragma mark VirtioQueue ++ ++VirtioQueue::VirtioQueue(VirtioDevice *dev, int32 id): ++ fDev(dev), fId(id), ++ fQueueHandler(NULL), fQueueHandlerCookie(NULL) ++{ ++} ++ ++VirtioQueue::~VirtioQueue() ++{ ++} ++ ++status_t VirtioQueue::Init() ++{ ++ fDev->fRegs->queueSel = fId; ++// dprintf("queueNumMax: "); dprintf("%d", fRegs->queueNumMax); dprintf("\n"); ++ fQueueLen = fDev->fRegs->queueNumMax; ++ fDev->fRegs->queueNum = fQueueLen; ++ fLastUsed = 0; ++ ++ size_t queueMemSize = 0; ++ fDescs = (VirtioDesc*)queueMemSize; queueMemSize += ROUNDUP(sizeof(VirtioDesc)*fQueueLen, B_PAGE_SIZE); ++ fAvail = (VirtioAvail*)queueMemSize; queueMemSize += ROUNDUP(sizeof(VirtioAvail) + sizeof(uint16)*fQueueLen, B_PAGE_SIZE); ++ fUsed = (VirtioUsed*)queueMemSize; queueMemSize += ROUNDUP(sizeof(VirtioUsed) + sizeof(VirtioUsedItem)*fQueueLen, B_PAGE_SIZE); ++ ++ uint8* queueMem = NULL; ++ fArea.SetTo(create_area("VirtIO Queue", (void**)&queueMem, B_ANY_KERNEL_ADDRESS, queueMemSize, B_CONTIGUOUS, B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA)); ++ if (!fArea.IsSet()) { ++ ERROR("can't create area: %08" B_PRIx32, fArea.Get()); ++ return fArea.Get(); ++ } ++ ++ physical_entry pe; ++ if(status_t res = get_memory_map(queueMem, queueMemSize, &pe, 1) < B_OK) { ++ ERROR("get_memory_map failed"); ++ return res; ++ } ++ ++ dprintf("queueMem: %p\n", queueMem); ++ ++ memset(queueMem, 0, queueMemSize); ++ ++ fDescs = (VirtioDesc*) ((uint8*)fDescs + (size_t)queueMem); ++ fAvail = (VirtioAvail*)((uint8*)fAvail + (size_t)queueMem); ++ fUsed = (VirtioUsed*) ((uint8*)fUsed + (size_t)queueMem); ++ ++ // dprintf("fDescs: %p\n", fDescs); ++ // dprintf("fAvail: %p\n", fAvail); ++ // dprintf("fUsed: %p\n", fUsed); ++ ++ phys_addr_t descsPhys = (addr_t)fDescs - (addr_t)queueMem + pe.address; ++ phys_addr_t availPhys = (addr_t)fAvail - (addr_t)queueMem + pe.address; ++ phys_addr_t usedPhys = (addr_t)fUsed - (addr_t)queueMem + pe.address; ++ ++ // dprintf("descsPhys: %08" B_PRIxADDR "\n", descsPhys); ++ // dprintf("availPhys: %08" B_PRIxADDR "\n", availPhys); ++ // dprintf("usedPhys: %08" B_PRIxADDR "\n", usedPhys); ++ ++ SetLowHi(fDev->fRegs->queueDescLow, fDev->fRegs->queueDescHi, descsPhys); ++ SetLowHi(fDev->fRegs->queueAvailLow, fDev->fRegs->queueAvailHi, availPhys); ++ SetLowHi(fDev->fRegs->queueUsedLow, fDev->fRegs->queueUsedHi, usedPhys); ++ ++ fFreeDescs.SetTo(new(std::nothrow) uint32[(fQueueLen + 31)/32]); ++ if (!fFreeDescs.IsSet()) ++ return B_NO_MEMORY; ++ memset(fFreeDescs.Get(), 0xff, sizeof(uint32)*((fQueueLen + 31)/32)); ++ fCookies.SetTo(new(std::nothrow) void*[fQueueLen]); ++ if (!fCookies.IsSet()) ++ return B_NO_MEMORY; ++ ++ fDev->fRegs->queueReady = 1; ++ ++ return B_OK; ++} ++ ++ ++int32 VirtioQueue::AllocDesc() ++{ ++ for (size_t i = 0; i < fQueueLen; i++) { ++ if ((fFreeDescs[i / 32] & (1 << (i % 32))) != 0) { ++ fFreeDescs[i / 32] &= ~((uint32)1 << (i % 32)); ++ return i; ++ } ++ } ++ return -1; ++} ++ ++void VirtioQueue::FreeDesc(int32 idx) ++{ ++ fFreeDescs[idx / 32] |= (uint32)1 << (idx % 32); ++} ++ ++status_t VirtioQueue::Enqueue( ++ const physical_entry* vector, ++ size_t readVectorCount, size_t writtenVectorCount, ++ void* cookie ++) ++{ ++ int32 firstDesc = -1, lastDesc; ++ size_t count = readVectorCount + writtenVectorCount; ++ if (count == 0) ++ return B_OK; ++ ++ for (size_t i = 0; i < count; i++) { ++ // dprintf(" vector[%" B_PRIuSIZE "]: 0x%" B_PRIx64 ", 0x%" B_PRIx64 ", %s\n", i, vector[i].address, vector[i].size, (i < readVectorCount) ? "read" : "write"); ++ int32 desc = AllocDesc(); ++ // dprintf("%p.AllocDesc(): %" B_PRId32 "\n", queue, desc); ++ if (desc < 0) { ++ ERROR("no free virtio descs, queue: %p\n", this); ++ ++ if (firstDesc >= 0) { ++ desc = firstDesc; ++ while (kVringDescFlagsNext & fDescs[desc].flags) { ++ int32_t nextDesc = fDescs[desc].next; ++ // dprintf("%p.FreeDesc(): %" B_PRId32 "\n", queue, desc); ++ FreeDesc(desc); ++ desc = nextDesc; ++ } ++ // dprintf("%p.FreeDesc(): %" B_PRId32 "\n", queue, desc); ++ FreeDesc(desc); ++ } ++ ++ return B_WOULD_BLOCK; ++ } ++ if (i == 0) { ++ firstDesc = desc; ++ } else { ++ fDescs[lastDesc].flags |= kVringDescFlagsNext; ++ fDescs[lastDesc].next = desc; ++ } ++ fDescs[desc].addr = vector[i].address; ++ fDescs[desc].len = vector[i].size; ++ fDescs[desc].flags = 0; ++ fDescs[desc].next = 0; ++ if (i >= readVectorCount) ++ fDescs[desc].flags |= kVringDescFlagsWrite; ++ ++ lastDesc = desc; ++ } ++ ++ int32_t idx = fAvail->idx % fQueueLen; ++ fCookies[idx] = cookie; ++ fAvail->ring[idx] = firstDesc; ++ fAvail->idx++; ++ fDev->fRegs->queueNotify = fId; ++ ++ return B_OK; ++} ++ ++bool VirtioQueue::Dequeue(void** _cookie, uint32* _usedLength) ++{ ++ fDev->fRegs->queueSel = fId; ++ ++ if (fUsed->idx == fLastUsed) ++ return false; ++ ++ if (_cookie != NULL) ++ *_cookie = fCookies[fLastUsed % fQueueLen]; ++ fCookies[fLastUsed % fQueueLen] = NULL; ++ ++ if (_usedLength != NULL) ++ *_usedLength = fUsed->ring[fLastUsed % fQueueLen].len; ++ ++ int32_t desc = fUsed->ring[fLastUsed % fQueueLen].id; ++ while (kVringDescFlagsNext & fDescs[desc].flags) { ++ int32_t nextDesc = fDescs[desc].next; ++ // dprintf("%p.FreeDesc(): %" B_PRId32 "\n", queue, desc); ++ FreeDesc(desc); ++ desc = nextDesc; ++ } ++ // dprintf("%p.FreeDesc(): %" B_PRId32 "\n", queue, desc); ++ FreeDesc(desc); ++ fLastUsed++; ++ ++ return true; ++} ++ ++ ++//#pragma mark VirtioIrqHandler ++ ++VirtioIrqHandler::VirtioIrqHandler(VirtioDevice* dev): fDev(dev) ++{ ++ fReferenceCount = 0; ++} ++ ++void VirtioIrqHandler::FirstReferenceAcquired() ++{ ++ install_io_interrupt_handler(fDev->fIrq, Handle, fDev, 0); ++} ++ ++void VirtioIrqHandler::LastReferenceReleased() ++{ ++ remove_io_interrupt_handler(fDev->fIrq, Handle, fDev); ++} ++ ++int32 VirtioIrqHandler::Handle(void* data) ++{ ++ // TRACE("VirtioIrqHandler::Handle(%p)\n", data); ++ VirtioDevice* dev = (VirtioDevice*)data; ++ ++ if ((kVirtioIntQueue & dev->fRegs->interruptStatus) != 0) { ++ for (int32 i = 0; i < dev->fQueueCnt; i++) { ++ VirtioQueue* queue = dev->fQueues[i].Get(); ++ if (queue->fUsed->idx != queue->fLastUsed && queue->fQueueHandler != NULL) ++ queue->fQueueHandler(dev->fConfigHandlerCookie, queue->fQueueHandlerCookie); ++ } ++ dev->fRegs->interruptAck = kVirtioIntQueue; ++ } ++ ++ if ((kVirtioIntConfig & dev->fRegs->interruptStatus) != 0) { ++ if (dev->fConfigHandler != NULL) ++ dev->fConfigHandler(dev->fConfigHandlerCookie); ++ ++ dev->fRegs->interruptAck = kVirtioIntConfig; ++ } ++ ++ return B_HANDLED_INTERRUPT; ++} ++ ++ ++//#pragma mark VirtioDevice ++ ++VirtioDevice::VirtioDevice(): ++ fRegs(NULL), ++ fQueueCnt(0), ++ fIrqHandler(this), ++ fConfigHandler(NULL), ++ fConfigHandlerCookie(NULL) ++{ ++} ++ ++status_t VirtioDevice::Init(phys_addr_t regs, size_t regsLen, int32 irq, int32 queueCnt) ++{ ++ fRegsArea.SetTo(map_physical_memory( ++ "Virtio MMIO", ++ regs, regsLen, B_ANY_KERNEL_ADDRESS, ++ B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA, ++ (void**)&fRegs ++ )); ++ if (!fRegsArea.IsSet()) ++ return fRegsArea.Get(); ++ ++ fIrq = irq; ++ ++ // Reset ++ fRegs->status = 0; ++ ++ return B_OK; ++} +diff --git a/src/add-ons/kernel/busses/virtio/virtio_mmio/VirtioDevice.h b/src/add-ons/kernel/busses/virtio/virtio_mmio/VirtioDevice.h +new file mode 100644 +index 0000000000..d671e0c5d1 +--- /dev/null ++++ b/src/add-ons/kernel/busses/virtio/virtio_mmio/VirtioDevice.h +@@ -0,0 +1,88 @@ ++#ifndef _VIRTIODEVICE_H_ ++#define _VIRTIODEVICE_H_ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++ ++#define TRACE_VIRTIO ++#ifdef TRACE_VIRTIO ++# define TRACE(x...) dprintf("virtio_mmio: " x) ++#else ++# define TRACE(x...) ; ++#endif ++#define TRACE_ALWAYS(x...) dprintf("virtio_mmio: " x) ++#define ERROR(x...) dprintf("virtio_mmio: " x) ++ ++ ++struct VirtioIrqHandler; ++struct VirtioDevice; ++ ++struct VirtioQueue { ++ VirtioDevice *fDev; ++ int32 fId; ++ size_t fQueueLen; ++ AreaDeleter fArea; ++ VirtioDesc *volatile fDescs; ++ VirtioAvail *volatile fAvail; ++ VirtioUsed *volatile fUsed; ++ ArrayDeleter fFreeDescs; ++ uint16 fLastUsed; ++ ArrayDeleter fCookies; ++ ++ BReference fQueueHandlerRef; ++ virtio_callback_func fQueueHandler; ++ void *fQueueHandlerCookie; ++ ++ VirtioQueue(VirtioDevice *dev, int32 id); ++ ~VirtioQueue(); ++ status_t Init(); ++ ++ int32 AllocDesc(); ++ void FreeDesc(int32 idx); ++ ++ status_t Enqueue( ++ const physical_entry* vector, ++ size_t readVectorCount, size_t writtenVectorCount, ++ void* cookie ++ ); ++ ++ bool Dequeue(void** _cookie, uint32* _usedLength); ++}; ++ ++struct VirtioIrqHandler: public BReferenceable ++{ ++ VirtioDevice* fDev; ++ ++ VirtioIrqHandler(VirtioDevice* dev); ++ ++ virtual void FirstReferenceAcquired(); ++ virtual void LastReferenceReleased(); ++ ++ static int32 Handle(void* data); ++}; ++ ++struct VirtioDevice ++{ ++ AreaDeleter fRegsArea; ++ VirtioRegs* volatile fRegs; ++ int32 fIrq; ++ int32 fQueueCnt; ++ ArrayDeleter > fQueues; ++ ++ VirtioIrqHandler fIrqHandler; ++ ++ BReference fConfigHandlerRef; ++ virtio_intr_func fConfigHandler; ++ void* fConfigHandlerCookie; ++ ++ VirtioDevice(); ++ status_t Init(phys_addr_t regs, size_t regsLen, int32 irq, int32 queueCnt); ++}; ++ ++ ++#endif // _VIRTIODEVICE_H_ +diff --git a/src/add-ons/kernel/busses/virtio/virtio_mmio/virtio_mmio.cpp b/src/add-ons/kernel/busses/virtio/virtio_mmio/virtio_mmio.cpp +new file mode 100644 +index 0000000000..d54f186bc8 +--- /dev/null ++++ b/src/add-ons/kernel/busses/virtio/virtio_mmio/virtio_mmio.cpp +@@ -0,0 +1,491 @@ ++/* ++ * Copyright 2013, 2018, Jรฉrรดme Duval, jerome.duval@gmail.com. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++ ++#include ++#include ++#include ++ ++#include ++#include ++#include ++ ++#include ++ ++#include ++ ++#include ++#include ++#include "VirtioDevice.h" ++ ++ ++#define VIRTIO_MMIO_DEVICE_MODULE_NAME "busses/virtio/virtio_mmio/driver_v1" ++ ++#define VIRTIO_MMIO_CONTROLLER_TYPE_NAME "virtio MMIO controller" ++ ++ ++device_manager_info* gDeviceManager; ++ ++ ++//#pragma mark Device ++ ++static float ++virtio_device_supports_device(device_node* parent) ++{ ++ TRACE("supports_device(%p)\n", parent); ++ ++ const char* name; ++ const char* bus; ++ const char* compatible; ++ ++ if (gDeviceManager->get_attr_string(parent, B_DEVICE_PRETTY_NAME, &name, false) >= B_OK) ++ dprintf(" name: %s\n", name); ++ ++ if ( ++ gDeviceManager->get_attr_string(parent, B_DEVICE_BUS, &bus, false) < B_OK || ++ gDeviceManager->get_attr_string(parent, "fdt/compatible", &compatible, false) < B_OK ++ ) { ++ return -1.0f; ++ } ++ ++ if (strcmp(bus, "fdt") != 0) ++ return 0.0f; ++ ++ if (strcmp(compatible, "virtio,mmio") != 0) ++ return 0.0f; ++ ++ return 1.0f; ++} ++ ++ ++static status_t ++virtio_device_register_device(device_node* parent) ++{ ++ TRACE("register_device(%p)\n", parent); ++ ++ fdt_device_module_info *parentModule; ++ fdt_device* parentDev; ++ if (gDeviceManager->get_driver(parent, (driver_module_info**)&parentModule, (void**)&parentDev)) { ++ ERROR("can't get parent node driver"); ++ return B_ERROR; ++ } ++ ++ uint64 regs, regsLen; ++ if (!parentModule->get_reg(parentDev, 0, ®s, ®sLen)) { ++ ERROR("no regs"); ++ return B_ERROR; ++ } ++ ++ VirtioRegs *volatile mappedRegs; ++ AreaDeleter fRegsArea(map_physical_memory( ++ "Virtio MMIO", ++ regs, regsLen, B_ANY_KERNEL_ADDRESS, ++ B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA, ++ (void **)&mappedRegs ++ )); ++ if (!fRegsArea.IsSet()) { ++ ERROR("cant't map regs"); ++ return B_ERROR; ++ } ++ ++ if (mappedRegs->signature != kVirtioSignature) { ++ ERROR("bad signature: 0x%08" B_PRIx32 ", should be 0x%08" B_PRIx32 "\n", mappedRegs->signature, kVirtioSignature); ++ return B_ERROR; ++ } ++ ++ dprintf(" version: 0x%08" B_PRIx32 "\n", mappedRegs->version); ++ dprintf(" deviceId: 0x%08" B_PRIx32 "\n", mappedRegs->deviceId); ++ dprintf(" vendorId: 0x%08" B_PRIx32 "\n", mappedRegs->vendorId); ++ ++ device_attr attrs[] = { ++ {B_DEVICE_PRETTY_NAME, B_STRING_TYPE, {string: "Virtio MMIO"}}, ++ {B_DEVICE_BUS, B_STRING_TYPE, {string: "virtio"}}, ++ {"virtio/version", B_UINT32_TYPE, {ui32: mappedRegs->version}}, ++ {"virtio/device_id", B_UINT32_TYPE, {ui32: mappedRegs->deviceId}}, ++ {"virtio/type", B_UINT16_TYPE, {ui16: (uint16)mappedRegs->deviceId}}, ++ {"virtio/vendor_id", B_UINT32_TYPE, {ui32: mappedRegs->vendorId}}, ++ {} ++ }; ++ ++ return gDeviceManager->register_node(parent, VIRTIO_MMIO_DEVICE_MODULE_NAME, ++ attrs, NULL, NULL); ++} ++ ++ ++static status_t ++virtio_device_init_device(device_node* node, void** cookie) ++{ ++ TRACE("init_device(%p)\n", node); ++ ++ device_node* parent = gDeviceManager->get_parent_node(node); ++ fdt_device_module_info *parentModule; ++ fdt_device* parentDev; ++ if (gDeviceManager->get_driver(parent, (driver_module_info**)&parentModule, (void**)&parentDev)) ++ panic("can't get parent node driver"); ++ ++ dprintf(" bus: %p\n", parentModule->get_bus(parentDev)); ++ dprintf(" compatible: %s\n", (const char*)parentModule->get_prop(parentDev, "compatible", NULL)); ++ ++ uint64 regs; ++ uint64 regsLen; ++ for (uint32 i = 0; parentModule->get_reg(parentDev, i, ®s, ®sLen); i++) { ++ dprintf(" reg[%" B_PRIu32 "]: (0x%" B_PRIx64 ", 0x%" B_PRIx64 ")\n", i, regs, regsLen); ++ } ++ ++ device_node* interruptController; ++ uint64 interrupt; ++ for (uint32 i = 0; parentModule->get_interrupt(parentDev, i, &interruptController, &interrupt); i++) { ++ const char* name; ++ if ( ++ interruptController == NULL || ++ gDeviceManager->get_attr_string(interruptController, "fdt/name", &name, false) < B_OK ++ ) name = NULL; ++ dprintf(" interrupt[%" B_PRIu32 "]: ('%s', 0x%" B_PRIx64 ")\n", i, name, interrupt); ++ } ++ ++ if (!parentModule->get_reg(parentDev, 0, ®s, ®sLen)) { ++ dprintf(" no regs\n"); ++ return B_ERROR; ++ } ++ ++ if (!parentModule->get_interrupt(parentDev, 0, &interruptController, &interrupt)) { ++ dprintf(" no interrupts\n"); ++ return B_ERROR; ++ } ++ ++ ObjectDeleter dev(new(std::nothrow) VirtioDevice()); ++ if (!dev.IsSet()) ++ return B_NO_MEMORY; ++ ++ status_t res = dev->Init(regs, regsLen, interrupt, 1); ++ if (res < B_OK) ++ return res; ++ ++ *cookie = dev.Detach(); ++ return B_OK; ++} ++ ++ ++static void ++virtio_device_uninit_device(void* cookie) ++{ ++ TRACE("uninit_device(%p)\n", cookie); ++ ObjectDeleter dev((VirtioDevice*)cookie); ++} ++ ++ ++static status_t ++virtio_device_register_child_devices(void* cookie) ++{ ++ TRACE("register_child_devices(%p)\n", cookie); ++ return B_OK; ++} ++ ++ ++//#pragma mark driver API ++ ++static const char * ++virtio_get_feature_name(uint32 feature) ++{ ++ switch (feature) { ++ case VIRTIO_FEATURE_NOTIFY_ON_EMPTY: ++ return "notify on empty"; ++ case VIRTIO_FEATURE_RING_INDIRECT_DESC: ++ return "ring indirect"; ++ case VIRTIO_FEATURE_RING_EVENT_IDX: ++ return "ring event index"; ++ case VIRTIO_FEATURE_BAD_FEATURE: ++ return "bad feature"; ++ } ++ return NULL; ++} ++ ++static void ++DumpFeatures(const char* title, uint32 features, ++ const char* (*get_feature_name)(uint32)) ++{ ++ char features_string[512] = ""; ++ for (uint32 i = 0; i < 32; i++) { ++ uint32 feature = features & (1 << i); ++ if (feature == 0) ++ continue; ++ const char* name = virtio_get_feature_name(feature); ++ if (name == NULL) ++ name = get_feature_name(feature); ++ if (name != NULL) { ++ strlcat(features_string, "[", sizeof(features_string)); ++ strlcat(features_string, name, sizeof(features_string)); ++ strlcat(features_string, "] ", sizeof(features_string)); ++ } ++ } ++ TRACE("%s: %s\n", title, features_string); ++} ++ ++static status_t ++virtio_device_negotiate_features(virtio_device cookie, uint32 supported, ++ uint32* negotiated, const char* (*get_feature_name)(uint32)) ++{ ++ TRACE("virtio_device_negotiate_features(%p)\n", cookie); ++ VirtioDevice* dev = (VirtioDevice*)cookie; ++ ++ dev->fRegs->status |= kVirtioConfigSAcknowledge; ++ dev->fRegs->status |= kVirtioConfigSDriver; ++ ++ uint32 features = dev->fRegs->deviceFeatures; ++ DumpFeatures("read features", features, get_feature_name); ++ features &= supported; ++ // filter our own features ++ features &= (VIRTIO_FEATURE_TRANSPORT_MASK | VIRTIO_FEATURE_RING_INDIRECT_DESC | VIRTIO_FEATURE_RING_EVENT_IDX); ++ *negotiated = features; ++ DumpFeatures("negotiated features", features, get_feature_name); ++ dev->fRegs->driverFeatures = features; ++ ++ dev->fRegs->status |= kVirtioConfigSFeaturesOk; ++ dev->fRegs->status |= kVirtioConfigSDriverOk; ++ ++ dev->fRegs->guestPageSize = B_PAGE_SIZE; ++ ++ return B_OK; ++} ++ ++static status_t ++virtio_device_clear_feature(virtio_device cookie, uint32 feature) ++{ ++ panic("not implemented"); ++ return B_ERROR; ++} ++ ++static status_t ++virtio_device_read_device_config(virtio_device cookie, uint8 offset, ++ void* buffer, size_t bufferSize) ++{ ++ TRACE("virtio_device_read_device_config(%p, %d, %" B_PRIuSIZE ")\n", cookie, offset, bufferSize); ++ VirtioDevice* dev = (VirtioDevice*)cookie; ++ memcpy(buffer, dev->fRegs->config + offset, bufferSize); ++ return B_OK; ++} ++ ++static status_t ++virtio_device_write_device_config(virtio_device cookie, uint8 offset, ++ const void* buffer, size_t bufferSize) ++{ ++ TRACE("virtio_device_write_device_config(%p, %d, %" B_PRIuSIZE ")\n", cookie, offset, bufferSize); ++ VirtioDevice* dev = (VirtioDevice*)cookie; ++ memcpy(dev->fRegs->config + offset, buffer, bufferSize); ++ return B_OK; ++} ++ ++static status_t ++virtio_device_alloc_queues(virtio_device cookie, size_t count, ++ virtio_queue* queues) ++{ ++ TRACE("virtio_device_alloc_queues(%p, %" B_PRIuSIZE ")\n", cookie, count); ++ VirtioDevice* dev = (VirtioDevice*)cookie; ++ ++ ArrayDeleter > newQueues(new(std::nothrow) ObjectDeleter[count]); ++ if (!newQueues.IsSet()) ++ return B_NO_MEMORY; ++ ++ for (size_t i = 0; i < count; i++) { ++ newQueues[i].SetTo(new(std::nothrow) VirtioQueue(dev, i)); ++ if (!newQueues[i].IsSet()) ++ return B_NO_MEMORY; ++ if (status_t res = newQueues[i]->Init() < B_OK) ++ return res; ++ } ++ ++ dev->fQueueCnt = count; ++ dev->fQueues.SetTo(newQueues.Detach()); ++ ++ for (size_t i = 0; i < count; i++) ++ queues[i] = dev->fQueues[i].Get(); ++ ++ return B_OK; ++} ++ ++static void ++virtio_device_free_queues(virtio_device cookie) ++{ ++ TRACE("virtio_device_free_queues(%p)\n", cookie); ++ VirtioDevice* dev = (VirtioDevice*)cookie; ++ ++ dev->fQueues.Unset(); ++ dev->fQueueCnt = 0; ++} ++ ++ ++void WritePC(addr_t adr); ++ ++static status_t ++virtio_device_setup_interrupt(virtio_device cookie, ++ virtio_intr_func config_handler, void* driverCookie) ++{ ++ VirtioDevice* dev = (VirtioDevice*)cookie; ++ TRACE_ALWAYS("virtio_device_setup_interrupt(%p, ", dev); ++ WritePC((addr_t)config_handler); ++ dprintf(")\n"); ++ ++ dev->fConfigHandler = config_handler; ++ dev->fConfigHandlerCookie = driverCookie; ++ dev->fConfigHandlerRef.SetTo((config_handler == NULL) ? NULL : &dev->fIrqHandler); ++ ++ return B_OK; ++} ++ ++static status_t ++virtio_device_free_interrupts(virtio_device cookie) ++{ ++ VirtioDevice* dev = (VirtioDevice*)cookie; ++ TRACE("virtio_device_free_interrupts(%p)\n", dev); ++ ++ for (int32 i = 0; i < dev->fQueueCnt; i++) { ++ VirtioQueue* queue = dev->fQueues[i].Get(); ++ queue->fQueueHandler = NULL; ++ queue->fQueueHandlerCookie = NULL; ++ queue->fQueueHandlerRef.Unset(); ++ } ++ ++ dev->fConfigHandler = NULL; ++ dev->fConfigHandlerCookie = NULL; ++ dev->fConfigHandlerRef.Unset(); ++ ++ return B_OK; ++} ++ ++static status_t ++virtio_device_queue_setup_interrupt(virtio_queue aQueue, ++ virtio_callback_func handler, void* cookie) ++{ ++ TRACE("virtio_device_queue_setup_interrupt(%p, ", aQueue); ++ WritePC((addr_t)handler); ++ dprintf(")\n"); ++ ++ VirtioQueue* queue = (VirtioQueue*)aQueue; ++ VirtioDevice* dev = queue->fDev; ++ ++ queue->fQueueHandler = handler; ++ queue->fQueueHandlerCookie = cookie; ++ queue->fQueueHandlerRef.SetTo((handler == NULL) ? NULL : &dev->fIrqHandler); ++ ++ return B_OK; ++} ++ ++static status_t ++virtio_device_queue_request_v(virtio_queue aQueue, ++ const physical_entry* vector, ++ size_t readVectorCount, size_t writtenVectorCount, ++ void* cookie) ++{ ++ // TRACE("virtio_device_queue_request_v(%p, %" B_PRIuSIZE ", %" B_PRIuSIZE ", %p)\n", aQueue, readVectorCount, writtenVectorCount, cookie); ++ VirtioQueue* queue = (VirtioQueue*)aQueue; ++ ++ return queue->Enqueue(vector, readVectorCount, writtenVectorCount, cookie); ++} ++ ++static status_t ++virtio_device_queue_request(virtio_queue aQueue, ++ const physical_entry* readEntry, ++ const physical_entry* writtenEntry, void* cookie) ++{ ++ VirtioQueue* queue = (VirtioQueue*)aQueue; ++ ++ physical_entry vector[2]; ++ physical_entry* vectorEnd = vector; ++ if (readEntry != NULL) *vectorEnd++ = *readEntry; ++ if (writtenEntry != NULL) *vectorEnd++ = *writtenEntry; ++ ++ return queue->Enqueue( ++ vector, ++ (readEntry != NULL) ? 1 : 0, ++ (writtenEntry != NULL) ? 1 : 0, ++ cookie ++ ); ++} ++ ++static bool ++virtio_device_queue_is_full(virtio_queue queue) ++{ ++ panic("not implemented"); ++ return false; ++} ++ ++static bool ++virtio_device_queue_is_empty(virtio_queue aQueue) ++{ ++ VirtioQueue *queue = (VirtioQueue *)aQueue; ++ return queue->fUsed->idx == queue->fLastUsed; ++} ++ ++static uint16 ++virtio_device_queue_size(virtio_queue aQueue) ++{ ++ VirtioQueue *queue = (VirtioQueue *)aQueue; ++ return (uint16)queue->fQueueLen; ++} ++ ++static bool ++virtio_device_queue_dequeue(virtio_queue aQueue, void** _cookie, ++ uint32* _usedLength) ++{ ++ // TRACE("virtio_device_queue_dequeue(%p)\n", aQueue); ++ VirtioQueue* queue = (VirtioQueue*)aQueue; ++ return queue->Dequeue(_cookie, _usedLength); ++} ++ ++ ++//#pragma mark - ++ ++module_dependency module_dependencies[] = { ++ {B_DEVICE_MANAGER_MODULE_NAME, (module_info**)&gDeviceManager}, ++ {} ++}; ++ ++ ++static virtio_device_interface sVirtioDevice = { ++ { ++ { ++ VIRTIO_MMIO_DEVICE_MODULE_NAME, ++ 0, ++ NULL ++ }, ++ ++ virtio_device_supports_device, ++ virtio_device_register_device, ++ virtio_device_init_device, ++ virtio_device_uninit_device, ++ virtio_device_register_child_devices, ++ NULL, // rescan ++ NULL, // device removed ++ }, ++ virtio_device_negotiate_features, ++ virtio_device_clear_feature, ++ virtio_device_read_device_config, ++ virtio_device_write_device_config, ++ virtio_device_alloc_queues, ++ virtio_device_free_queues, ++ virtio_device_setup_interrupt, ++ virtio_device_free_interrupts, ++ virtio_device_queue_setup_interrupt, ++ virtio_device_queue_request, ++ virtio_device_queue_request_v, ++ virtio_device_queue_is_full, ++ virtio_device_queue_is_empty, ++ virtio_device_queue_size, ++ virtio_device_queue_dequeue, ++}; ++ ++module_info* modules[] = { ++ (module_info* )&sVirtioDevice, ++ NULL ++}; ++ ++/* ++ ++VirtIO block driver use ++ string B_DEVICE_BUS == "virtio" ++ uint16 "virtio/type" == 2 ++ ++ virtio_device_interface ++*/ +diff --git a/src/add-ons/kernel/busses/virtio/virtio_pci/Jamfile b/src/add-ons/kernel/busses/virtio/virtio_pci/Jamfile +new file mode 100644 +index 0000000000..45708f2f02 +--- /dev/null ++++ b/src/add-ons/kernel/busses/virtio/virtio_pci/Jamfile +@@ -0,0 +1,9 @@ ++SubDir HAIKU_TOP src add-ons kernel busses virtio virtio_pci ; ++ ++SubDirC++Flags -fno-rtti ; ++ ++UsePrivateHeaders kernel virtio ; ++ ++KernelAddon virtio_pci : ++ virtio_pci.cpp ++; +diff --git a/src/add-ons/kernel/busses/virtio/virtio_pci.cpp b/src/add-ons/kernel/busses/virtio/virtio_pci/virtio_pci.cpp +similarity index 100% +rename from src/add-ons/kernel/busses/virtio/virtio_pci.cpp +rename to src/add-ons/kernel/busses/virtio/virtio_pci/virtio_pci.cpp +diff --git a/src/add-ons/kernel/busses/virtio/virtio_pci.h b/src/add-ons/kernel/busses/virtio/virtio_pci/virtio_pci.h +similarity index 100% +rename from src/add-ons/kernel/busses/virtio/virtio_pci.h +rename to src/add-ons/kernel/busses/virtio/virtio_pci/virtio_pci.h +-- +2.30.2 + diff --git a/patchset-hrev55144/0061-virtio_input-add.patch b/patchset-hrev55144/0061-virtio_input-add.patch new file mode 100644 index 0000000..7c2b3ec --- /dev/null +++ b/patchset-hrev55144/0061-virtio_input-add.patch @@ -0,0 +1,575 @@ +From 15340221c460d310e3cdf6091f4a9e994d262191 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 24 May 2021 06:41:04 +0900 +Subject: virtio_input: add + +Change-Id: I10af2b30c79d1e8ff890d45642988f362d3d0a1e +--- + headers/private/input/virtio_input_driver.h | 15 + + src/add-ons/kernel/drivers/input/Jamfile | 1 + + .../kernel/drivers/input/virtio_input/Jamfile | 9 + + .../input/virtio_input/virtio_input.cpp | 505 ++++++++++++++++++ + 4 files changed, 530 insertions(+) + create mode 100644 headers/private/input/virtio_input_driver.h + create mode 100644 src/add-ons/kernel/drivers/input/virtio_input/Jamfile + create mode 100644 src/add-ons/kernel/drivers/input/virtio_input/virtio_input.cpp + +diff --git a/headers/private/input/virtio_input_driver.h b/headers/private/input/virtio_input_driver.h +new file mode 100644 +index 0000000000..d61ff07ea4 +--- /dev/null ++++ b/headers/private/input/virtio_input_driver.h +@@ -0,0 +1,15 @@ ++#ifndef _VIRTIO_INPUT_DRIVER_H_ ++#define _VIRTIO_INPUT_DRIVER_H_ ++ ++ ++#include ++#include ++ ++ ++enum { ++ virtioInputRead = B_DEVICE_OP_CODES_END + 1, ++ virtioInputCancelIO = B_DEVICE_OP_CODES_END + 2, ++}; ++ ++ ++#endif // _VIRTIO_INPUT_DRIVER_H_ +diff --git a/src/add-ons/kernel/drivers/input/Jamfile b/src/add-ons/kernel/drivers/input/Jamfile +index 73ba672d6a..00eeb816c6 100644 +--- a/src/add-ons/kernel/drivers/input/Jamfile ++++ b/src/add-ons/kernel/drivers/input/Jamfile +@@ -4,3 +4,4 @@ SubInclude HAIKU_TOP src add-ons kernel drivers input i2c_hid ; + SubInclude HAIKU_TOP src add-ons kernel drivers input ps2_hid ; + SubInclude HAIKU_TOP src add-ons kernel drivers input usb_hid ; + SubInclude HAIKU_TOP src add-ons kernel drivers input wacom ; ++SubInclude HAIKU_TOP src add-ons kernel drivers input virtio_input ; +diff --git a/src/add-ons/kernel/drivers/input/virtio_input/Jamfile b/src/add-ons/kernel/drivers/input/virtio_input/Jamfile +new file mode 100644 +index 0000000000..2a93617803 +--- /dev/null ++++ b/src/add-ons/kernel/drivers/input/virtio_input/Jamfile +@@ -0,0 +1,9 @@ ++SubDir HAIKU_TOP src add-ons kernel drivers input virtio_input ; ++ ++UsePrivateKernelHeaders ; ++UsePrivateHeaders drivers virtio input ; ++SubDirHdrs $(HAIKU_TOP) src system kernel device_manager ; ++ ++KernelAddon virtio_input : ++ virtio_input.cpp ++; +diff --git a/src/add-ons/kernel/drivers/input/virtio_input/virtio_input.cpp b/src/add-ons/kernel/drivers/input/virtio_input/virtio_input.cpp +new file mode 100644 +index 0000000000..688996e979 +--- /dev/null ++++ b/src/add-ons/kernel/drivers/input/virtio_input/virtio_input.cpp +@@ -0,0 +1,505 @@ ++/* ++ * Copyright 2013, Jรฉrรดme Duval, korli@users.berlios.de. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++ ++#include ++#include ++ ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++ ++#include ++ ++#include ++#include ++#include ++#include ++ ++ ++#define VIRTIO_INPUT_DRIVER_MODULE_NAME "drivers/input/virtio_input/driver_v1" ++#define VIRTIO_INPUT_DEVICE_MODULE_NAME "drivers/input/virtio_input/device_v1" ++#define VIRTIO_INPUT_DEVICE_ID_GENERATOR "virtio_input/device_id" ++ ++ ++struct Packet { ++ VirtioInputPacket data; ++ int32 next; ++}; ++ ++struct VirtioInputDevice { ++ device_node* node; ++ ::virtio_device virtio_device; ++ virtio_device_interface* virtio; ++ ::virtio_queue virtio_queue; ++ ++ uint32 features; ++ ++ uint32 packetCnt; ++ int32 freePackets; ++ int32 readyPackets, lastReadyPacket; ++ AreaDeleter packetArea; ++ phys_addr_t physAdr; ++ Packet* packets; ++ ++ SemDeleter sem_cb; ++}; ++ ++ ++struct VirtioInputHandle { ++ VirtioInputDevice* info; ++}; ++ ++ ++ ++#define TRACE_VIRTIO_INPUT ++#ifdef TRACE_VIRTIO_INPUT ++# define TRACE(x...) dprintf("virtio_input: " x) ++#else ++# define TRACE(x...) ; ++#endif ++#define ERROR(x...) dprintf("virtio_input: " x) ++#define CALLED() TRACE("CALLED %s\n", __PRETTY_FUNCTION__) ++ ++ ++static device_manager_info* sDeviceManager; ++ ++ ++static void WriteInputPacket(const VirtioInputPacket &pkt) ++{ ++ switch (pkt.type) { ++ case kVirtioInputEvSyn: dprintf("syn"); break; ++ case kVirtioInputEvKey: dprintf("key"); ++ dprintf(", "); ++ switch (pkt.code) { ++ case kVirtioInputBtnLeft: dprintf("left"); break; ++ case kVirtioInputBtnRight: dprintf("middle"); break; ++ case kVirtioInputBtnMiddle: dprintf("right"); break; ++ case kVirtioInputBtnGearDown: dprintf("gearDown"); break; ++ case kVirtioInputBtnGearUp: dprintf("gearUp"); break; ++ default: dprintf("%d", pkt.code); ++ } ++ break; ++ case kVirtioInputEvRel: dprintf("rel"); ++ dprintf(", "); ++ switch (pkt.code) { ++ case kVirtioInputRelX: dprintf("relX"); break; ++ case kVirtioInputRelY: dprintf("relY"); break; ++ case kVirtioInputRelZ: dprintf("relZ"); break; ++ case kVirtioInputRelWheel: dprintf("relWheel"); break; ++ default: dprintf("%d", pkt.code); ++ } ++ break; ++ case kVirtioInputEvAbs: dprintf("abs"); ++ dprintf(", "); ++ switch (pkt.code) { ++ case kVirtioInputAbsX: dprintf("absX"); break; ++ case kVirtioInputAbsY: dprintf("absY"); break; ++ case kVirtioInputAbsZ: dprintf("absZ"); break; ++ default: dprintf("%d", pkt.code); ++ } ++ break; ++ case kVirtioInputEvRep: dprintf("rep"); break; ++ default: dprintf("?(%d)", pkt.type); ++ } ++ switch (pkt.type) { ++ case kVirtioInputEvSyn: break; ++ case kVirtioInputEvKey: dprintf(", "); if (pkt.value == 0) dprintf("up"); else if (pkt.value == 1) dprintf("down"); else dprintf("%d", pkt.value); break; ++ default: dprintf(", "); dprintf("%d", pkt.value); ++ } ++} ++ ++ ++static void InitPackets(VirtioInputDevice* dev, uint32 count) ++{ ++ TRACE("InitPackets(%p, %" B_PRIu32 ")\n", dev, count); ++ size_t size = ROUNDUP(sizeof(Packet)*count, B_PAGE_SIZE); ++ ++ dev->packetArea.SetTo(create_area( ++ "VirtIO input packets", (void**)&dev->packets, B_ANY_KERNEL_ADDRESS, size, B_CONTIGUOUS, B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA ++ )); ++ ASSERT(dev->packetArea.IsSet()); ++ physical_entry pe; ++ ASSERT(get_memory_map(dev->packets, size, &pe, 1) >= B_OK); ++ dev->physAdr = pe.address; ++ memset(dev->packets, 0, size); ++ dprintf(" size: 0x%" B_PRIxSIZE "\n", size); ++ dprintf(" virt: %p\n", dev->packets); ++ dprintf(" phys: %p\n", (void*)dev->physAdr); ++ ++ dev->packetCnt = count; ++ ++ dev->freePackets = 0; ++ for (uint32 i = 0; i < dev->packetCnt - 1; i++) ++ dev->packets[i].next = i + 1; ++ dev->packets[dev->packetCnt - 1].next = -1; ++ ++ dev->readyPackets = -1; ++ dev->lastReadyPacket = -1; ++} ++ ++ ++static const physical_entry PacketPhysEntry(VirtioInputDevice* dev, Packet* pkt) ++{ ++ physical_entry pe; ++ pe.address = dev->physAdr + (uint8*)pkt - (uint8*)dev->packets; ++ pe.size = sizeof(VirtioInputPacket); ++ return pe; ++} ++ ++static Packet* AllocPacket(VirtioInputDevice* dev) ++{ ++ int32 idx = dev->freePackets; ++ if (idx < 0) return NULL; ++ dev->freePackets = dev->packets[idx].next; ++ return &dev->packets[idx]; ++} ++ ++static void FreePacket(VirtioInputDevice* dev, Packet* pkt) ++{ ++ pkt->next = dev->freePackets; ++ dev->freePackets = pkt - dev->packets; ++} ++ ++static void ScheduleReadyPacket(VirtioInputDevice* dev, Packet* pkt) ++{ ++ if (dev->readyPackets < 0) ++ dev->readyPackets = pkt - dev->packets; ++ else ++ dev->packets[dev->lastReadyPacket].next = pkt - dev->packets; ++ ++ dev->lastReadyPacket = pkt - dev->packets; ++} ++ ++static Packet *ConsumeReadyPacket(VirtioInputDevice* dev) ++{ ++ if (dev->readyPackets < 0) ++ return NULL; ++ Packet* pkt = &dev->packets[dev->readyPackets]; ++ dev->readyPackets = pkt->next; ++ if (dev->readyPackets < 0) ++ dev->lastReadyPacket = -1; ++ return pkt; ++} ++ ++static void ++virtio_input_callback(void* driverCookie, void* cookie) ++{ ++ // TRACE("virtio_input_callback(%p, %p)\n", driverCookie, cookie); ++ VirtioInputDevice* dev = (VirtioInputDevice*)cookie; ++ ++ Packet* pkt; ++ while (dev->virtio->queue_dequeue(dev->virtio_queue, (void**)&pkt, NULL)) { ++ // dprintf("%" B_PRIdSSIZE ": ", pkt - dev->packets); WriteInputPacket(pkt->data); dprintf("\n"); ++ ScheduleReadyPacket(dev, pkt); ++ release_sem_etc(dev->sem_cb.Get(), 1, B_DO_NOT_RESCHEDULE); ++ // enable_interrupts(); ++ // release_sem(dev->sem_cb.Get()); ++ } ++} ++ ++ ++// #pragma mark - device module API ++ ++ ++static status_t ++virtio_input_init_device(void* _info, void** _cookie) ++{ ++ TRACE("virtio_input_init_device(%p)\n", _info); ++ VirtioInputDevice* info = (VirtioInputDevice*)_info; ++ ++ DeviceNodePutter<&sDeviceManager> parent(sDeviceManager->get_parent_node(info->node)); ++ sDeviceManager->get_driver(parent.Get(), (driver_module_info **)&info->virtio, ++ (void **)&info->virtio_device); ++ ++ info->virtio->negotiate_features(info->virtio_device, 0, &info->features, NULL); ++ ++ status_t status = B_OK; ++/* ++ status = info->virtio->read_device_config( ++ info->virtio_device, 0, &info->config, ++ sizeof(struct virtio_blk_config)); ++ if (status != B_OK) ++ return status; ++*/ ++ ++ InitPackets(info, 8); ++ ++ status = info->virtio->alloc_queues(info->virtio_device, 1, ++ &info->virtio_queue); ++ if (status != B_OK) { ++ ERROR("queue allocation failed (%s)\n", strerror(status)); ++ return status; ++ } ++ TRACE(" queue: %p\n", info->virtio_queue); ++ ++ status = info->virtio->queue_setup_interrupt(info->virtio_queue, ++ virtio_input_callback, info); ++ if (status < B_OK) ++ return status; ++ ++ for (uint32 i = 0; i < info->packetCnt; i++) { ++ Packet* pkt = &info->packets[i]; ++ physical_entry pe = PacketPhysEntry(info, pkt); ++ info->virtio->queue_request(info->virtio_queue, NULL, &pe, pkt); ++ } ++ ++ *_cookie = info; ++ return B_OK; ++} ++ ++ ++static void ++virtio_input_uninit_device(void* _cookie) ++{ ++ TRACE("virtio_input_uninit_device(%p)\n", _cookie); ++ VirtioInputDevice* info = (VirtioInputDevice*)_cookie; ++ (void)info; ++} ++ ++ ++static status_t ++virtio_input_open(void* _info, const char* path, int openMode, void** _cookie) ++{ ++ TRACE("virtio_input_open(%p, \"%s\", %d)\n", _info, path, openMode); ++ VirtioInputDevice* info = (VirtioInputDevice*)_info; ++ ++ ObjectDeleter handle(new(std::nothrow) (VirtioInputHandle)); ++ if (!handle.IsSet()) ++ return B_NO_MEMORY; ++ ++ handle->info = info; ++ ++ *_cookie = handle.Detach(); ++ return B_OK; ++} ++ ++ ++static status_t ++virtio_input_close(void* cookie) ++{ ++ TRACE("virtio_input_close(%p)\n", cookie); ++ return B_OK; ++} ++ ++ ++static status_t ++virtio_input_free(void* cookie) ++{ ++ TRACE("virtio_input_free(%p)\n", cookie); ++ ObjectDeleter handle((VirtioInputHandle*)cookie); ++ return B_OK; ++} ++ ++ ++static status_t ++virtio_input_read(void* cookie, off_t pos, void* buffer, size_t* _length) ++{ ++ return B_ERROR; ++} ++ ++ ++static status_t ++virtio_input_write(void* cookie, off_t pos, const void* buffer, ++ size_t* _length) ++{ ++ *_length = 0; ++ return B_ERROR; ++} ++ ++ ++static status_t ++virtio_input_ioctl(void* cookie, uint32 op, void* buffer, size_t length) ++{ ++ // TRACE("virtio_input_ioctl(%p, %" B_PRIu32 ")\n", cookie, op); ++ ++ VirtioInputHandle* handle = (VirtioInputHandle*)cookie; ++ VirtioInputDevice* info = handle->info; ++ (void)info; ++ ++ // TRACE("ioctl(op = %" B_PRIu32 ")\n", op); ++ ++ switch (op) { ++ case virtioInputRead: { ++ // dprintf("virtioInputRead\n"); ++ if (buffer == NULL || length < sizeof(VirtioInputPacket)) ++ return B_BAD_VALUE; ++ ++ status_t res = acquire_sem(info->sem_cb.Get()); ++ if (res < B_OK) return res; ++ ++ Packet* pkt = ConsumeReadyPacket(info); ++ // dprintf(" pkt: %" B_PRIdSSIZE "\n", pkt - info->packets); ++ ++ physical_entry pe = PacketPhysEntry(info, pkt); ++ info->virtio->queue_request(info->virtio_queue, NULL, &pe, pkt); ++ ++ res = user_memcpy(buffer, pkt, sizeof(Packet)); ++ if (res < B_OK) ++ return res; ++ ++ return B_OK; ++ } ++ } ++ ++ return B_DEV_INVALID_IOCTL; ++} ++ ++ ++// #pragma mark - driver module API ++ ++ ++static float ++virtio_input_supports_device(device_node *parent) ++{ ++ TRACE("virtio_input_supports_device(%p)\n", parent); ++ ++ const char *bus; ++ uint16 deviceType; ++ ++ // make sure parent is really the Virtio bus manager ++ if (sDeviceManager->get_attr_string(parent, B_DEVICE_BUS, &bus, false)) ++ return -1; ++ ++ if (strcmp(bus, "virtio")) ++ return 0.0; ++ ++ // check whether it's really a Direct Access Device ++ if (sDeviceManager->get_attr_uint16(parent, VIRTIO_DEVICE_TYPE_ITEM, ++ &deviceType, true) != B_OK || deviceType != kVirtioDevInput) ++ return 0.0; ++ ++ TRACE("Virtio input device found!\n"); ++ ++ return 0.6; ++} ++ ++ ++static status_t ++virtio_input_register_device(device_node *node) ++{ ++ TRACE("virtio_input_register_device(%p)\n", node); ++ ++ device_attr attrs[] = { ++ { B_DEVICE_PRETTY_NAME, B_STRING_TYPE, { string: "VirtIO input" }}, ++ { NULL } ++ }; ++ ++ return sDeviceManager->register_node(node, VIRTIO_INPUT_DRIVER_MODULE_NAME, ++ attrs, NULL, NULL); ++} ++ ++ ++static status_t ++virtio_input_init_driver(device_node *node, void **cookie) ++{ ++ TRACE("virtio_input_init_driver(%p)\n", node); ++ ++ ObjectDeleter info(new(std::nothrow) VirtioInputDevice()); ++ if (!info.IsSet()) ++ return B_NO_MEMORY; ++ ++ memset(info.Get(), 0, sizeof(*info.Get())); ++ ++ info->sem_cb.SetTo(create_sem(0, "virtio_input_cb")); ++ if (!info->sem_cb.IsSet()) { ++ return info->sem_cb.Get(); ++ } ++ info->node = node; ++ ++ *cookie = info.Detach(); ++ return B_OK; ++} ++ ++ ++static void ++virtio_input_uninit_driver(void *_cookie) ++{ ++ TRACE("virtio_input_uninit_driver(%p)\n", _cookie); ++ ObjectDeleter info((VirtioInputDevice*)_cookie); ++} ++ ++ ++static status_t ++virtio_input_register_child_devices(void* _cookie) ++{ ++ TRACE("virtio_input_register_child_devices(%p)\n", _cookie); ++ VirtioInputDevice* info = (VirtioInputDevice*)_cookie; ++ status_t status; ++ ++ int32 id = sDeviceManager->create_id(VIRTIO_INPUT_DEVICE_ID_GENERATOR); ++ if (id < 0) ++ return id; ++ ++ char name[64]; ++ snprintf(name, sizeof(name), "input/virtio/%" B_PRId32 "/raw", id); ++ ++ status = sDeviceManager->publish_device(info->node, name, VIRTIO_INPUT_DEVICE_MODULE_NAME); ++ if (status < B_OK) { ++ TRACE(" error: 0x%" B_PRIx32 "(%s) \n", status, strerror(status)); ++ panic("(!)"); ++ } ++ ++ return status; ++} ++ ++ ++// #pragma mark - ++ ++ ++module_dependency module_dependencies[] = { ++ {B_DEVICE_MANAGER_MODULE_NAME, (module_info**)&sDeviceManager}, ++ {} ++}; ++ ++struct device_module_info sVirtioBlockDevice = { ++ { ++ VIRTIO_INPUT_DEVICE_MODULE_NAME, ++ 0, ++ NULL ++ }, ++ ++ virtio_input_init_device, ++ virtio_input_uninit_device, ++ NULL, // remove, ++ ++ virtio_input_open, ++ virtio_input_close, ++ virtio_input_free, ++ virtio_input_read, ++ virtio_input_write, ++ NULL, ++ virtio_input_ioctl, ++ ++ NULL, // select ++ NULL, // deselect ++}; ++ ++struct driver_module_info sVirtioBlockDriver = { ++ { ++ VIRTIO_INPUT_DRIVER_MODULE_NAME, ++ 0, ++ NULL ++ }, ++ ++ virtio_input_supports_device, ++ virtio_input_register_device, ++ virtio_input_init_driver, ++ virtio_input_uninit_driver, ++ virtio_input_register_child_devices, ++ NULL, // rescan ++ NULL, // removed ++}; ++ ++module_info* modules[] = { ++ (module_info*)&sVirtioBlockDriver, ++ (module_info*)&sVirtioBlockDevice, ++ NULL ++}; +-- +2.30.2 + diff --git a/patchset-hrev55144/0062-libroot-exit-thread-by-syscall-when-finished.patch b/patchset-hrev55144/0062-libroot-exit-thread-by-syscall-when-finished.patch new file mode 100644 index 0000000..661edaa --- /dev/null +++ b/patchset-hrev55144/0062-libroot-exit-thread-by-syscall-when-finished.patch @@ -0,0 +1,26 @@ +From 9ece0ce14d03f8d84bd11c5e0ca32d354f75ef67 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Wed, 26 May 2021 12:53:19 +0900 +Subject: libroot: exit thread by syscall when finished + +This reverts commit 51d414dddc9221816efc0a9d5dd988f08e927cbb. +--- + src/system/libroot/os/thread.c | 2 ++ + 1 file changed, 2 insertions(+) + +diff --git a/src/system/libroot/os/thread.c b/src/system/libroot/os/thread.c +index c278e660f1..2bb71d357a 100644 +--- a/src/system/libroot/os/thread.c ++++ b/src/system/libroot/os/thread.c +@@ -45,6 +45,8 @@ thread_entry(void* _entry, void* _thread) + + _thread_do_exit_work(); + __heap_thread_exit(); ++ ++ _kern_exit_thread(returnCode); + + return returnCode; + } +-- +2.30.2 + diff --git a/patchset-hrev55144/0063-Support-Kit-fix-crash-in-JobQueue.patch b/patchset-hrev55144/0063-Support-Kit-fix-crash-in-JobQueue.patch new file mode 100644 index 0000000..bbb49e6 --- /dev/null +++ b/patchset-hrev55144/0063-Support-Kit-fix-crash-in-JobQueue.patch @@ -0,0 +1,25 @@ +From 1406ce3dc68c5720834562a5494016afc58048a0 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Wed, 26 May 2021 12:55:05 +0900 +Subject: Support Kit: fix crash in JobQueue + +This reverts commit d3beab52d1a93d87d243f65ac9c00a9f897b88db. +--- + src/kits/support/JobQueue.cpp | 1 - + 1 file changed, 1 deletion(-) + +diff --git a/src/kits/support/JobQueue.cpp b/src/kits/support/JobQueue.cpp +index 13e48ce124..fec5b26add 100644 +--- a/src/kits/support/JobQueue.cpp ++++ b/src/kits/support/JobQueue.cpp +@@ -283,7 +283,6 @@ JobQueue::_RemoveDependantJobsOf(BJob* job) + _RemoveDependantJobsOf(dependantJob); + dependantJob->RemoveDependency(job); + // TODO: we need some sort of ownership management +- delete dependantJob; + } + } + +-- +2.30.2 + diff --git a/patchset-hrev55144/0064-BeBuild-add-ALWAYS_INLINE-macros.patch b/patchset-hrev55144/0064-BeBuild-add-ALWAYS_INLINE-macros.patch new file mode 100644 index 0000000..0b2e4e9 --- /dev/null +++ b/patchset-hrev55144/0064-BeBuild-add-ALWAYS_INLINE-macros.patch @@ -0,0 +1,26 @@ +From 24995522f03358ea8eeee3c2d35b3ec0266a18db Mon Sep 17 00:00:00 2001 +From: X512 +Date: Wed, 26 May 2021 22:16:22 +0900 +Subject: BeBuild: add ALWAYS_INLINE macros + +Change-Id: Ifc059d5fedd15a5aeda1514312fbbf98a72d3128 +--- + headers/os/BeBuild.h | 2 ++ + 1 file changed, 2 insertions(+) + +diff --git a/headers/os/BeBuild.h b/headers/os/BeBuild.h +index 77f577e670..5a54f99d4d 100644 +--- a/headers/os/BeBuild.h ++++ b/headers/os/BeBuild.h +@@ -88,6 +88,8 @@ + #endif + #define _IMPORT + ++#define B_ALWAYS_INLINE __attribute__((always_inline)) inline ++ + #define B_DEFINE_SYMBOL_VERSION(function, versionedSymbol) \ + __asm__(".symver " function "," versionedSymbol) + +-- +2.30.2 + diff --git a/patchset-hrev55144/0065-Terminal-avoid-using-exceptions.patch b/patchset-hrev55144/0065-Terminal-avoid-using-exceptions.patch new file mode 100644 index 0000000..258d13b --- /dev/null +++ b/patchset-hrev55144/0065-Terminal-avoid-using-exceptions.patch @@ -0,0 +1,158 @@ +From f98a889dbf589d125f0fd937f0d625490a6567fa Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sat, 29 May 2021 12:59:18 +0900 +Subject: Terminal: avoid using exceptions + +Exceptions currently not working on riscv64. + +Change-Id: If3d8128179777e5313e043319d5ad445fe281534 +--- + src/apps/terminal/TermParse.cpp | 36 +++++++++++++++++++-------------- + src/apps/terminal/TermParse.h | 2 +- + 2 files changed, 22 insertions(+), 16 deletions(-) + +diff --git a/src/apps/terminal/TermParse.cpp b/src/apps/terminal/TermParse.cpp +index d925ade1fc..0e46c7206a 100644 +--- a/src/apps/terminal/TermParse.cpp ++++ b/src/apps/terminal/TermParse.cpp +@@ -57,21 +57,22 @@ extern const char* gLineDrawGraphSet[]; /* may be used for G0, G1, G2, G3 */ + + + //! Get char from pty reader buffer. +-inline uchar +-TermParse::_NextParseChar() ++inline status_t ++TermParse::_NextParseChar(uchar& ch) + { + if (fParserBufferOffset >= fParserBufferSize) { + // parser buffer empty + status_t error = _ReadParserBuffer(); + if (error != B_OK) +- throw error; ++ return error; + } + + #ifdef USE_DEBUG_SNAPSHOTS + fBuffer->CaptureChar(fParserBuffer[fParserBufferOffset]); + #endif + +- return fParserBuffer[fParserBufferOffset++]; ++ ch = fParserBuffer[fParserBufferOffset++]; ++ return B_OK; + } + + +@@ -360,6 +361,9 @@ TermParse::_GuessGroundTable(int encoding) + } + + ++#define CheckSkip(res) {status_t _res = res; if (_res < B_OK) goto failed;} ++ ++ + int32 + TermParse::EscParse() + { +@@ -391,8 +395,9 @@ TermParse::EscParse() + BAutolock locker(fBuffer); + + while (!fQuitting) { +- try { +- uchar c = _NextParseChar(); ++ { ++ uchar c = 0; ++ CheckSkip(_NextParseChar(c)); + + //DumpState(groundtable, parsestate, c); + +@@ -433,7 +438,7 @@ TermParse::EscParse() + case B_JIS_CONVERSION: + case B_BIG5_CONVERSION: + cbuf[srcLen++] = c; +- c = _NextParseChar(); ++ CheckSkip(_NextParseChar(c)); + cbuf[srcLen++] = c; + break; + +@@ -441,7 +446,7 @@ TermParse::EscParse() + cbuf[srcLen++] = c; + do { + // GBK-compatible codepoints are 2-bytes long +- c = _NextParseChar(); ++ CheckSkip(_NextParseChar(c)); + cbuf[srcLen++] = c; + + // GB18030 extends GBK with 4-byte codepoints +@@ -495,7 +500,7 @@ TermParse::EscParse() + + case CASE_SJIS_INSTRING: + cbuf[srcLen++] = c; +- c = _NextParseChar(); ++ CheckSkip(_NextParseChar(c)); + cbuf[srcLen++] = c; + + convert_to_utf8(currentEncoding, cbuf, &srcLen, +@@ -505,7 +510,7 @@ TermParse::EscParse() + + case CASE_UTF8_2BYTE: + cbuf[srcLen++] = c; +- c = _NextParseChar(); ++ CheckSkip(_NextParseChar(c)); + if (groundtable[c] != CASE_UTF8_INSTRING) + break; + cbuf[srcLen++] = c; +@@ -517,7 +522,7 @@ TermParse::EscParse() + cbuf[srcLen++] = c; + + do { +- c = _NextParseChar(); ++ CheckSkip(_NextParseChar(c)); + if (groundtable[c] != CASE_UTF8_INSTRING) { + srcLen = 0; + break; +@@ -554,7 +559,8 @@ TermParse::EscParse() + } + + if (set > -1) { +- char page = _NextParseChar(); ++ uchar page = 0; ++ CheckSkip(_NextParseChar(page)); + switch (page) { + case '0': + graphSets[set] = gLineDrawGraphSet; +@@ -1063,7 +1069,7 @@ TermParse::EscParse() + bool isParsed = false; + int32 skipCount = 0; // take care about UTF-8 characters + for (uint i = 0; !isParsed && i < sizeof(params); i++) { +- params[i] = _NextParseChar(); ++ CheckSkip(_NextParseChar(params[i])); + + if (skipCount > 0) { + skipCount--; +@@ -1228,9 +1234,9 @@ TermParse::EscParse() + default: + break; + } +- } catch (...) { +- break; + } ++ failed: ++ ; + } + + return B_OK; +diff --git a/src/apps/terminal/TermParse.h b/src/apps/terminal/TermParse.h +index 26e57ecc78..a7a870b7ab 100644 +--- a/src/apps/terminal/TermParse.h ++++ b/src/apps/terminal/TermParse.h +@@ -38,7 +38,7 @@ public: + status_t StopThreads(); + + private: +- inline uchar _NextParseChar(); ++ inline status_t _NextParseChar(uchar& ch); + + // Initialize TermParse and PtyReader thread. + status_t _InitTermParse(); +-- +2.30.2 + diff --git a/patchset-hrev55144/0066-build_cross_tools-add-enable-initfini-array-flag.patch b/patchset-hrev55144/0066-build_cross_tools-add-enable-initfini-array-flag.patch new file mode 100644 index 0000000..9e24e4e --- /dev/null +++ b/patchset-hrev55144/0066-build_cross_tools-add-enable-initfini-array-flag.patch @@ -0,0 +1,25 @@ +From 6caf063a404ab6be3fa8e2b025a81acf741615dd Mon Sep 17 00:00:00 2001 +From: X512 +Date: Tue, 1 Jun 2021 07:26:40 +0900 +Subject: build_cross_tools: add `--enable-initfini-array` flag + +Change-Id: I455a52b314967f1a0a06c3e143e02d4ac888316c +--- + build/scripts/build_cross_tools_gcc4 | 1 + + 1 file changed, 1 insertion(+) + +diff --git a/build/scripts/build_cross_tools_gcc4 b/build/scripts/build_cross_tools_gcc4 +index 55bee36d50..2368c93db1 100755 +--- a/build/scripts/build_cross_tools_gcc4 ++++ b/build/scripts/build_cross_tools_gcc4 +@@ -242,6 +242,7 @@ CFLAGS="$ccFlags" CXXFLAGS="$cxxFlags" "$gccSourceDir/configure" \ + --disable-maintainer-mode \ + --disable-libgomp \ + --disable-libatomic \ ++ --enable-initfini-array \ + $gccConfigureArgs \ + || exit 1 + +-- +2.30.2 + diff --git a/patchset-hrev55144/0067-Revert-Terminal-avoid-using-exceptions.patch b/patchset-hrev55144/0067-Revert-Terminal-avoid-using-exceptions.patch new file mode 100644 index 0000000..c9bc78b --- /dev/null +++ b/patchset-hrev55144/0067-Revert-Terminal-avoid-using-exceptions.patch @@ -0,0 +1,156 @@ +From 006e5d5d554833c1fe9fe94ffe249152c71a4287 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Wed, 2 Jun 2021 14:07:40 +0900 +Subject: Revert "Terminal: avoid using exceptions" + +This reverts commit 7773a4a7c8f6b5b9447f72b20cd2db715e31b6eb. +--- + src/apps/terminal/TermParse.cpp | 36 ++++++++++++++------------------- + src/apps/terminal/TermParse.h | 2 +- + 2 files changed, 16 insertions(+), 22 deletions(-) + +diff --git a/src/apps/terminal/TermParse.cpp b/src/apps/terminal/TermParse.cpp +index 0e46c7206a..d925ade1fc 100644 +--- a/src/apps/terminal/TermParse.cpp ++++ b/src/apps/terminal/TermParse.cpp +@@ -57,22 +57,21 @@ extern const char* gLineDrawGraphSet[]; /* may be used for G0, G1, G2, G3 */ + + + //! Get char from pty reader buffer. +-inline status_t +-TermParse::_NextParseChar(uchar& ch) ++inline uchar ++TermParse::_NextParseChar() + { + if (fParserBufferOffset >= fParserBufferSize) { + // parser buffer empty + status_t error = _ReadParserBuffer(); + if (error != B_OK) +- return error; ++ throw error; + } + + #ifdef USE_DEBUG_SNAPSHOTS + fBuffer->CaptureChar(fParserBuffer[fParserBufferOffset]); + #endif + +- ch = fParserBuffer[fParserBufferOffset++]; +- return B_OK; ++ return fParserBuffer[fParserBufferOffset++]; + } + + +@@ -361,9 +360,6 @@ TermParse::_GuessGroundTable(int encoding) + } + + +-#define CheckSkip(res) {status_t _res = res; if (_res < B_OK) goto failed;} +- +- + int32 + TermParse::EscParse() + { +@@ -395,9 +391,8 @@ TermParse::EscParse() + BAutolock locker(fBuffer); + + while (!fQuitting) { +- { +- uchar c = 0; +- CheckSkip(_NextParseChar(c)); ++ try { ++ uchar c = _NextParseChar(); + + //DumpState(groundtable, parsestate, c); + +@@ -438,7 +433,7 @@ TermParse::EscParse() + case B_JIS_CONVERSION: + case B_BIG5_CONVERSION: + cbuf[srcLen++] = c; +- CheckSkip(_NextParseChar(c)); ++ c = _NextParseChar(); + cbuf[srcLen++] = c; + break; + +@@ -446,7 +441,7 @@ TermParse::EscParse() + cbuf[srcLen++] = c; + do { + // GBK-compatible codepoints are 2-bytes long +- CheckSkip(_NextParseChar(c)); ++ c = _NextParseChar(); + cbuf[srcLen++] = c; + + // GB18030 extends GBK with 4-byte codepoints +@@ -500,7 +495,7 @@ TermParse::EscParse() + + case CASE_SJIS_INSTRING: + cbuf[srcLen++] = c; +- CheckSkip(_NextParseChar(c)); ++ c = _NextParseChar(); + cbuf[srcLen++] = c; + + convert_to_utf8(currentEncoding, cbuf, &srcLen, +@@ -510,7 +505,7 @@ TermParse::EscParse() + + case CASE_UTF8_2BYTE: + cbuf[srcLen++] = c; +- CheckSkip(_NextParseChar(c)); ++ c = _NextParseChar(); + if (groundtable[c] != CASE_UTF8_INSTRING) + break; + cbuf[srcLen++] = c; +@@ -522,7 +517,7 @@ TermParse::EscParse() + cbuf[srcLen++] = c; + + do { +- CheckSkip(_NextParseChar(c)); ++ c = _NextParseChar(); + if (groundtable[c] != CASE_UTF8_INSTRING) { + srcLen = 0; + break; +@@ -559,8 +554,7 @@ TermParse::EscParse() + } + + if (set > -1) { +- uchar page = 0; +- CheckSkip(_NextParseChar(page)); ++ char page = _NextParseChar(); + switch (page) { + case '0': + graphSets[set] = gLineDrawGraphSet; +@@ -1069,7 +1063,7 @@ TermParse::EscParse() + bool isParsed = false; + int32 skipCount = 0; // take care about UTF-8 characters + for (uint i = 0; !isParsed && i < sizeof(params); i++) { +- CheckSkip(_NextParseChar(params[i])); ++ params[i] = _NextParseChar(); + + if (skipCount > 0) { + skipCount--; +@@ -1234,9 +1228,9 @@ TermParse::EscParse() + default: + break; + } ++ } catch (...) { ++ break; + } +- failed: +- ; + } + + return B_OK; +diff --git a/src/apps/terminal/TermParse.h b/src/apps/terminal/TermParse.h +index a7a870b7ab..26e57ecc78 100644 +--- a/src/apps/terminal/TermParse.h ++++ b/src/apps/terminal/TermParse.h +@@ -38,7 +38,7 @@ public: + status_t StopThreads(); + + private: +- inline status_t _NextParseChar(uchar& ch); ++ inline uchar _NextParseChar(); + + // Initialize TermParse and PtyReader thread. + status_t _InitTermParse(); +-- +2.30.2 + diff --git a/patchset-hrev55144/0068-Terminal-launch-links-directly-without-system.patch b/patchset-hrev55144/0068-Terminal-launch-links-directly-without-system.patch new file mode 100644 index 0000000..f7aeb6f --- /dev/null +++ b/patchset-hrev55144/0068-Terminal-launch-links-directly-without-system.patch @@ -0,0 +1,44 @@ +From 99d25eab0fb59c0d83c1485062d3580ef5b5fb22 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 21:05:50 +0900 +Subject: Terminal: launch links directly without system() + +Change-Id: Ie99304128c7704ffc1b30ecd3139b247da2c993e +--- + src/apps/terminal/HyperLink.cpp | 15 ++++++++++----- + 1 file changed, 10 insertions(+), 5 deletions(-) + +diff --git a/src/apps/terminal/HyperLink.cpp b/src/apps/terminal/HyperLink.cpp +index e3eab2843a..ea4ea10be6 100644 +--- a/src/apps/terminal/HyperLink.cpp ++++ b/src/apps/terminal/HyperLink.cpp +@@ -9,6 +9,8 @@ + #include + #include + ++#include ++ + #include "TermConst.h" + + +@@ -45,9 +47,12 @@ HyperLink::Open() + return B_BAD_VALUE; + + // open with the "open" program +- BString address(fAddress); +- address.CharacterEscape(kShellEscapeCharacters, '\\'); +- BString commandLine; +- commandLine.SetToFormat("/bin/open %s", address.String()); +- return system(commandLine) == 0 ? B_OK : errno; ++ BEntry entry("/bin/open"); ++ entry_ref ref; ++ status_t res = entry.GetRef(&ref); ++ if (res < B_OK) ++ return res; ++ ++ const char *argv[] = {fAddress, NULL}; ++ return be_roster->Launch(&ref, 1, argv); + } +-- +2.30.2 + diff --git a/patchset-hrev55144/0069-libroot-riscv64-define-syscall-function-size-impleme.patch b/patchset-hrev55144/0069-libroot-riscv64-define-syscall-function-size-impleme.patch new file mode 100644 index 0000000..5f5244d --- /dev/null +++ b/patchset-hrev55144/0069-libroot-riscv64-define-syscall-function-size-impleme.patch @@ -0,0 +1,45 @@ +From 45a2d248628554ef78e53c0b305185e79182a90b Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 21:09:19 +0900 +Subject: libroot/riscv64: define syscall function size, implement time + +Change-Id: Ib08b0b700506e3e1eb41d1b30b025bdf688342d9 +--- + src/system/libroot/os/arch/riscv64/syscalls.inc | 3 ++- + src/system/libroot/os/arch/riscv64/time.cpp | 5 ++++- + 2 files changed, 6 insertions(+), 2 deletions(-) + +diff --git a/src/system/libroot/os/arch/riscv64/syscalls.inc b/src/system/libroot/os/arch/riscv64/syscalls.inc +index 76bee643a3..bcebdae486 100644 +--- a/src/system/libroot/os/arch/riscv64/syscalls.inc ++++ b/src/system/libroot/os/arch/riscv64/syscalls.inc +@@ -10,7 +10,8 @@ + name: \ + li t0, n; \ + ecall; \ +- ret ++ ret; \ ++.size name, .-name + + #define SYSCALL0(name, n) _SYSCALL(name, n) + #define SYSCALL1(name, n) _SYSCALL(name, n) +diff --git a/src/system/libroot/os/arch/riscv64/time.cpp b/src/system/libroot/os/arch/riscv64/time.cpp +index 236080fc79..d898887325 100644 +--- a/src/system/libroot/os/arch/riscv64/time.cpp ++++ b/src/system/libroot/os/arch/riscv64/time.cpp +@@ -25,8 +25,11 @@ __arch_init_time(struct real_time_data *data, bool setDefaults) + } + + ++ ++ + bigtime_t + __arch_get_system_time_offset(struct real_time_data *data) + { +- return 0; ++ //we don't use atomic_get64 because memory is read-only, maybe find another way to lock ++ return data->arch_data.system_time_offset; + } +-- +2.30.2 + diff --git a/patchset-hrev55144/0070-kernel-arch_real_time_clock-implement-for-riscv64.patch b/patchset-hrev55144/0070-kernel-arch_real_time_clock-implement-for-riscv64.patch new file mode 100644 index 0000000..a86262a --- /dev/null +++ b/patchset-hrev55144/0070-kernel-arch_real_time_clock-implement-for-riscv64.patch @@ -0,0 +1,56 @@ +From 48bb059417b5d991c4e5e78375809f398b1c7dfa Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 21:10:47 +0900 +Subject: kernel/arch_real_time_clock: implement for riscv64 + +Change-Id: I3a50b3343e00ef45ef9391d463939abba9e666a0 +--- + .../kernel/arch/riscv64/arch_real_time_clock.cpp | 10 ++++++++-- + 1 file changed, 8 insertions(+), 2 deletions(-) + +diff --git a/src/system/kernel/arch/riscv64/arch_real_time_clock.cpp b/src/system/kernel/arch/riscv64/arch_real_time_clock.cpp +index 937b58d595..c4bc17be48 100644 +--- a/src/system/kernel/arch/riscv64/arch_real_time_clock.cpp ++++ b/src/system/kernel/arch/riscv64/arch_real_time_clock.cpp +@@ -3,10 +3,15 @@ + #include + #include + ++#include ++ + + status_t + arch_rtc_init(kernel_args *args, struct real_time_data *data) + { ++ bigtime_t systemTime = system_time(); ++ uint64 rtcTime = HtifCmd(2, 0, 0); ++ data->arch_data.system_time_conversion_factor = rtcTime - systemTime; + return B_OK; + } + +@@ -14,7 +19,7 @@ arch_rtc_init(kernel_args *args, struct real_time_data *data) + uint32 + arch_rtc_get_hw_time(void) + { +- return 0; ++ return (uint32)(HtifCmd(2, 0, 0) / 1000000); + } + + +@@ -27,11 +32,12 @@ arch_rtc_set_hw_time(uint32 seconds) + void + arch_rtc_set_system_time_offset(struct real_time_data *data, bigtime_t offset) + { ++ atomic_set64(&data->arch_data.system_time_offset, offset); + } + + + bigtime_t + arch_rtc_get_system_time_offset(struct real_time_data *data) + { +- return 0; ++ return atomic_get64(&data->arch_data.system_time_offset); + } +-- +2.30.2 + diff --git a/patchset-hrev55144/0071-HaikuPortsCross-riscv64-update-GCC-package.patch b/patchset-hrev55144/0071-HaikuPortsCross-riscv64-update-GCC-package.patch new file mode 100644 index 0000000..ba623cf --- /dev/null +++ b/patchset-hrev55144/0071-HaikuPortsCross-riscv64-update-GCC-package.patch @@ -0,0 +1,30 @@ +From a92789f75a352a84993b3b478e75804dec805fb6 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 21:16:25 +0900 +Subject: HaikuPortsCross/riscv64: update GCC package + +Change-Id: Ifb2158822df63121397ccbe7dadaba44594832d2 +--- + build/jam/repositories/HaikuPortsCross/riscv64 | 6 +++--- + 1 file changed, 3 insertions(+), 3 deletions(-) + +diff --git a/build/jam/repositories/HaikuPortsCross/riscv64 b/build/jam/repositories/HaikuPortsCross/riscv64 +index 01e28a0aab..a42635622c 100644 +--- a/build/jam/repositories/HaikuPortsCross/riscv64 ++++ b/build/jam/repositories/HaikuPortsCross/riscv64 +@@ -6,9 +6,9 @@ BootstrapPackageRepository HaikuPortsCross + noto-20170202-7 + : + # repository architecture packages (stage 0) +- gcc_bootstrap-8.3.0_2019_05_24-4 +- gcc_bootstrap_syslibs-8.3.0_2019_05_24-4 +- gcc_bootstrap_syslibs_devel-8.3.0_2019_05_24-4 ++ gcc_bootstrap-8.3.0_2021_02_27-1 ++ gcc_bootstrap_syslibs-8.3.0_2021_02_27-1 ++ gcc_bootstrap_syslibs_devel-8.3.0_2021_02_27-1 + : + # repository architecture packages (stage 1) + bash_bootstrap-4.4.023-1 +-- +2.30.2 + diff --git a/patchset-hrev55144/0072-ldscripts-riscv64-adjust-after-adding-enable-initfin.patch b/patchset-hrev55144/0072-ldscripts-riscv64-adjust-after-adding-enable-initfin.patch new file mode 100644 index 0000000..ebc454c --- /dev/null +++ b/patchset-hrev55144/0072-ldscripts-riscv64-adjust-after-adding-enable-initfin.patch @@ -0,0 +1,50 @@ +From 8ddb44924c6107ded3a025aa1701066b0b72b1a1 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 21:18:31 +0900 +Subject: ldscripts/riscv64: adjust after adding `--enable-initfini-array` flag + +Change-Id: Icd5b944901c483100808d6624ca742bd04b869bc +--- + src/system/ldscripts/riscv64/boot_loader_riscv.ld | 5 ++++- + src/system/ldscripts/riscv64/runtime_loader.ld | 8 +++++--- + 2 files changed, 9 insertions(+), 4 deletions(-) + +diff --git a/src/system/ldscripts/riscv64/boot_loader_riscv.ld b/src/system/ldscripts/riscv64/boot_loader_riscv.ld +index 716c3a54d0..ee50e2c4a8 100644 +--- a/src/system/ldscripts/riscv64/boot_loader_riscv.ld ++++ b/src/system/ldscripts/riscv64/boot_loader_riscv.ld +@@ -16,8 +16,11 @@ SECTIONS + + . = ALIGN(0x8); + __ctor_list = .; +- .ctors : { *(.ctors) } ++ .init_array : { *(.init_array) } + __ctor_end = .; ++ __dtor_list = .; ++ .fini_array : { *(.fini_array) } ++ __dtor_end = .; + + .rodata : { *(.rodata .rodata.*) } + +diff --git a/src/system/ldscripts/riscv64/runtime_loader.ld b/src/system/ldscripts/riscv64/runtime_loader.ld +index 1f5b386262..888c082e5f 100644 +--- a/src/system/ldscripts/riscv64/runtime_loader.ld ++++ b/src/system/ldscripts/riscv64/runtime_loader.ld +@@ -46,9 +46,11 @@ SECTIONS + .data : { *(.data .gnu.linkonce.d.*) } + + __ctor_list = .; +- PROVIDE (_ctor_list = .); +- .ctors : { *(.ctors) } +- PROVIDE (__ctor_end = .); ++ .init_array : { *(.init_array) } ++ __ctor_end = .; ++ __dtor_list = .; ++ .fini_array : { *(.fini_array) } ++ __dtor_end = .; + + + /* uninitialized data (in same segment as writable data) */ +-- +2.30.2 + diff --git a/patchset-hrev55144/0073-virtio_net-fix-for-TinyEMU.patch b/patchset-hrev55144/0073-virtio_net-fix-for-TinyEMU.patch new file mode 100644 index 0000000..4a5d3a6 --- /dev/null +++ b/patchset-hrev55144/0073-virtio_net-fix-for-TinyEMU.patch @@ -0,0 +1,33 @@ +From 8c05183c2a022060937ccdb179361792e580f014 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 21:20:04 +0900 +Subject: virtio_net: fix for TinyEMU + +Change-Id: I777f8ea7506794d24c8c44e2c7b2e73f26e2627d +--- + src/add-ons/kernel/drivers/network/virtio/virtio_net.h | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/src/add-ons/kernel/drivers/network/virtio/virtio_net.h b/src/add-ons/kernel/drivers/network/virtio/virtio_net.h +index a7f8f70abe..dee49e1d16 100644 +--- a/src/add-ons/kernel/drivers/network/virtio/virtio_net.h ++++ b/src/add-ons/kernel/drivers/network/virtio/virtio_net.h +@@ -88,6 +88,7 @@ struct virtio_net_hdr { + uint16_t gso_size; /* Bytes to append to hdr_len per frame */ + uint16_t csum_start; /* Position to start checksumming from */ + uint16_t csum_offset; /* Offset after that to place checksum */ ++ uint16_t num_buffers; /* Number of merged rx buffers */ + }; + + /* +@@ -96,7 +97,6 @@ struct virtio_net_hdr { + */ + struct virtio_net_hdr_mrg_rxbuf { + struct virtio_net_hdr hdr; +- uint16_t num_buffers; /* Number of merged rx buffers */ + }; + + /* +-- +2.30.2 + diff --git a/patchset-hrev55144/0074-debug_server-improve-stack-trace.patch b/patchset-hrev55144/0074-debug_server-improve-stack-trace.patch new file mode 100644 index 0000000..c43f6c5 --- /dev/null +++ b/patchset-hrev55144/0074-debug_server-improve-stack-trace.patch @@ -0,0 +1,42 @@ +From cc81531c3e47c49159a0e9ee77c6e2ffd0509038 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 21:20:55 +0900 +Subject: debug_server: improve stack trace + +Change-Id: I94fc9e9e547f0191484cad8e7dc6e8b233b981db +--- + src/servers/debug/DebugServer.cpp | 6 +++--- + 1 file changed, 3 insertions(+), 3 deletions(-) + +diff --git a/src/servers/debug/DebugServer.cpp b/src/servers/debug/DebugServer.cpp +index b54b0a29be..286ee4c005 100644 +--- a/src/servers/debug/DebugServer.cpp ++++ b/src/servers/debug/DebugServer.cpp +@@ -913,13 +913,13 @@ TeamDebugHandler::_LookupSymbolAddress( + // we were able to look something up + if (strlen(symbolName) > 0) { + // we even got a symbol +- snprintf(buffer, bufferSize, "%s + %#lx%s", symbolName, ++ snprintf(buffer, bufferSize, "<%s> %s + %#lx%s", imageName, symbolName, + (addr_t)address - (addr_t)baseAddress, + (exactMatch ? "" : " (closest symbol)")); + + } else { + // no symbol: image relative address +- snprintf(buffer, bufferSize, "(%s + %#lx)", imageName, ++ snprintf(buffer, bufferSize, "<%s> %#lx", imageName, + (addr_t)address - (addr_t)baseAddress); + } + +@@ -979,7 +979,7 @@ TeamDebugHandler::_PrintStackTrace(thread_id thread) + break; + + // lookup the return address +- _LookupSymbolAddress(lookupContext, stackFrameInfo.return_address, ++ _LookupSymbolAddress(lookupContext, (uint8*)stackFrameInfo.return_address - 1, + symbolBuffer, sizeof(symbolBuffer) - 1); + + debug_printf(" (%p) %p %s\n", stackFrameInfo.frame, +-- +2.30.2 + diff --git a/patchset-hrev55144/0075-package_daemon-add-debug-output.patch b/patchset-hrev55144/0075-package_daemon-add-debug-output.patch new file mode 100644 index 0000000..7244de1 --- /dev/null +++ b/patchset-hrev55144/0075-package_daemon-add-debug-output.patch @@ -0,0 +1,69 @@ +From fa962a69c687013b67313f996508192b0b306775 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 6 Jun 2021 21:21:22 +0900 +Subject: package_daemon: add debug output + +Change-Id: Ica830f291d375ccd960976d1a926cca1f0d2c9ec +--- + .../package/CommitTransactionHandler.cpp | 19 ++++++++++++++++--- + 1 file changed, 16 insertions(+), 3 deletions(-) + +diff --git a/src/servers/package/CommitTransactionHandler.cpp b/src/servers/package/CommitTransactionHandler.cpp +index 1cbfbe117f..1623c86f6e 100644 +--- a/src/servers/package/CommitTransactionHandler.cpp ++++ b/src/servers/package/CommitTransactionHandler.cpp +@@ -885,8 +885,10 @@ CommitTransactionHandler::_AddGlobalWritableFile(Package* package, + if (targetPath == "settings" + || targetPath.StartsWith("settings/")) { + targetPath.Insert("/global", 8); +- if (targetPath.Length() == file.Path().Length()) ++ if (targetPath.Length() == file.Path().Length()) { ++ debug_printf("(1)\n"); + throw std::bad_alloc(); ++ } + } + } + +@@ -898,12 +900,20 @@ CommitTransactionHandler::_AddGlobalWritableFile(Package* package, + sourceDirectory = &stackSourceDirectory; + BString sourceParentPath(file.Path(), + lastSlash - file.Path().String()); +- if (sourceParentPath.Length() == 0) ++ if (sourceParentPath.Length() == 0) { ++ debug_printf("(2)\n"); + throw std::bad_alloc(); ++ } + + status_t error = stackSourceDirectory.SetTo( + &extractedFilesDirectory, sourceParentPath); + if (error != B_OK) { ++ debug_printf("(3)\n"); ++ debug_printf(" path1: \"%s\"\n", _GetPath( ++ FSUtils::Entry(extractedFilesDirectory, sourceParentPath), ++ sourceParentPath).String()); ++ debug_printf(" package name: \"%s\"\n", package->FileName().String()); ++ debug_printf(" error: 0x%" B_PRIx32 "(%s)\n", error, strerror(error)); + throw Exception(B_TRANSACTION_FAILED_TO_OPEN_DIRECTORY) + .SetPath1(_GetPath( + FSUtils::Entry(extractedFilesDirectory, sourceParentPath), +@@ -921,13 +931,16 @@ CommitTransactionHandler::_AddGlobalWritableFile(Package* package, + if (lastSlash != NULL) { + BString targetParentPath(targetPath, + lastSlash - targetPath.String()); +- if (targetParentPath.Length() == 0) ++ if (targetParentPath.Length() == 0) { ++ debug_printf("(4)\n"); + throw std::bad_alloc(); ++ } + + BDirectory targetDirectory; + status_t error = FSUtils::OpenSubDirectory(rootDirectory, + RelativePath(targetParentPath), true, targetDirectory); + if (error != B_OK) { ++ debug_printf("(5)\n"); + throw Exception(B_TRANSACTION_FAILED_TO_OPEN_DIRECTORY) + .SetPath1(_GetPath( + FSUtils::Entry(rootDirectory, targetParentPath), +-- +2.30.2 + diff --git a/patchset-hrev55144/0076-haiku_loader-add-J-K-keys-support-for-up-down-keys.patch b/patchset-hrev55144/0076-haiku_loader-add-J-K-keys-support-for-up-down-keys.patch new file mode 100644 index 0000000..075ab58 --- /dev/null +++ b/patchset-hrev55144/0076-haiku_loader-add-J-K-keys-support-for-up-down-keys.patch @@ -0,0 +1,43 @@ +From ba198f635b9ccf48587fe30bd760ce6234c62084 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 13 Jun 2021 02:11:22 +0900 +Subject: haiku_loader: add J, K keys support for up/down keys + +Arrow keys are not available on some platforms. + +Change-Id: Ia38797eb12202668a0b0976b31f21f564d140901 +--- + src/system/boot/platform/generic/text_menu.cpp | 7 ++++++- + 1 file changed, 6 insertions(+), 1 deletion(-) + +diff --git a/src/system/boot/platform/generic/text_menu.cpp b/src/system/boot/platform/generic/text_menu.cpp +index 611268ce88..5826688ecb 100644 +--- a/src/system/boot/platform/generic/text_menu.cpp ++++ b/src/system/boot/platform/generic/text_menu.cpp +@@ -412,7 +412,8 @@ run_menu(Menu* menu) + + item = menu->ItemAt(selected); + +- if (TEXT_CONSOLE_IS_CURSOR_KEY(key)) { ++ if (TEXT_CONSOLE_IS_CURSOR_KEY(key) || key == 'j' || key == 'J' ++ || key == 'k' || key == 'K') { + if (item == NULL) + continue; + +@@ -420,9 +421,13 @@ run_menu(Menu* menu) + + switch (key) { + case TEXT_CONSOLE_KEY_UP: ++ case 'k': ++ case 'K': + selected = select_previous_valid_item(menu, selected - 1); + break; + case TEXT_CONSOLE_KEY_DOWN: ++ case 'j': ++ case 'J': + selected = select_next_valid_item(menu, selected + 1); + break; + case TEXT_CONSOLE_KEY_PAGE_UP: +-- +2.30.2 + diff --git a/patchset-hrev55144/0077-app_server-turn-on-screen-on-start.patch b/patchset-hrev55144/0077-app_server-turn-on-screen-on-start.patch new file mode 100644 index 0000000..f8c1ccd --- /dev/null +++ b/patchset-hrev55144/0077-app_server-turn-on-screen-on-start.patch @@ -0,0 +1,39 @@ +From a36beca8671899012fa9d1cc81fbbbbd655dbff9 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Tue, 22 Jun 2021 01:39:10 +0900 +Subject: app_server: turn on screen on start + +Screen may be turned off if video card is not supported by firmware and boot +loader. + +Change-Id: Ie60fc00da281ec3781084dd97466a68b885fde7b +--- + src/servers/app/VirtualScreen.cpp | 5 +++++ + 1 file changed, 5 insertions(+) + +diff --git a/src/servers/app/VirtualScreen.cpp b/src/servers/app/VirtualScreen.cpp +index 94a9e1e1f2..92745ef561 100644 +--- a/src/servers/app/VirtualScreen.cpp ++++ b/src/servers/app/VirtualScreen.cpp +@@ -136,6 +136,10 @@ VirtualScreen::AddScreen(Screen* screen, ScreenConfigurations& configurations) + } + } + ++ // Turn on screen if this is not yet done by BIOS ++ if (status == B_OK) ++ screen->HWInterface()->SetDPMSMode(B_DPMS_ON); ++ + // TODO: this works only for single screen configurations + fDrawingEngine = screen->GetDrawingEngine(); + fHWInterface = screen->HWInterface(); +@@ -144,6 +148,7 @@ VirtualScreen::AddScreen(Screen* screen, ScreenConfigurations& configurations) + + fScreenList.AddItem(item); + ++ + return B_OK; + } + +-- +2.30.2 + diff --git a/patchset-hrev55144/0078-ati.accelerant-64-bit-fixes.patch b/patchset-hrev55144/0078-ati.accelerant-64-bit-fixes.patch new file mode 100644 index 0000000..1ef8c5f --- /dev/null +++ b/patchset-hrev55144/0078-ati.accelerant-64-bit-fixes.patch @@ -0,0 +1,65 @@ +From 280795e35e0261a3c9ebd14178f7b12a00c15226 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Tue, 22 Jun 2021 01:47:09 +0900 +Subject: ati.accelerant: 64 bit fixes + +Change-Id: I0f82dfe7bc73122546d262ab7e94010f1adff500 +--- + src/add-ons/accelerants/ati/mach64_overlay.cpp | 4 ++-- + src/add-ons/accelerants/ati/overlay.cpp | 4 ++-- + src/add-ons/accelerants/ati/rage128_overlay.cpp | 2 +- + 3 files changed, 5 insertions(+), 5 deletions(-) + +diff --git a/src/add-ons/accelerants/ati/mach64_overlay.cpp b/src/add-ons/accelerants/ati/mach64_overlay.cpp +index dedbaacf01..b9a856ae83 100644 +--- a/src/add-ons/accelerants/ati/mach64_overlay.cpp ++++ b/src/add-ons/accelerants/ati/mach64_overlay.cpp +@@ -122,8 +122,8 @@ Mach64_DisplayOverlay(const overlay_window* window, + OUTREG(VIDEO_FORMAT, videoFormat); + + // Compute offset of overlay buffer in the video memory. +- uint32 offset = uint32(buffer->buffer) - si.videoMemAddr; +- ++ uint32 offset = (uint32)((addr_t)buffer->buffer - si.videoMemAddr); ++ + if (si.chipType < MACH64_264VTB) { + OUTREG(BUF0_OFFSET, offset); + OUTREG(BUF0_PITCH, buffer->width); +diff --git a/src/add-ons/accelerants/ati/overlay.cpp b/src/add-ons/accelerants/ati/overlay.cpp +index 4d45e1d6e3..6094d03fd1 100644 +--- a/src/add-ons/accelerants/ati/overlay.cpp ++++ b/src/add-ons/accelerants/ati/overlay.cpp +@@ -264,7 +264,7 @@ ReleaseOverlay(overlay_token overlayToken) + { + SharedInfo& si = *gInfo.sharedInfo; + +- if (overlayToken != (overlay_token)si.overlayToken) { ++ if (overlayToken != (overlay_token)(addr_t)si.overlayToken) { + TRACE("ReleaseOverlay() error - no overlay previously allocated\n"); + return B_BAD_VALUE; + } +@@ -285,7 +285,7 @@ ConfigureOverlay(overlay_token overlayToken, const overlay_buffer* buffer, + { + SharedInfo& si = *gInfo.sharedInfo; + +- if (overlayToken != (overlay_token)si.overlayToken) ++ if (overlayToken != (overlay_token)(addr_t)si.overlayToken) + return B_BAD_VALUE; + + if (buffer == NULL) +diff --git a/src/add-ons/accelerants/ati/rage128_overlay.cpp b/src/add-ons/accelerants/ati/rage128_overlay.cpp +index 727fa961fb..d59f50cf11 100644 +--- a/src/add-ons/accelerants/ati/rage128_overlay.cpp ++++ b/src/add-ons/accelerants/ati/rage128_overlay.cpp +@@ -131,7 +131,7 @@ Rage128_DisplayOverlay(const overlay_window* window, + int32 p1_v_accum_init = ((tmp << 4) & 0x03ff8000) | 0x00000001; + + // Compute offset of overlay buffer in the video memory. +- uint32 offset = uint32(buffer->buffer) - si.videoMemAddr; ++ uint32 offset = (uint32)((addr_t)buffer->buffer - si.videoMemAddr); + + OUTREG(R128_OV0_REG_LOAD_CNTL, 1); + while (!(INREG(R128_OV0_REG_LOAD_CNTL) & (1 << 3))) +-- +2.30.2 + diff --git a/patchset-hrev55144/0079-ati-fix-for-64-bits-and-non-x86-architectures-SMAP-f.patch b/patchset-hrev55144/0079-ati-fix-for-64-bits-and-non-x86-architectures-SMAP-f.patch new file mode 100644 index 0000000..67ae24a --- /dev/null +++ b/patchset-hrev55144/0079-ati-fix-for-64-bits-and-non-x86-architectures-SMAP-f.patch @@ -0,0 +1,233 @@ +From 8a81f0f32ad647b28c113a568beaefeb59519287 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Tue, 22 Jun 2021 02:58:58 +0900 +Subject: ati: fix for 64 bits and non-x86 architectures, SMAP fixes + +ATI graphics driver is useful for QEMU option `-device ati-vga`. + +Change-Id: Ia932d07d23b16cd9e2eefe65821a38a87427c416 +--- + .../kernel/drivers/graphics/ati/driver.cpp | 90 ++++++++++++++----- + 1 file changed, 67 insertions(+), 23 deletions(-) + +diff --git a/src/add-ons/kernel/drivers/graphics/ati/driver.cpp b/src/add-ons/kernel/drivers/graphics/ati/driver.cpp +index 27f02f4cb9..6c6d41ec5e 100644 +--- a/src/add-ons/kernel/drivers/graphics/ati/driver.cpp ++++ b/src/add-ons/kernel/drivers/graphics/ati/driver.cpp +@@ -20,6 +20,7 @@ + + #undef TRACE + ++#define ENABLE_DEBUG_TRACE + #ifdef ENABLE_DEBUG_TRACE + # define TRACE(x...) dprintf("ati: " x) + #else +@@ -418,14 +419,19 @@ Mach64_GetBiosParameters(DeviceInfo& di, uint8& clockType) + + uint8* romAddr; + area_id romArea = map_physical_memory("ATI Mach64 ROM", ++#if defined(__x86__) || defined(__x86_64__) + 0x000c0000, ++#else ++ di.pciInfo.u.h0.rom_base, ++#endif + M64_BIOS_SIZE, + B_ANY_KERNEL_ADDRESS, +- B_READ_AREA, ++ B_KERNEL_READ_AREA, + (void**)&(romAddr)); + + if (romArea < 0) { +- TRACE("Mach64_GetBiosParameters(), ROM mapping error: %ld\n", romArea); ++ TRACE("Mach64_GetBiosParameters(), ROM mapping error: %" B_PRId32 "\n", ++ romArea); + return romArea; // ROM mapping failed; return error code + } + +@@ -497,14 +503,19 @@ Rage128_GetBiosParameters(DeviceInfo& di) + + uint8* romAddr; + area_id romArea = map_physical_memory("ATI Rage128 ROM", ++#if defined(__x86__) || defined(__x86_64__) + 0x000c0000, ++#else ++ di.pciInfo.u.h0.rom_base, ++#endif + R128_BIOS_SIZE, + B_ANY_KERNEL_ADDRESS, +- B_READ_AREA, ++ B_KERNEL_READ_AREA, + (void**)&(romAddr)); + + if (romArea < 0) { +- TRACE("Rage128_GetBiosParameters(), ROM mapping error: %ld\n", romArea); ++ TRACE("Rage128_GetBiosParameters(), ROM mapping error: %" B_PRId32 ++ "\n", romArea); + return romArea; // ROM mapping failed; return error code + } + +@@ -527,7 +538,8 @@ Rage128_GetBiosParameters(DeviceInfo& di) + pll.max_pll_freq = BIOS32(pllInfoBlock + 0x16); + pll.xclk = BIOS16(pllInfoBlock + 0x08); + +- TRACE("PLL parameters: rf=%d rd=%d min=%ld max=%ld; xclk=%d\n", ++ TRACE("PLL parameters: rf=%d rd=%d min=%" B_PRId32 " max=%" B_PRId32 ++ "; xclk=%d\n", + pll.reference_freq, pll.reference_div, pll.min_pll_freq, + pll.max_pll_freq, pll.xclk); + +@@ -588,6 +600,13 @@ MapDevice(DeviceInfo& di) + SetPCI(pciInfo, PCI_command, 2, GetPCI(pciInfo, PCI_command, 2) + | PCI_command_io | PCI_command_memory | PCI_command_master); + ++ // Enable ROM decoding ++ ++ if (di.pciInfo.u.h0.rom_size > 0) { ++ SetPCI(pciInfo, PCI_rom_base, 4, ++ GetPCI(pciInfo, PCI_rom_base, 4) | 0x00000001); ++ } ++ + // Map the video memory. + + phys_addr_t videoRamAddr = pciInfo.u.h0.base_registers[0]; +@@ -627,7 +646,7 @@ MapDevice(DeviceInfo& di) + + if (MACH64_FAMILY(si.chipType) && (regsBase == 0 || regAreaSize == 0)) { + uint32 regsOffset = 0x7ff000; // offset to regs area in video memory +- uint32 regs = uint32(si.videoMemAddr) + regsOffset; ++ addr_t regs = addr_t(si.videoMemAddr) + regsOffset; + uint32 chipInfo = *((vuint32*)(regs + M64_CONFIG_CHIP_ID)); + + if (si.deviceID != (chipInfo & M64_CFG_CHIP_TYPE)) { +@@ -643,8 +662,8 @@ MapDevice(DeviceInfo& di) + + regsBase = videoRamAddr + regsOffset; + regAreaSize = 0x1000; +- TRACE("Register address is at end of frame buffer memory at 0x%lx\n", +- uint32(regsBase)); ++ TRACE("Register address is at end of frame buffer memory at 0x%" ++ B_PRIxPHYSADDR "\n", regsBase); + } + + si.regsArea = map_physical_memory("ATI mmio registers", +@@ -969,7 +988,7 @@ init_driver(void) + + gDeviceNames[count] = NULL; // terminate list with null pointer + +- TRACE("init_driver() %ld supported devices\n", count); ++ TRACE("init_driver() %" B_PRIu32 " supported devices\n", count); + + return B_OK; + } +@@ -1040,7 +1059,7 @@ device_open(const char* name, uint32 /*flags*/, void** cookie) + *cookie = &di; // send cookie to opener + } + +- TRACE("device_open() returning 0x%lx, open count: %ld\n", status, ++ TRACE("device_open() returning 0x%" B_PRIx32 ", open count: %" B_PRIu32 "\n", status, + di.openCount); + return status; + } +@@ -1122,7 +1141,7 @@ device_free(void* dev) + + gLock.Release(); // unlock driver + +- TRACE("exit device_free() openCount: %ld\n", di.openCount); ++ TRACE("exit device_free() openCount: %" B_PRIu32 "\n", di.openCount); + return B_OK; + } + +@@ -1132,25 +1151,35 @@ device_ioctl(void* dev, uint32 msg, void* buffer, size_t bufferLength) + { + DeviceInfo& di = *((DeviceInfo*)dev); + +-// TRACE("device_ioctl(); ioctl: %lu, buffer: 0x%08lx, bufLen: %lu\n", msg, +-// (uint32)buffer, bufferLength); ++ TRACE("device_ioctl(); ioctl: %" B_PRIu32 ", buffer: %#08" B_PRIxADDR ++ ", bufLen: %" B_PRIuSIZE "\n", msg, (addr_t)buffer, bufferLength); + + switch (msg) { + case B_GET_ACCELERANT_SIGNATURE: +- strcpy((char*)buffer, ATI_ACCELERANT_NAME); ++ { ++ status_t status = user_strlcpy((char*)buffer, ATI_ACCELERANT_NAME, ++ bufferLength); ++ if (status < B_OK) ++ return status; ++ + return B_OK; ++ } + + case ATI_DEVICE_NAME: +- strncpy((char*)buffer, di.name, B_OS_NAME_LENGTH); +- ((char*)buffer)[B_OS_NAME_LENGTH -1] = '\0'; ++ { ++ status_t status = user_strlcpy((char*)buffer, di.name, ++ B_OS_NAME_LENGTH); ++ if (status < B_OK) ++ return status; ++ + return B_OK; ++ } + + case ATI_GET_SHARED_DATA: + if (bufferLength != sizeof(area_id)) + return B_BAD_DATA; + +- *((area_id*)buffer) = di.sharedArea; +- return B_OK; ++ return user_memcpy(buffer, &di.sharedArea, sizeof(area_id)); + + case ATI_GET_EDID: + { +@@ -1159,27 +1188,42 @@ device_ioctl(void* dev, uint32 msg, void* buffer, size_t bufferLength) + + edid1_raw rawEdid; + status_t status = GetEdidFromBIOS(rawEdid); +- if (status == B_OK) +- user_memcpy((edid1_raw*)buffer, &rawEdid, sizeof(rawEdid)); +- return status; ++ if (status != B_OK) ++ return status; ++ ++ return user_memcpy((edid1_raw*)buffer, &rawEdid, sizeof(rawEdid)); + } + + case ATI_SET_VESA_DISPLAY_MODE: ++ { + if (bufferLength != sizeof(uint16)) + return B_BAD_DATA; + +- return SetVesaDisplayMode(*((uint16*)buffer)); ++ uint16 value; ++ status_t status = user_memcpy(&value, buffer, sizeof(uint16)); ++ if (status < B_OK) ++ return status; ++ ++ return SetVesaDisplayMode(value); ++ } + + case ATI_RUN_INTERRUPTS: ++ { + if (bufferLength != sizeof(bool)) + return B_BAD_DATA; + +- if (*((bool*)buffer)) ++ bool value; ++ status_t res = user_memcpy(&value, buffer, sizeof(bool)); ++ if (res < B_OK) ++ return res; ++ ++ if (value) + EnableVBI(); + else + DisableVBI(); + + return B_OK; ++ } + } + + return B_DEV_INVALID_IOCTL; +-- +2.30.2 + diff --git a/patchset-hrev55144/0080-ahci-remove-packed-attribute-from-register-structure.patch b/patchset-hrev55144/0080-ahci-remove-packed-attribute-from-register-structure.patch new file mode 100644 index 0000000..eb3da7c --- /dev/null +++ b/patchset-hrev55144/0080-ahci-remove-packed-attribute-from-register-structure.patch @@ -0,0 +1,30 @@ +From 74a6bbf4dc822f9a1ce27da140a7eac7e0211523 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Tue, 22 Jun 2021 12:30:15 +0900 +Subject: ahci: remove packed attribute from register structure + +It cause per-byte access instead of 32 bit on GCC/riscv64 that breaks operation. + +All fields are 32 bit so alignment is already fine and packing is not needed. + +Change-Id: Ie96eac6615c9326e84608be1c667bc5d3600c508 +--- + src/add-ons/kernel/busses/scsi/ahci/ahci_defs.h | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/src/add-ons/kernel/busses/scsi/ahci/ahci_defs.h b/src/add-ons/kernel/busses/scsi/ahci/ahci_defs.h +index 578defa00b..b016dab232 100644 +--- a/src/add-ons/kernel/busses/scsi/ahci/ahci_defs.h ++++ b/src/add-ons/kernel/busses/scsi/ahci/ahci_defs.h +@@ -129,7 +129,7 @@ typedef struct { + uint32 devslp; // Device Sleep + uint32 res[10]; // Reserved + uint32 vendor[4]; // Vendor Specific +-} _PACKED ahci_port; ++} ahci_port; + + + enum { +-- +2.30.2 + diff --git a/patchset-hrev55144/0081-riscv64-add-SBI-syscall-interface.patch b/patchset-hrev55144/0081-riscv64-add-SBI-syscall-interface.patch new file mode 100644 index 0000000..9f6cead --- /dev/null +++ b/patchset-hrev55144/0081-riscv64-add-SBI-syscall-interface.patch @@ -0,0 +1,234 @@ +From 224bc758cf1bea6aa914faaafa06eb730b3f3f52 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Wed, 23 Jun 2021 15:04:36 +0900 +Subject: riscv64: add SBI syscall interface + +Change-Id: Ifab2a65fdad1de807e2334ec94137b992d6fe19d +--- + .../kernel/platform/sbi/sbi_syscalls.h | 132 ++++++++++++++++++ + src/system/kernel/arch/riscv64/Jamfile | 1 + + src/system/kernel/arch/riscv64/sbi_syscalls.S | 61 ++++++++ + 3 files changed, 194 insertions(+) + create mode 100644 headers/private/kernel/platform/sbi/sbi_syscalls.h + create mode 100644 src/system/kernel/arch/riscv64/sbi_syscalls.S + +diff --git a/headers/private/kernel/platform/sbi/sbi_syscalls.h b/headers/private/kernel/platform/sbi/sbi_syscalls.h +new file mode 100644 +index 0000000000..2d32de19d7 +--- /dev/null ++++ b/headers/private/kernel/platform/sbi/sbi_syscalls.h +@@ -0,0 +1,132 @@ ++/* ++ * Copyright 2021, Haiku, Inc. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++#ifndef _SBI_SYSCALLS_H_ ++#define _SBI_SYSCALLS_H_ ++ ++ ++#include ++ ++ ++enum { ++ SBI_SUCCESS = 0, ++ SBI_ERR_FAILED = -1, ++ SBI_ERR_NOT_SUPPORTED = -2, ++ SBI_ERR_INVALID_PARAM = -3, ++ SBI_ERR_DENIED = -4, ++ SBI_ERR_INVALID_ADDRESS = -5, ++ SBI_ERR_ALREADY_AVAILABLE = -6, ++}; ++ ++struct sbiret { ++ long error; // a0 ++ long value; // a1 ++}; ++ ++enum { ++ SBI_HART_STATE_STARTED = 0, ++ SBI_HART_STATE_STOPPED = 1, ++ SBI_HART_STATE_START_PENDING = 2, ++ SBI_HART_STATE_STOP_PENDING = 3, ++ SBI_HART_STATE_SUSPENDED = 4, ++ SBI_HART_STATE_SUSPEND_PENDING = 5, ++ SBI_HART_STATE_RESUME_PENDING = 6, ++}; ++ ++// a7: EID, a6: FID ++ ++extern "C" { ++ ++// Base Extension (EID #0x10) ++struct sbiret sbi_get_spec_version(void); // FID #0 ++struct sbiret sbi_get_impl_id(void); // FID #1 ++struct sbiret sbi_get_impl_version(void); // FID #2 ++struct sbiret sbi_probe_extension(long extension_id); // FID #3 ++struct sbiret sbi_get_mvendorid(void); // FID #4 ++struct sbiret sbi_get_marchid(void); // FID #5 ++struct sbiret sbi_get_mimpid(void); // FID #6 ++ ++// Legacy Extensions (EIDs #0x00 - #0x0F) ++void sbi_set_timer_legacy(uint64_t stime_value); // EID #0x00 ++void sbi_console_putchar_legacy(int ch); // EID #0x01 ++int sbi_console_getchar_legacy(void); // EID #0x02 ++void sbi_clear_ipi_legacy(void); // EID #0x03 ++void sbi_send_ipi_legacy(const unsigned long *hart_mask); // EID #0x04 ++void sbi_remote_fence_i_legacy(const unsigned long *hart_mask); // EID #0x05 ++void sbi_remote_sfence_vma_legacy( // EID #0x06 ++ const unsigned long *hart_mask, ++ unsigned long start, ++ unsigned long size); ++void sbi_remote_sfence_vma_asid_legacy( // EID #0x07 ++ const unsigned long *hart_mask, ++ unsigned long start, ++ unsigned long size, ++ unsigned long asid); ++void sbi_shutdown_legacy(void); // EID #0x08 ++ ++// Timer Extension (EID #0x54494D45 "TIME") ++struct sbiret sbi_set_timer(uint64_t stime_value); // FID #0 ++ ++// IPI Extension (EID #0x735049 "sPI: s-mode IPI") ++struct sbiret sbi_send_ipi( // FID #0 ++ unsigned long hart_mask, ++ unsigned long hart_mask_base); ++ ++// RFENCE Extension (EID #0x52464E43 "RFNC") ++struct sbiret sbi_remote_fence_i( // FID #0 ++ unsigned long hart_mask, ++ unsigned long hart_mask_base); ++struct sbiret sbi_remote_sfence_vma( // FID #1 ++ unsigned long hart_mask, ++ unsigned long hart_mask_base, ++ unsigned long start_addr, ++ unsigned long size); ++struct sbiret sbi_remote_sfence_vma_asid( // FID #2 ++ unsigned long hart_mask, ++ unsigned long hart_mask_base, ++ unsigned long start_addr, ++ unsigned long size, ++ unsigned long asid); ++struct sbiret sbi_remote_hfence_gvma_vmid( // FID #3 ++ unsigned long hart_mask, ++ unsigned long hart_mask_base, ++ unsigned long start_addr, ++ unsigned long size, ++ unsigned long vmid); ++struct sbiret sbi_remote_hfence_gvma( // FID #4 ++ unsigned long hart_mask, ++ unsigned long hart_mask_base, ++ unsigned long start_addr, ++ unsigned long size); ++struct sbiret sbi_remote_hfence_vvma_asid( // FID #5 ++ unsigned long hart_mask, ++ unsigned long hart_mask_base, ++ unsigned long start_addr, ++ unsigned long size, ++ unsigned long asid); ++struct sbiret sbi_remote_hfence_vvma( // FID #6 ++ unsigned long hart_mask, ++ unsigned long hart_mask_base, ++ unsigned long start_addr, ++ unsigned long size); ++ ++// Hart State Management Extension (EID #0x48534D "HSM") ++struct sbiret sbi_hart_start( // FID #0 ++ unsigned long hartid, ++ unsigned long start_addr, ++ unsigned long opaque); ++struct sbiret sbi_hart_stop(void); // FID #1 ++struct sbiret sbi_hart_get_status(unsigned long hartid); // FID #2 ++struct sbiret sbi_hart_suspend( // FID #3 ++ uint32_t suspend_type, ++ unsigned long resume_addr, ++ unsigned long opaque); ++ ++// System Reset Extension (EID #0x53525354 "SRST") ++struct sbiret sbi_system_reset(uint32_t reset_type, uint32_t reset_reason); // FID #0 ++ ++} ++ ++#endif // _SBI_SYSCALLS_H_ +diff --git a/src/system/kernel/arch/riscv64/Jamfile b/src/system/kernel/arch/riscv64/Jamfile +index de684e5081..1a6b74b5dd 100644 +--- a/src/system/kernel/arch/riscv64/Jamfile ++++ b/src/system/kernel/arch/riscv64/Jamfile +@@ -23,6 +23,7 @@ KernelMergeObject kernel_arch_riscv64.o : + arch_vm_translation_map.cpp + RISCV64VMTranslationMap.cpp + Htif.cpp ++ sbi_syscalls.S + : + $(TARGET_KERNEL_PIC_CCFLAGS) -Wno-unused + : +diff --git a/src/system/kernel/arch/riscv64/sbi_syscalls.S b/src/system/kernel/arch/riscv64/sbi_syscalls.S +new file mode 100644 +index 0000000000..d85ec90366 +--- /dev/null ++++ b/src/system/kernel/arch/riscv64/sbi_syscalls.S +@@ -0,0 +1,61 @@ ++/* ++ * Copyright 2021, Haiku, Inc. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++#define SBI_SYSCALL(name, eid, fid) \ ++.globl name; \ ++.type name,%function; \ ++name: \ ++ li a7, eid; \ ++ li a6, fid; \ ++ ecall; \ ++ ret; \ ++.size name, .-name ++ ++#define SBI_SYSCALL_LEGACY(name, eid) \ ++.globl name; \ ++.type name,%function; \ ++name: \ ++ li a7, eid; \ ++ ecall; \ ++ ret; \ ++.size name, .-name ++ ++ ++SBI_SYSCALL(sbi_get_spec_version, 0x10, 0) ++SBI_SYSCALL(sbi_get_impl_id, 0x10, 1) ++SBI_SYSCALL(sbi_get_impl_version, 0x10, 2) ++SBI_SYSCALL(sbi_probe_extension, 0x10, 3) ++SBI_SYSCALL(sbi_get_mvendorid, 0x10, 4) ++SBI_SYSCALL(sbi_get_marchid, 0x10, 5) ++SBI_SYSCALL(sbi_get_mimpid, 0x10, 6) ++ ++SBI_SYSCALL_LEGACY(sbi_set_timer_legacy, 0) ++SBI_SYSCALL_LEGACY(sbi_console_putchar_legacy, 1) ++SBI_SYSCALL_LEGACY(sbi_console_getchar_legacy, 2) ++SBI_SYSCALL_LEGACY(sbi_clear_ipi_legacy, 3) ++SBI_SYSCALL_LEGACY(sbi_send_ipi_legacy, 4) ++SBI_SYSCALL_LEGACY(sbi_remote_fence_i_legacy, 5) ++SBI_SYSCALL_LEGACY(sbi_remote_sfence_vma_legacy, 6) ++SBI_SYSCALL_LEGACY(sbi_remote_sfence_vma_asid_legacy, 7) ++SBI_SYSCALL_LEGACY(sbi_shutdown_legacy, 8) ++ ++SBI_SYSCALL(sbi_set_timer, 0x54494D45, 0) ++ ++SBI_SYSCALL(sbi_send_ipi, 0x735049, 0) ++ ++SBI_SYSCALL(sbi_remote_fence_i, 0x52464E43, 0) ++SBI_SYSCALL(sbi_remote_sfence_vma, 0x52464E43, 1) ++SBI_SYSCALL(sbi_remote_sfence_vma_asid, 0x52464E43, 2) ++SBI_SYSCALL(sbi_remote_hfence_gvma_vmid, 0x52464E43, 3) ++SBI_SYSCALL(sbi_remote_hfence_gvma, 0x52464E43, 4) ++SBI_SYSCALL(sbi_remote_hfence_vvma_asid, 0x52464E43, 5) ++SBI_SYSCALL(sbi_remote_hfence_vvma, 0x52464E43, 6) ++ ++SBI_SYSCALL(sbi_hart_start, 0x48534D, 0) ++SBI_SYSCALL(sbi_hart_stop, 0x48534D, 1) ++SBI_SYSCALL(sbi_hart_get_status, 0x48534D, 2) ++SBI_SYSCALL(sbi_hart_suspend, 0x48534D, 3) ++ ++SBI_SYSCALL(sbi_system_reset, 0x53525354, 0) +-- +2.30.2 + diff --git a/patchset-hrev55144/0082-ati.accelerant-fix-mode-setting.patch b/patchset-hrev55144/0082-ati.accelerant-fix-mode-setting.patch new file mode 100644 index 0000000..f38b9b9 --- /dev/null +++ b/patchset-hrev55144/0082-ati.accelerant-fix-mode-setting.patch @@ -0,0 +1,52 @@ +From 1f2956a87cf765ff0ad3b52fb5cdae5009bd0e98 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Sun, 27 Jun 2021 05:06:10 +0900 +Subject: ati.accelerant: fix mode setting + +Change-Id: I000a646bad46e372a4d65306c4ab419212887721 +--- + src/add-ons/accelerants/ati/mode.cpp | 22 +++++++++++++++++++++- + 1 file changed, 21 insertions(+), 1 deletion(-) + +diff --git a/src/add-ons/accelerants/ati/mode.cpp b/src/add-ons/accelerants/ati/mode.cpp +index dd101165d0..f0515f4cc6 100644 +--- a/src/add-ons/accelerants/ati/mode.cpp ++++ b/src/add-ons/accelerants/ati/mode.cpp +@@ -298,13 +298,33 @@ SetDisplayMode(display_mode* pMode) + (mode.timing.flags & B_POSITIVE_HSYNC) ? '+' : '-', + (mode.timing.flags & B_POSITIVE_VSYNC) ? '+' : '-'); + } +- ++ ++ // QEMU need to reenable screen to apply new mode change. ++ struct ScopeExit { ++ uint32 oldDpms; ++ ++ ScopeExit() ++ { ++ oldDpms = gInfo.GetDPMSMode(); ++ gInfo.SetDPMSMode(B_DPMS_OFF); ++ } ++ ++ ~ScopeExit() ++ { ++ gInfo.SetDPMSMode(oldDpms); ++ } ++ } scopeExit; ++ + status_t status = gInfo.SetDisplayMode(mode); + if (status != B_OK) { + TRACE("SetDisplayMode() failed; status 0x%x\n", status); + return status; + } + ++ // Clear framebuffer to avoid artifacts on mode change. ++ memset((void*)((addr_t)si.videoMemAddr + si.frameBufferOffset), 0, ++ mode.virtual_width * mode.virtual_height * bytesPerPixel); ++ + si.displayMode = mode; + + TRACE("SetDisplayMode() done\n"); +-- +2.30.2 + diff --git a/patchset-hrev55144/0083-haiku_loader.riscv-update.patch b/patchset-hrev55144/0083-haiku_loader.riscv-update.patch new file mode 100644 index 0000000..44245fc --- /dev/null +++ b/patchset-hrev55144/0083-haiku_loader.riscv-update.patch @@ -0,0 +1,1512 @@ +From aa0572dbeaabcf3e7288d3d694eab22a09b92ca8 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 00:45:30 +0900 +Subject: haiku_loader.riscv: update + +* Moved machine mode code from kernel. + +* Added MMU page table generation. + +* Added QEMU ramfb video driver. + +Change-Id: Icd67cd2e8dbf2b568d81ab8dd0d6127ca3cd97a8 +--- + src/system/boot/platform/riscv/FwCfg.cpp | 148 +++++++++ + src/system/boot/platform/riscv/FwCfg.h | 86 +++++ + src/system/boot/platform/riscv/Jamfile | 3 + + src/system/boot/platform/riscv/cpu.cpp | 8 +- + src/system/boot/platform/riscv/entry.S | 24 +- + src/system/boot/platform/riscv/fdt.cpp | 125 ++++++-- + src/system/boot/platform/riscv/mmu.cpp | 355 +++++++++++++++++++-- + src/system/boot/platform/riscv/mmu.h | 26 +- + src/system/boot/platform/riscv/smp.cpp | 7 + + src/system/boot/platform/riscv/smp.h | 40 +++ + src/system/boot/platform/riscv/start.cpp | 80 ++++- + src/system/boot/platform/riscv/traps.cpp | 164 ++++++++++ + src/system/boot/platform/riscv/traps.h | 8 + + src/system/boot/platform/riscv/traps_asm.S | 57 ++++ + src/system/boot/platform/riscv/video.cpp | 4 +- + src/system/boot/platform/riscv/virtio.cpp | 13 +- + 16 files changed, 1077 insertions(+), 71 deletions(-) + create mode 100644 src/system/boot/platform/riscv/FwCfg.cpp + create mode 100644 src/system/boot/platform/riscv/FwCfg.h + create mode 100644 src/system/boot/platform/riscv/smp.cpp + create mode 100644 src/system/boot/platform/riscv/smp.h + create mode 100644 src/system/boot/platform/riscv/traps.cpp + create mode 100644 src/system/boot/platform/riscv/traps.h + create mode 100644 src/system/boot/platform/riscv/traps_asm.S + +diff --git a/src/system/boot/platform/riscv/FwCfg.cpp b/src/system/boot/platform/riscv/FwCfg.cpp +new file mode 100644 +index 0000000000..07c62bc645 +--- /dev/null ++++ b/src/system/boot/platform/riscv/FwCfg.cpp +@@ -0,0 +1,148 @@ ++#include "FwCfg.h" ++ ++#include ++#include ++#include ++ ++#include ++#include ++ ++#include "graphics.h" ++ ++ ++FwCfgRegs *volatile gFwCfgRegs = NULL; ++ ++ ++#define _B(n) ((unsigned long long)((uint8_t *)&x)[n]) ++static inline uint16_t SwapEndian16(uint16_t x) ++{ ++ return (_B(0) << 8) | _B(1); ++} ++ ++static inline uint32_t SwapEndian32(uint32_t x) ++{ ++ return (_B(0) << 24) | (_B(1) << 16) | (_B(2) << 8) | _B(3); ++} ++ ++static inline uint64_t SwapEndian64(uint64_t x) ++{ ++ return (_B(0) << 56) | (_B(1) << 48) | (_B(2) << 40) | (_B(3) << 32) ++ | (_B(4) << 24) | (_B(5) << 16) | (_B(6) << 8) | _B(7); ++} ++#undef _B ++ ++ ++namespace FwCfg { ++ ++void Select(uint16_t selector) ++{ ++ // GCC, why are you so crazy? ++ // gFwCfgRegs->selector = SwapEndian16(selector); ++ *(uint16*)0x10100008 = SwapEndian16(selector); ++} ++ ++void DmaOp(uint8_t *bytes, size_t count, uint32_t op) ++{ ++ __attribute__ ((aligned (8))) FwCfgDmaAccess volatile dma; ++ dma.control = SwapEndian32(1 << op); ++ dma.length = SwapEndian32(count); ++ dma.address = SwapEndian64((addr_t)bytes); ++ // gFwCfgRegs->dmaAdr = SwapEndian64((addr_t)&dma); ++ *(uint64*)0x10100010 = SwapEndian64((addr_t)&dma); ++ while (uint32_t control = SwapEndian32(dma.control) != 0) { ++ if (((1 << fwCfgDmaFlagsError) & control) != 0) ++ abort(); ++ } ++} ++ ++void ReadBytes(uint8_t *bytes, size_t count) ++{ ++ DmaOp(bytes, count, fwCfgDmaFlagsRead); ++} ++ ++void WriteBytes(uint8_t *bytes, size_t count) ++{ ++ DmaOp(bytes, count, fwCfgDmaFlagsWrite); ++} ++ ++uint8_t Read8 () {uint8_t val; ReadBytes( &val, sizeof(val)); return val;} ++uint16_t Read16() {uint16_t val; ReadBytes((uint8_t*)&val, sizeof(val)); return val;} ++uint32_t Read32() {uint32_t val; ReadBytes((uint8_t*)&val, sizeof(val)); return val;} ++uint64_t Read64() {uint64_t val; ReadBytes((uint8_t*)&val, sizeof(val)); return val;} ++ ++ ++void ListDir() ++{ ++ uint32_t count = SwapEndian32(Read32()); ++ dprintf("count: %" B_PRIu32 "\n", count); ++ for (uint32_t i = 0; i < count; i++) { ++ FwCfgFile file; ++ ReadBytes((uint8_t*)&file, sizeof(file)); ++ file.size = SwapEndian32(file.size); ++ file.select = SwapEndian16(file.select); ++ file.reserved = SwapEndian16(file.reserved); ++ dprintf("\n"); ++ dprintf("size: %" B_PRIu32 "\n", file.size); ++ dprintf("select: %" B_PRIu32 "\n", file.select); ++ dprintf("reserved: %" B_PRIu32 "\n", file.reserved); ++ dprintf("name: %s\n", file.name); ++ } ++} ++ ++bool ThisFile(FwCfgFile& file, uint16_t dir, const char *name) ++{ ++ Select(dir); ++ uint32_t count = SwapEndian32(Read32()); ++ for (uint32_t i = 0; i < count; i++) { ++ ReadBytes((uint8_t*)&file, sizeof(file)); ++ file.size = SwapEndian32(file.size); ++ file.select = SwapEndian16(file.select); ++ file.reserved = SwapEndian16(file.reserved); ++ if (strcmp(file.name, name) == 0) ++ return true; ++ } ++ return false; ++} ++ ++void InitFramebuffer() ++{ ++ FwCfgFile file; ++ if (!ThisFile(file, fwCfgSelectFileDir, "etc/ramfb")) { ++ dprintf("[!] ramfb not found\n"); ++ return; ++ } ++ dprintf("file.select: %" B_PRIu16 "\n", file.select); ++ ++ RamFbCfg cfg; ++ uint32_t width = 1024, height = 768; ++ ++ gFramebuf.colors = (uint32_t*)malloc(4*width*height); ++ gFramebuf.stride = width; ++ gFramebuf.width = width; ++ gFramebuf.height = height; ++ ++ cfg.addr = SwapEndian64((size_t)gFramebuf.colors); ++ cfg.fourcc = SwapEndian32(ramFbFormatXrgb8888); ++ cfg.flags = SwapEndian32(0); ++ cfg.width = SwapEndian32(width); ++ cfg.height = SwapEndian32(height); ++ cfg.stride = SwapEndian32(4*width); ++ Select(file.select); ++ WriteBytes((uint8_t*)&cfg, sizeof(cfg)); ++} ++ ++void Init() ++{ ++ dprintf("gFwCfgRegs: 0x%08" B_PRIx64 "\n", (addr_t)gFwCfgRegs); ++ if (gFwCfgRegs == NULL) ++ return; ++ Select(fwCfgSelectSignature); ++ dprintf("fwCfgSelectSignature: 0x%08" B_PRIx32 "\n", Read32()); ++ Select(fwCfgSelectId); ++ dprintf("fwCfgSelectId: : 0x%08" B_PRIx32 "\n", Read32()); ++ Select(fwCfgSelectFileDir); ++ ListDir(); ++ InitFramebuffer(); ++} ++ ++}; +diff --git a/src/system/boot/platform/riscv/FwCfg.h b/src/system/boot/platform/riscv/FwCfg.h +new file mode 100644 +index 0000000000..d99c6b52e7 +--- /dev/null ++++ b/src/system/boot/platform/riscv/FwCfg.h +@@ -0,0 +1,86 @@ ++#ifndef _FWCFG_H_ ++#define _FWCFG_H_ ++ ++#include ++#include ++ ++ ++enum { ++ fwCfgSelectSignature = 0x0000, ++ fwCfgSelectId = 0x0001, ++ fwCfgSelectFileDir = 0x0019, ++ fwCfgSelectFileFirst = 0x0020, ++}; ++ ++enum { ++ fwCfgSignature = 0x554D4551, ++ ++ fwCfgIdTraditional = 0, ++ fwCfgIdDma = 1, ++}; ++ ++enum { ++ fwCfgDmaFlagsError = 0, ++ fwCfgDmaFlagsRead = 1, ++ fwCfgDmaFlagsSkip = 2, ++ fwCfgDmaFlagsSelect = 3, ++ fwCfgDmaFlagsWrite = 4, ++}; ++ ++// integer values are big endian ++struct __attribute__((packed)) FwCfgFile { ++ uint32_t size; ++ uint16_t select; ++ uint16_t reserved; ++ char name[56]; // '/0' terminated ++}; ++ ++struct __attribute__((packed)) FwCfgFiles { ++ uint32_t count; ++ FwCfgFile f[]; ++}; ++ ++struct __attribute__((packed)) FwCfgDmaAccess { ++ uint32_t control; ++ uint32_t length; ++ uint64_t address; ++}; ++ ++ ++struct __attribute__((packed)) FwCfgRegs { ++ uint64_t data; ++ uint16_t selector; ++ uint16_t unused1; ++ uint32_t unused2; ++ uint64_t dmaAdr; ++}; ++ ++ ++// ramfb ++ ++enum { ++ ramFbFormatXrgb8888 = ((uint32_t)('X') | ((uint32_t)('R') << 8) | ((uint32_t)('2') << 16) | ((uint32_t)('4') << 24)), ++}; ++ ++// all fields are big endian ++struct __attribute__((packed)) RamFbCfg { ++ uint64_t addr; ++ uint32_t fourcc; ++ uint32_t flags; ++ uint32_t width; ++ uint32_t height; ++ uint32_t stride; ++}; ++ ++ ++extern FwCfgRegs *volatile gFwCfgRegs; ++ ++ ++namespace FwCfg { ++ ++void Init(); ++ ++}; ++ ++ ++#endif // _FWCFG_H_ +diff --git a/src/system/boot/platform/riscv/Jamfile b/src/system/boot/platform/riscv/Jamfile +index f68b501b0f..c1349cfb1b 100644 +--- a/src/system/boot/platform/riscv/Jamfile ++++ b/src/system/boot/platform/riscv/Jamfile +@@ -38,7 +38,10 @@ for platform in [ MultiBootSubDirSetup riscv ] { + graphics.cpp + fixed_font.S + htif.cpp ++ FwCfg.cpp + virtio.cpp ++ traps.cpp ++ traps_asm.S + entry.S + + : : +diff --git a/src/system/boot/platform/riscv/cpu.cpp b/src/system/boot/platform/riscv/cpu.cpp +index af19c5d768..4c41f9fdb2 100644 +--- a/src/system/boot/platform/riscv/cpu.cpp ++++ b/src/system/boot/platform/riscv/cpu.cpp +@@ -35,10 +35,10 @@ cpu_init() + { + gKernelArgs.num_cpus = 1; + +- // enable FPU +- MstatusReg status(Mstatus()); +- status.fs = extStatusInitial; +- SetMstatus(status.val); ++ SstatusReg status(Sstatus()); ++ status.fs = extStatusInitial; // enable FPU ++ status.xs = extStatusOff; ++ SetSstatus(status.val); + } + + +diff --git a/src/system/boot/platform/riscv/entry.S b/src/system/boot/platform/riscv/entry.S +index 185c000ddb..2c1dc948b4 100644 +--- a/src/system/boot/platform/riscv/entry.S ++++ b/src/system/boot/platform/riscv/entry.S +@@ -7,24 +7,30 @@ + + .text + +-/* status_t arch_enter_kernel(struct kernel_args* kernelArgs, ++/* status_t arch_enter_kernel(uint64 satp, struct kernel_args *kernelArgs, + addr_t kernelEntry, addr_t kernelStackTop); + +- a0 - kernelArgs +- a1 - kernelEntry +- a2 - kernelStackTop ++ a0 - SATP register value ++ a1 - kernelArgs ++ a2 - kernelEntry ++ a3 - kernelStackTop + */ + FUNCTION(arch_enter_kernel): ++ csrw satp, a0 ++ sfence.vma ++ + // set the kernel stack +- mv sp,a2 ++ mv sp, a3 ++# li fp, 0 ++# li ra, 0 + + // Setup kernel args +- //mv a0,a0 // kernelArgs +- mv a4,a1 +- li a1,0 // currentCPU=0 ++ mv a0, a1 // kernelArgs ++ mv t0, a2 ++ li a1, 0 // currentCPU=0 + + // call the kernel +- jr a4 ++ jr t0 + + // return + li a0,-1 // B_ERROR +diff --git a/src/system/boot/platform/riscv/fdt.cpp b/src/system/boot/platform/riscv/fdt.cpp +index d7d656a873..80cb0692e9 100644 +--- a/src/system/boot/platform/riscv/fdt.cpp ++++ b/src/system/boot/platform/riscv/fdt.cpp +@@ -17,45 +17,117 @@ extern "C" { + #include "mmu.h" + #include "graphics.h" + #include "virtio.h" ++#include "Htif.h" ++#include "Clint.h" ++#include "FwCfg.h" + + + void* gFdt = NULL; ++ClintRegs *volatile gClintRegs = NULL; ++ ++static uint64 sTimerFrequrency = 10000000; ++ ++static addr_range sPlic = {0}; ++static addr_range sClint = {0}; ++static ArchUart sUart = {.kind = kUartKindNone}; ++ ++ ++static bool ++HasFdtString(const char* prop, int size, const char* pattern) ++{ ++ int patternLen = strlen(pattern); ++ const char* propEnd = prop + size; ++ while (propEnd - prop > 0) { ++ int curLen = strlen(prop); ++ if (curLen == patternLen && memcmp(prop, pattern, curLen + 1) == 0) ++ return true; ++ prop += curLen + 1; ++ } ++ return false; ++} ++ ++ ++static uint32 ++GetInterrupt(const void* fdt, int node) ++{ ++ if (uint32* prop = (uint32*)fdt_getprop(fdt, node, "interrupts-extended", NULL)) { ++ return fdt32_to_cpu(*(prop + 1)); ++ } ++ if (uint32* prop = (uint32*)fdt_getprop(fdt, node, "interrupts", NULL)) { ++ return fdt32_to_cpu(*prop); ++ } ++ dprintf("[!] no interrupt field\n"); ++ return 0; ++} + + + static void +-HandleFdt(const void* fdt, int node, uint32_t addressCells, uint32_t sizeCells, +- uint32_t interruptCells /* from parent node */) ++HandleFdt(const void* fdt, int node, uint32 addressCells, uint32 sizeCells, ++ uint32 interruptCells /* from parent node */) + { + // TODO: handle different field sizes + ++ const char* name = fdt_get_name(fdt, node, NULL); ++ if (strcmp(name, "cpus") == 0) { ++ if (uint32* prop = (uint32*)fdt_getprop(fdt, node, "timebase-frequency", NULL)) ++ sTimerFrequrency = fdt32_to_cpu(*prop); ++ } ++ + const char* device_type = (const char*)fdt_getprop(fdt, node, + "device_type", NULL); + if (device_type != NULL && strcmp(device_type, "memory") == 0) { +- gMemBase = (uint8*)fdt64_to_cpu(*((uint64_t*)fdt_getprop(fdt, node, ++ gMemBase = (uint8*)fdt64_to_cpu(*((uint64*)fdt_getprop(fdt, node, + "reg", NULL) + 0)); +- gTotalMem = fdt64_to_cpu(*((uint64_t*)fdt_getprop(fdt, node, ++ gTotalMem = fdt64_to_cpu(*((uint64*)fdt_getprop(fdt, node, + "reg", NULL) + 1)); + return; + } ++ int compatibleLen; + const char* compatible = (const char*)fdt_getprop(fdt, node, +- "compatible", NULL); ++ "compatible", &compatibleLen); + if (compatible == NULL) return; +- if (strcmp(compatible, "virtio,mmio") == 0) { ++ if (HasFdtString(compatible, compatibleLen, "riscv,clint0")) { ++ uint64* reg = (uint64*)fdt_getprop(fdt, node, "reg", NULL); ++ sClint.start = fdt64_to_cpu(*(reg + 0)); ++ sClint.size = fdt64_to_cpu(*(reg + 1)); ++ gClintRegs = (ClintRegs*)sClint.start; ++ } else if (HasFdtString(compatible, compatibleLen, "riscv,plic0")) { ++ uint64* reg = (uint64*)fdt_getprop(fdt, node, "reg", NULL); ++ sPlic.start = fdt64_to_cpu(*(reg + 0)); ++ sPlic.size = fdt64_to_cpu(*(reg + 1)); ++ } else if (HasFdtString(compatible, compatibleLen, "virtio,mmio")) { ++ uint64* reg = (uint64*)fdt_getprop(fdt, node, "reg", NULL); + virtio_register( +- fdt64_to_cpu(*((uint64_t*)fdt_getprop(fdt, node, "reg", NULL) + 0)), +- fdt64_to_cpu(*((uint64_t*)fdt_getprop(fdt, node, "reg", NULL) + 1)), +- fdt32_to_cpu(*((uint32_t*)fdt_getprop(fdt, node, +- "interrupts-extended", NULL) + 1)) +- ); +- } else if (strcmp(compatible, "simple-framebuffer") == 0) { +- gFramebuf.colors = (uint32_t*)fdt64_to_cpu( +- *(uint64_t*)fdt_getprop(fdt, node, "reg", NULL)); ++ fdt64_to_cpu(*(reg + 0)), fdt64_to_cpu(*(reg + 1)), ++ GetInterrupt(fdt, node)); ++ } else if ( ++ sUart.kind == kUartKindNone && ( ++ HasFdtString(compatible, compatibleLen, "ns16550a") || ++ HasFdtString(compatible, compatibleLen, "sifive,uart0")) ++ ) { ++ if (HasFdtString(compatible, compatibleLen, "ns16550a")) ++ sUart.kind = kUartKind8250; ++ else if (HasFdtString(compatible, compatibleLen, "sifive,uart0")) ++ sUart.kind = kUartKindSifive; ++ ++ uint64* reg = (uint64*)fdt_getprop(fdt, node, "reg", NULL); ++ sUart.regs.start = fdt64_to_cpu(*(reg + 0)); ++ sUart.regs.size = fdt64_to_cpu(*(reg + 1)); ++ sUart.irq = GetInterrupt(fdt, node); ++ const void* prop = fdt_getprop(fdt, node, "clock-frequency", NULL); ++ sUart.clock = (prop == NULL) ? 0 : fdt32_to_cpu(*(uint32*)prop); ++ } else if (HasFdtString(compatible, compatibleLen, "qemu,fw-cfg-mmio")) { ++ gFwCfgRegs = (FwCfgRegs *volatile) ++ fdt64_to_cpu(*(uint64*)fdt_getprop(fdt, node, "reg", NULL)); ++ } else if (HasFdtString(compatible, compatibleLen, "simple-framebuffer")) { ++ gFramebuf.colors = (uint32*)fdt64_to_cpu( ++ *(uint64*)fdt_getprop(fdt, node, "reg", NULL)); + gFramebuf.stride = fdt32_to_cpu( +- *(uint32_t*)fdt_getprop(fdt, node, "stride", NULL)) / 4; ++ *(uint32*)fdt_getprop(fdt, node, "stride", NULL)) / 4; + gFramebuf.width = fdt32_to_cpu( +- *(uint32_t*)fdt_getprop(fdt, node, "width", NULL)); ++ *(uint32*)fdt_getprop(fdt, node, "width", NULL)); + gFramebuf.height = fdt32_to_cpu( +- *(uint32_t*)fdt_getprop(fdt, node, "height", NULL)); ++ *(uint32*)fdt_getprop(fdt, node, "height", NULL)); + } + } + +@@ -74,9 +146,9 @@ fdt_init(void* fdt) + dprintf("FDT valid, size: %" B_PRIu32 "\n", fdt_totalsize(gFdt)); + + int node = -1; +- int depth = 0; +- while ((node = fdt_next_node(gFdt, node, &depth)) >= 0) { +- HandleFdt(gFdt, node, 2, 2, 2); ++ int depth = -1; ++ while ((node = fdt_next_node(gFdt, node, &depth)) >= 0 && depth >= 0) { ++ HandleFdt(gFdt, node, 2, 2, 1); + } + } + +@@ -85,8 +157,17 @@ void + fdt_set_kernel_args() + { + gKernelArgs.arch_args.fdt = kernel_args_malloc(fdt_totalsize(gFdt)); +- if (gKernelArgs.arch_args.fdt != NULL) { ++ if (gKernelArgs.arch_args.fdt != NULL) + memcpy(gKernelArgs.arch_args.fdt, gFdt, fdt_totalsize(gFdt)); +- } else ++ else + panic("unable to malloc for FDT!\n"); ++ ++ gKernelArgs.arch_args.timerFrequrency = 1000000/*sTimerFrequrency*/; ++ ++ gKernelArgs.arch_args.htif.start = (addr_t)gHtifRegs; ++ gKernelArgs.arch_args.htif.size = sizeof(HtifRegs); ++ ++ gKernelArgs.arch_args.plic = sPlic; ++ gKernelArgs.arch_args.clint = sClint; ++ gKernelArgs.arch_args.uart = sUart; + } +diff --git a/src/system/boot/platform/riscv/mmu.cpp b/src/system/boot/platform/riscv/mmu.cpp +index 4a9a95f744..21a6425eb6 100644 +--- a/src/system/boot/platform/riscv/mmu.cpp ++++ b/src/system/boot/platform/riscv/mmu.cpp +@@ -15,31 +15,296 @@ + #include + #include + #include ++#include + + #include + + #include + ++ ++struct MemoryRegion ++{ ++ MemoryRegion* next; ++ addr_t virtAdr; ++ phys_addr_t physAdr; ++ size_t size; ++ uint32 protection; ++}; ++ ++ + extern uint8 gStackEnd; + + uint8* gMemBase = NULL; + size_t gTotalMem = 0; + uint8* gFreeMem = &gStackEnd; ++addr_t gFreeVirtMem = KERNEL_LOAD_BASE_64_BIT; ++ ++MemoryRegion* sRegions = NULL; ++ ++ssize_t gVirtFromPhysOffset = 0; ++phys_addr_t sPageTable = 0; ++ ++ ++static void ++WritePteFlags(uint32 flags) ++{ ++ bool first = true; ++ dprintf("{"); ++ for (uint32 i = 0; i < 32; i++) { ++ if ((1 << i) & flags) { ++ if (first) first = false; else dprintf(", "); ++ switch (i) { ++ case pteValid: dprintf("valid"); break; ++ case pteRead: dprintf("read"); break; ++ case pteWrite: dprintf("write"); break; ++ case pteExec: dprintf("exec"); break; ++ case pteUser: dprintf("user"); break; ++ case pteGlobal: dprintf("global"); break; ++ case pteAccessed: dprintf("accessed"); break; ++ case pteDirty: dprintf("dirty"); break; ++ default: dprintf("%" B_PRIu32, i); ++ } ++ } ++ } ++ dprintf("}"); ++} ++ ++ ++static phys_addr_t ++AllocPhysPages(size_t size) ++{ ++ size = ROUNDUP(size, B_PAGE_SIZE); ++ phys_addr_t adr = ROUNDUP((addr_t)gFreeMem, B_PAGE_SIZE); ++ ++ if (adr + size - (addr_t)gMemBase > gTotalMem) ++ return 0; ++ ++ gFreeMem = (uint8*)(adr + size); ++ ++ return adr; ++} ++ ++ ++static phys_addr_t ++AllocPhysPage() ++{ ++ return AllocPhysPages(B_PAGE_SIZE); ++} ++ ++ ++static void ++FreePhysPages(phys_addr_t physAdr, size_t size) ++{ ++ if (physAdr + size == (phys_addr_t)gFreeMem) ++ gFreeMem -= size; ++} ++ ++ ++static phys_addr_t ++AllocVirtPages(size_t size) ++{ ++ size = ROUNDUP(size, B_PAGE_SIZE); ++ phys_addr_t adr = ROUNDUP(gFreeVirtMem, B_PAGE_SIZE); ++ gFreeVirtMem = adr + size; ++ ++ return adr; ++} ++ ++ ++static void ++FreeVirtPages(addr_t virtAdr, size_t size) ++{ ++ if (virtAdr + size == gFreeVirtMem) ++ gFreeVirtMem -= size; ++} ++ ++ ++static inline void* ++VirtFromPhys(phys_addr_t physAdr) ++{ ++ return (void*)physAdr; ++} ++ ++ ++static inline phys_addr_t ++PhysFromVirt(void* virtAdr) ++{ ++ return (phys_addr_t)virtAdr; ++} ++ ++ ++static Pte* ++LookupPte(addr_t virtAdr, bool alloc) ++{ ++ Pte *pte = (Pte*)VirtFromPhys(sPageTable); ++ for (int level = 2; level > 0; level--) { ++ pte += VirtAdrPte(virtAdr, level); ++ if (!((1 << pteValid) & pte->flags)) { ++ if (!alloc) ++ return NULL; ++ pte->ppn = AllocPhysPage() / B_PAGE_SIZE; ++ if (pte->ppn == 0) ++ return NULL; ++ memset((Pte*)VirtFromPhys(B_PAGE_SIZE * pte->ppn), 0, B_PAGE_SIZE); ++ pte->flags |= (1 << pteValid); ++ } ++ pte = (Pte*)VirtFromPhys(B_PAGE_SIZE * pte->ppn); ++ } ++ pte += VirtAdrPte(virtAdr, 0); ++ return pte; ++} ++ ++ ++static void ++Map(addr_t virtAdr, phys_addr_t physAdr, uint64 flags) ++{ ++ // dprintf("Map(0x%" B_PRIxADDR ", 0x%" B_PRIxADDR ")\n", virtAdr, physAdr); ++ Pte* pte = LookupPte(virtAdr, true); ++ if (pte == NULL) ++ panic("can't allocate page table"); ++ ++ pte->ppn = physAdr / B_PAGE_SIZE; ++ pte->flags = (1 << pteValid) | (1 << pteAccessed) | (1 << pteDirty) | flags; ++} ++ ++ ++static void ++MapRange(addr_t virtAdr, phys_addr_t physAdr, size_t size, uint64 flags) ++{ ++ dprintf("MapRange(0x%" B_PRIxADDR ", 0x%" B_PRIxADDR ", 0x%" ++ B_PRIxADDR ", ", virtAdr, physAdr, size); ++ WritePteFlags(flags); ++ dprintf(")\n"); ++ for (size_t i = 0; i < size; i += B_PAGE_SIZE) ++ Map(virtAdr + i, physAdr + i, flags); ++ ++ ASSERT_ALWAYS(insert_virtual_allocated_range(virtAdr, size) >= B_OK); ++} ++ ++ ++static void ++MapRangeIdentity(addr_t adr, size_t size, uint64 flags) ++{ ++ MapRange(adr, adr, size, flags); ++} ++ ++ ++static void ++MapAddrRange(addr_range& range, uint64 flags) ++{ ++ phys_addr_t physAdr = range.start; ++ range.start = AllocVirtPages(range.size); ++ ++ MapRange(range.start, physAdr, range.size, flags); ++ ++ if (gKernelArgs.arch_args.num_virtual_ranges_to_keep ++ >= MAX_VIRTUAL_RANGES_TO_KEEP) ++ panic("too many virtual ranges to keep"); ++ ++ gKernelArgs.arch_args.virtual_ranges_to_keep[ ++ gKernelArgs.arch_args.num_virtual_ranges_to_keep++] = range; ++} ++ ++ ++static void ++PreallocKernelRange() ++{ ++ Pte *root = (Pte*)VirtFromPhys(sPageTable); ++ for (uint64 i = VirtAdrPte(KERNEL_BASE, 2); i <= VirtAdrPte(KERNEL_TOP, 2); ++ i++) { ++ Pte* pte = &root[i]; ++ pte->ppn = AllocPhysPage() / B_PAGE_SIZE; ++ if (pte->ppn == 0) panic("can't alloc early physical page"); ++ memset(VirtFromPhys(B_PAGE_SIZE * pte->ppn), 0, B_PAGE_SIZE); ++ pte->flags |= (1 << pteValid); ++ } ++} ++ ++ ++static void ++SetupPageTable() ++{ ++ sPageTable = AllocPhysPage(); ++ memset(VirtFromPhys(sPageTable), 0, B_PAGE_SIZE); ++ ++ PreallocKernelRange(); ++ ++ // Physical memory mapping ++ gKernelArgs.arch_args.physMap.size ++ = gKernelArgs.physical_memory_range[0].size; ++ gKernelArgs.arch_args.physMap.start = KERNEL_TOP + 1 ++ - gKernelArgs.arch_args.physMap.size; ++ MapRange(gKernelArgs.arch_args.physMap.start, ++ gKernelArgs.physical_memory_range[0].start, ++ gKernelArgs.arch_args.physMap.size, ++ (1 << pteRead) | (1 << pteWrite)); ++ ++ // Boot loader ++ MapRangeIdentity((addr_t)gMemBase, &gStackEnd - gMemBase, ++ (1 << pteRead) | (1 << pteWrite) | (1 << pteExec)); ++ ++ // Memory regions ++ MemoryRegion* region; ++ for (region = sRegions; region != NULL; region = region->next) { ++ uint64 flags = 0; ++ if ((region->protection & B_READ_AREA) != 0) ++ flags |= (1 << pteRead); ++ if ((region->protection & B_WRITE_AREA) != 0) ++ flags |= (1 << pteWrite); ++ if ((region->protection & B_EXECUTE_AREA) != 0) ++ flags |= (1 << pteExec); ++ MapRange(region->virtAdr, region->physAdr, region->size, flags); ++ } ++ ++ // Devices ++ MapAddrRange(gKernelArgs.arch_args.clint, (1 << pteRead) | (1 << pteWrite)); ++ MapAddrRange(gKernelArgs.arch_args.htif, (1 << pteRead) | (1 << pteWrite)); ++ MapAddrRange(gKernelArgs.arch_args.plic, (1 << pteRead) | (1 << pteWrite)); ++ if (gKernelArgs.arch_args.uart.kind != kUartKindNone) { ++ MapAddrRange(gKernelArgs.arch_args.uart.regs, ++ (1 << pteRead) | (1 << pteWrite)); ++ } ++} ++ ++ ++static uint64 ++GetSatp() ++{ ++ SatpReg satp; ++ satp.ppn = sPageTable / B_PAGE_SIZE; ++ satp.asid = 0; ++ satp.mode = satpModeSv39; ++ return satp.val; ++} + + + // #pragma mark - + + extern "C" status_t +-platform_allocate_region(void** _address, size_t size, uint8 protection, ++platform_allocate_region(void** address, size_t size, uint8 protection, + bool exactAddress) + { ++ size = ROUNDUP(size, B_PAGE_SIZE); ++ + if (exactAddress) + return B_ERROR; + +- gFreeMem = (uint8*)(((addr_t)gFreeMem +- + (B_PAGE_SIZE - 1)) / B_PAGE_SIZE * B_PAGE_SIZE); +- *_address = gFreeMem; +- gFreeMem += size; ++ ObjectDeleter region(new(std::nothrow) MemoryRegion()); ++ if (!region.IsSet()) ++ return B_NO_MEMORY; ++ ++ region->physAdr = AllocPhysPages(size); ++ if (region->physAdr == 0) ++ return B_NO_MEMORY; ++ ++ region->virtAdr = AllocVirtPages(size); ++ region->size = size; ++ region->protection = protection; ++ ++ *address = (void*)region->physAdr; ++ ++ region->next = sRegions; ++ sRegions = region.Detach(); + + return B_OK; + } +@@ -48,6 +313,25 @@ platform_allocate_region(void** _address, size_t size, uint8 protection, + extern "C" status_t + platform_free_region(void* address, size_t size) + { ++ MemoryRegion* prev = NULL; ++ MemoryRegion* region = sRegions; ++ while (region != NULL && !(region->physAdr == (phys_addr_t)address)) { ++ prev = region; ++ region = region->next; ++ } ++ if (region == NULL) { ++ panic("platform_free_region: address %p is not allocated\n", address); ++ return B_ERROR; ++ } ++ FreePhysPages(region->physAdr, region->size); ++ FreeVirtPages(region->virtAdr, region->size); ++ if (prev == NULL) ++ sRegions = region->next; ++ else ++ prev->next = region->next; ++ ++ delete region; ++ + return B_OK; + } + +@@ -61,27 +345,44 @@ platform_release_heap(struct stage2_args* args, void* base) + status_t + platform_init_heap(struct stage2_args* args, void** _base, void** _top) + { +- void* heap = (void*)gFreeMem; +- gFreeMem += args->heap_size; ++ addr_t heap = AllocPhysPages(args->heap_size); ++ if (heap == 0) ++ return B_NO_MEMORY; + +- *_base = heap; +- *_top = (void*)((int8*)heap + args->heap_size); ++ *_base = (void*)heap; ++ *_top = (void*)(heap + args->heap_size); + return B_OK; + } + + + status_t +-platform_bootloader_address_to_kernel_address(void* address, addr_t* _result) ++platform_bootloader_address_to_kernel_address(void* address, addr_t* result) + { +- *_result = (addr_t)address; ++ MemoryRegion* region = sRegions; ++ while (region != NULL && !((phys_addr_t)address >= region->physAdr ++ && (phys_addr_t)address < region->physAdr + region->size)) ++ region = region->next; ++ ++ if (region == NULL) ++ return B_ERROR; ++ ++ *result = (addr_t)address - region->physAdr + region->virtAdr; + return B_OK; + } + + + status_t +-platform_kernel_address_to_bootloader_address(addr_t address, void** _result) ++platform_kernel_address_to_bootloader_address(addr_t address, void** result) + { +- *_result = (void*)address; ++ MemoryRegion* region = sRegions; ++ while (region != NULL && !((phys_addr_t)address >= region->virtAdr ++ && (phys_addr_t)address < region->virtAdr + region->size)) ++ region = region->next; ++ ++ if (region == NULL) ++ return B_ERROR; ++ ++ *result = (void*)(address - region->virtAdr + region->physAdr); + return B_OK; + } + +@@ -95,29 +396,33 @@ mmu_init(void) + + + void +-mmu_init_for_kernel(void) ++mmu_init_for_kernel(addr_t& satp) + { + // map in a kernel stack + void* stack_address = NULL; + if (platform_allocate_region(&stack_address, +- KERNEL_STACK_SIZE + KERNEL_STACK_GUARD_PAGES * B_PAGE_SIZE, 0, false) ++ KERNEL_STACK_SIZE + KERNEL_STACK_GUARD_PAGES * B_PAGE_SIZE, ++ B_READ_AREA | B_WRITE_AREA, false) + != B_OK) { + panic("Unabled to allocate a stack"); + } +- gKernelArgs.cpu_kstack[0].start = (addr_t)stack_address; ++ gKernelArgs.cpu_kstack[0].start = fix_address((addr_t)stack_address); + gKernelArgs.cpu_kstack[0].size = KERNEL_STACK_SIZE + + KERNEL_STACK_GUARD_PAGES * B_PAGE_SIZE; + dprintf("Kernel stack at %#lx\n", gKernelArgs.cpu_kstack[0].start); + +- gKernelArgs.physical_memory_range[0].start = (addr_t)gMemBase; +- gKernelArgs.physical_memory_range[0].size = gTotalMem; +- gKernelArgs.num_physical_memory_ranges = 1; ++ gKernelArgs.num_physical_memory_ranges = 0; ++ insert_physical_memory_range((addr_t)gMemBase, gTotalMem); ++ ++ gKernelArgs.num_virtual_allocated_ranges = 0; ++ gKernelArgs.arch_args.num_virtual_ranges_to_keep = 0; ++ ++ SetupPageTable(); ++ satp = GetSatp(); ++ dprintf("satp: %#" B_PRIx64 "\n", satp); + +- gKernelArgs.physical_allocated_range[0].start = (addr_t)gMemBase; +- gKernelArgs.physical_allocated_range[0].size = gFreeMem - gMemBase; +- gKernelArgs.num_physical_allocated_ranges = 1; ++ gKernelArgs.num_physical_allocated_ranges = 0; ++ insert_physical_allocated_range((addr_t)gMemBase, gFreeMem - gMemBase); + +- gKernelArgs.virtual_allocated_range[0].start = (addr_t)gMemBase; +- gKernelArgs.virtual_allocated_range[0].size = gFreeMem - gMemBase; +- gKernelArgs.num_virtual_allocated_ranges = 1; ++ sort_address_ranges(gKernelArgs.virtual_allocated_range, gKernelArgs.num_virtual_allocated_ranges); + } +diff --git a/src/system/boot/platform/riscv/mmu.h b/src/system/boot/platform/riscv/mmu.h +index 17f202f987..6b66fcecdd 100644 +--- a/src/system/boot/platform/riscv/mmu.h ++++ b/src/system/boot/platform/riscv/mmu.h +@@ -10,13 +10,37 @@ + + #include + ++#include ++#include ++ + + extern uint8* gMemBase; + extern size_t gTotalMem; + + + void mmu_init(); +-void mmu_init_for_kernel(); ++void mmu_init_for_kernel(addr_t& satp); ++ ++ ++inline addr_t ++fix_address(addr_t address) ++{ ++ addr_t result; ++ if (platform_bootloader_address_to_kernel_address((void *)address, &result) ++ != B_OK) ++ return address; ++ ++ return result; ++} ++ ++ ++template ++inline void ++fix_address(FixedWidthPointer& p) ++{ ++ if (p != NULL) ++ p.SetTo(fix_address(p.Get())); ++} + + + #endif /* MMU_H */ +diff --git a/src/system/boot/platform/riscv/smp.cpp b/src/system/boot/platform/riscv/smp.cpp +new file mode 100644 +index 0000000000..39e91d8ed5 +--- /dev/null ++++ b/src/system/boot/platform/riscv/smp.cpp +@@ -0,0 +1,7 @@ ++/* ++ * Copyright 2021, Haiku, Inc. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++ ++#include "smp.h" +diff --git a/src/system/boot/platform/riscv/smp.h b/src/system/boot/platform/riscv/smp.h +new file mode 100644 +index 0000000000..21103dd8d3 +--- /dev/null ++++ b/src/system/boot/platform/riscv/smp.h +@@ -0,0 +1,40 @@ ++/* ++ * Copyright 2021, Haiku, Inc. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++ ++#ifndef _SMP_H_ ++#define _SMP_H_ ++ ++ ++#include ++ ++ ++struct Mutex ++{ ++ int32 fLock; ++ ++ Mutex(): fLock(0) {} ++ ++ bool TryLock() ++ { ++ return atomic_test_and_set(&fLock, -1, 0) == 0; ++ } ++ ++ bool Lock() ++ { ++ while (!TryLock()) {} ++ if (atomic_add(&fLock, -1) < 0) { ++ } ++ return true; ++ } ++ ++ void Unlock() ++ { ++ atomic_add(&fLock, 1); ++ } ++}; ++ ++ ++#endif // _SMP_H_ +diff --git a/src/system/boot/platform/riscv/start.cpp b/src/system/boot/platform/riscv/start.cpp +index fc21aa14d6..686dec70fc 100644 +--- a/src/system/boot/platform/riscv/start.cpp ++++ b/src/system/boot/platform/riscv/start.cpp +@@ -16,6 +16,8 @@ + #include "console.h" + #include "cpu.h" + #include "mmu.h" ++#include "smp.h" ++#include "traps.h" + #include "fdt.h" + #include "Htif.h" + #include "virtio.h" +@@ -32,8 +34,8 @@ extern uint8 _end; + + extern "C" int main(stage2_args* args); + extern "C" void _start(int hartId, void* fdt); +-extern "C" status_t arch_enter_kernel(struct kernel_args* kernelArgs, +- addr_t kernelEntry, addr_t kernelStackTop);; ++extern "C" status_t arch_enter_kernel(uint64 satp, ++ struct kernel_args* kernelArgs, addr_t kernelEntry, addr_t kernelStackTop); + + + static uint32 sBootOptions; +@@ -90,10 +92,70 @@ platform_boot_options(void) + } + + ++static void ++convert_preloaded_image(preloaded_elf64_image* image) ++{ ++ fix_address(image->next); ++ fix_address(image->name); ++ fix_address(image->debug_string_table); ++ fix_address(image->syms); ++ fix_address(image->rel); ++ fix_address(image->rela); ++ fix_address(image->pltrel); ++ fix_address(image->debug_symbols); ++} ++ ++ ++static void ++convert_kernel_args() ++{ ++ if (gKernelArgs.kernel_image->elf_class != ELFCLASS64) ++ return; ++ ++ fix_address(gKernelArgs.boot_volume); ++ fix_address(gKernelArgs.vesa_modes); ++ fix_address(gKernelArgs.edid_info); ++ fix_address(gKernelArgs.debug_output); ++ fix_address(gKernelArgs.boot_splash); ++ #if defined(__x86_64__) || defined(__x86__) ++ fix_address(gKernelArgs.ucode_data); ++ fix_address(gKernelArgs.arch_args.apic); ++ fix_address(gKernelArgs.arch_args.hpet); ++ #endif ++ fix_address(gKernelArgs.arch_args.fdt); ++ ++ convert_preloaded_image(static_cast( ++ gKernelArgs.kernel_image.Pointer())); ++ fix_address(gKernelArgs.kernel_image); ++ ++ // Iterate over the preloaded images. Must save the next address before ++ // converting, as the next pointer will be converted. ++ preloaded_image* image = gKernelArgs.preloaded_images; ++ fix_address(gKernelArgs.preloaded_images); ++ while (image != NULL) { ++ preloaded_image* next = image->next; ++ convert_preloaded_image(static_cast(image)); ++ image = next; ++ } ++ ++ // Fix driver settings files. ++ driver_settings_file* file = gKernelArgs.driver_settings; ++ fix_address(gKernelArgs.driver_settings); ++ while (file != NULL) { ++ driver_settings_file* next = file->next; ++ fix_address(file->next); ++ fix_address(file->buffer); ++ file = next; ++ } ++} ++ ++ + extern "C" void + platform_start_kernel(void) + { + static struct kernel_args* args = &gKernelArgs; ++ // platform_bootloader_address_to_kernel_address(&gKernelArgs, (addr_t*)&args); ++ + preloaded_elf64_image* image = static_cast( + gKernelArgs.kernel_image.Pointer()); + +@@ -105,14 +167,21 @@ platform_start_kernel(void) + // Avoid interrupts from virtio devices before kernel driver takes control. + virtio_fini(); + ++ gKernelArgs.arch_args.platform1 = kPlatform1Riscv; ++ gKernelArgs.arch_args.platform2 = kPlatform2Riscv; ++ + fdt_set_kernel_args(); +- mmu_init_for_kernel(); + +- dprintf("kernel entry at %lx\n", image->elf_header.e_entry); ++ convert_kernel_args(); ++ uint64 satp; ++ mmu_init_for_kernel(satp); ++ ++ dprintf("kernel entry: %lx\n", image->elf_header.e_entry); ++ dprintf("args: %lx\n", (addr_t)args); + + addr_t stackTop + = gKernelArgs.cpu_kstack[0].start + gKernelArgs.cpu_kstack[0].size; +- arch_enter_kernel(args, image->elf_header.e_entry, stackTop); ++ arch_enter_kernel(satp, args, image->elf_header.e_entry, stackTop); + + panic("kernel returned!\n"); + +@@ -139,6 +208,7 @@ _start(int hartId, void* fdt) + args.heap_size = HEAP_SIZE; + args.arguments = NULL; + ++ traps_init(); + // console_init(); + // virtio_init(); + cpu_init(); +diff --git a/src/system/boot/platform/riscv/traps.cpp b/src/system/boot/platform/riscv/traps.cpp +new file mode 100644 +index 0000000000..1294d04963 +--- /dev/null ++++ b/src/system/boot/platform/riscv/traps.cpp +@@ -0,0 +1,164 @@ ++/* ++ * Copyright 2021, Haiku, Inc. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++#include "traps.h" ++#include ++#include ++#include ++#include ++#include ++ ++ ++// TODO: Put machine mode code in separate section and keep it loaded when ++// kernel is running. ++ ++ ++struct iframe { ++ uint64 ra; ++ uint64 t6; ++ uint64 sp; ++ uint64 gp; ++ uint64 tp; ++ uint64 t0; ++ uint64 t1; ++ uint64 t2; ++ uint64 t5; ++ uint64 s1; ++ uint64 a0; ++ uint64 a1; ++ uint64 a2; ++ uint64 a3; ++ uint64 a4; ++ uint64 a5; ++ uint64 a6; ++ uint64 a7; ++ uint64 s2; ++ uint64 s3; ++ uint64 s4; ++ uint64 s5; ++ uint64 s6; ++ uint64 s7; ++ uint64 s8; ++ uint64 s9; ++ uint64 s10; ++ uint64 s11; ++ uint64 t3; ++ uint64 t4; ++ uint64 fp; ++ uint64 epc; ++}; ++ ++ ++__attribute__ ((aligned (16))) char sMStack[64*1024]; ++ ++ ++extern "C" void MVec(); ++extern "C" void MVecS(); ++ ++static void ++InitPmp() ++{ ++ // Setup physical memory protecton. By default physical memory can be only ++ // accessed from machine mode. ++ ++ // We allow access to whole physical memory from non-machine mode. ++ ++ SetPmpaddr0((~0L) >> 10); ++ SetPmpcfg0((1 << pmpR) | (1 << pmpW) | (1 << pmpX) | (pmpMatchNapot)); ++} ++ ++ ++extern "C" status_t __attribute__((naked)) ++MSyscall(uint64 op, ...) ++{ ++ asm volatile("ecall"); ++ asm volatile("ret"); ++} ++ ++ ++extern "C" void ++MTrap(iframe* frame) ++{ ++ uint64 cause = Mcause(); ++/* ++ HtifOutString("MTrap("); WriteCause(Mcause()); HtifOutString(")\n"); ++ dprintf(" mstatus: "); WriteMstatus(Mstatus()); dprintf("\n"); ++ dprintf(" mie: "); WriteInterruptSet(Mie()); dprintf("\n"); ++ dprintf(" mip: "); WriteInterruptSet(Mip()); dprintf("\n"); ++ dprintf(" sie: "); WriteInterruptSet(Sie()); dprintf("\n"); ++ dprintf(" sip: "); WriteInterruptSet(Sip()); dprintf("\n"); ++ dprintf(" mscratch: 0x%" B_PRIxADDR "\n", Mscratch()); ++ DoStackTrace(Fp(), 0); ++*/ ++ switch (cause) { ++ case causeMEcall: ++ case causeSEcall: { ++ frame->epc += 4; ++ uint64 op = frame->a0; ++ switch (op) { ++ case kMSyscallSwitchToSmode: { ++ HtifOutString("switchToSmodeMmodeSyscall()\n"); ++ if (cause != causeMEcall) { ++ frame->a0 = B_NOT_ALLOWED; ++ return; ++ } ++ MstatusReg status(Mstatus()); ++ status.mpp = modeS; ++ SetMedeleg( ++ 0xffff & ~((1 << causeMEcall) | (1 << causeSEcall))); ++ SetMideleg(0xffff & ~(1 << mTimerInt)); ++ SetMstatus(status.val); ++ dprintf("modeM stack: 0x%" B_PRIxADDR ", 0x%" B_PRIxADDR ++ "\n", (addr_t)sMStack, ++ (addr_t)(sMStack + sizeof(sMStack))); ++ SetMscratch((addr_t)(sMStack + sizeof(sMStack))); ++ SetMtvec((uint64)MVecS); ++ frame->a0 = B_OK; ++ return; ++ } ++ case kMSyscallSetTimer: { ++ bool enable = frame->a1 != 0; ++ /* ++ dprintf("setTimerMmodeSyscall(%d, %" B_PRIu64 ")\n", ++ enable, frame->a2); ++ */ ++ // dprintf(" mtime: %" B_PRIu64 "\n", gClintRegs->mTime); ++ SetMip(Mip() & ~(1 << sTimerInt)); ++ if (!enable) { ++ SetMie(Mie() & ~(1 << mTimerInt)); ++ } else { ++ gClintRegs->mtimecmp[0] = frame->a2; ++ SetMie(Mie() | (1 << mTimerInt)); ++ } ++ frame->a0 = B_OK; ++ return; ++ } ++ default: ++ frame->a0 = B_NOT_SUPPORTED; ++ return; ++ } ++ break; ++ } ++ case causeInterrupt + mTimerInt: { ++ SetMie(Mie() & ~(1 << mTimerInt)); ++ SetMip(Mip() | (1 << sTimerInt)); ++ return; ++ } ++ } ++ HtifOutString("unhandled MTrap\n"); ++ HtifShutdown(); ++} ++ ++ ++void ++traps_init() ++{ ++ SetMtvec((uint64)MVec); ++ MstatusReg mstatus(Mstatus()); ++ mstatus.ie = 1 << modeM; ++ SetMstatus(mstatus.val); ++ InitPmp(); ++ MSyscall(kMSyscallSwitchToSmode); ++} +diff --git a/src/system/boot/platform/riscv/traps.h b/src/system/boot/platform/riscv/traps.h +new file mode 100644 +index 0000000000..42b60d6deb +--- /dev/null ++++ b/src/system/boot/platform/riscv/traps.h +@@ -0,0 +1,8 @@ ++#ifndef _TRAPS_H_ ++#define _TRAPS_H_ ++ ++ ++void traps_init(); ++ ++ ++#endif // _TRAPS_H_ +diff --git a/src/system/boot/platform/riscv/traps_asm.S b/src/system/boot/platform/riscv/traps_asm.S +new file mode 100644 +index 0000000000..610fabd0e7 +--- /dev/null ++++ b/src/system/boot/platform/riscv/traps_asm.S +@@ -0,0 +1,57 @@ ++/* ++ * Copyright 2021, Haiku, Inc. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++ ++#include ++ ++ ++.globl MVec ++.type MVec, @function ++.align 4 ++MVec: ++ PushTrapFrame ++ sd fp, 2*8(sp) ++ csrr t0, mepc ++ sd t0, 31*8(sp) ++ ++ mv a0, sp ++ call MTrap ++ ++ ld t0, 31*8(sp) ++ csrw mepc, t0 ++ PopTrapFrame ++ mret ++.size MVec, .-MVec ++ ++ ++.globl MVecS ++.type MVecS, @function ++.align 4 ++MVecS: ++ csrrw sp, mscratch, sp ++ ++ PushTrapFrame ++ ++ csrr t0, mscratch ++ sd t0, 2*8(sp) # save supervisor SP ++ csrw mscratch, fp ++ ++ csrr t0, mepc ++ sd t0, 31*8(sp) ++ ++ la t0, MVec ++ csrw mtvec, t0 ++ ++ mv a0, sp ++ call MTrap ++ ++ la t0, MVecS ++ csrw mtvec, t0 ++ ++ ld t0, 31*8(sp) ++ csrw mepc, t0 ++ PopTrapFrame ++ mret ++.size MVecS, .-MVecS +diff --git a/src/system/boot/platform/riscv/video.cpp b/src/system/boot/platform/riscv/video.cpp +index 95ceb8a9c2..f9ed28aafc 100644 +--- a/src/system/boot/platform/riscv/video.cpp ++++ b/src/system/boot/platform/riscv/video.cpp +@@ -10,6 +10,7 @@ + //#include "images.h" + #include "graphics.h" + #include "virtio.h" ++#include "FwCfg.h" + + #include + #include +@@ -94,7 +95,7 @@ platform_switch_to_logo(void) + gKernelArgs.frame_buffer.height = gFramebuf.height; + gKernelArgs.frame_buffer.depth = 32; + gKernelArgs.frame_buffer.bytes_per_row = 4 * gFramebuf.stride; +- gKernelArgs.frame_buffer.enabled = true; ++ gKernelArgs.frame_buffer.enabled = gFramebuf.width > 0 && gFramebuf.height > 0; + + video_display_splash(gKernelArgs.frame_buffer.physical_buffer.start); + } +@@ -110,6 +111,7 @@ platform_switch_to_text_mode(void) + extern "C" status_t + platform_init_video(void) + { ++ FwCfg::Init(); + virtio_init(); // we want heap initalized + Clear(gFramebuf, 0xff000000); + console_init(); +diff --git a/src/system/boot/platform/riscv/virtio.cpp b/src/system/boot/platform/riscv/virtio.cpp +index 091546abb9..01f04c41ba 100644 +--- a/src/system/boot/platform/riscv/virtio.cpp ++++ b/src/system/boot/platform/riscv/virtio.cpp +@@ -22,7 +22,6 @@ int32_t gVirtioDevListLen = 0; + + DoublyLinkedList gVirtioDevices; + VirtioDevice* gKeyboardDev = NULL; +-VirtioDevice* gDiskDev = NULL; + + + void* +@@ -251,9 +250,12 @@ virtio_init() + gKeyboardDev = new(std::nothrow) VirtioDevice(*devRes); + } + dprintf("virtio_input count: %d\n", i); +- for (int i = 0; i < 4; i++) +- gKeyboardDev->ScheduleIO(new(std::nothrow) IORequest(ioOpWrite, +- malloc(sizeof(VirtioInputPacket)), sizeof(VirtioInputPacket))); ++ if (gKeyboardDev != NULL) { ++ for (int i = 0; i < 4; i++) { ++ gKeyboardDev->ScheduleIO(new(std::nothrow) IORequest(ioOpWrite, ++ malloc(sizeof(VirtioInputPacket)), sizeof(VirtioInputPacket))); ++ } ++ } + } + + +@@ -270,6 +272,9 @@ virtio_fini() + int + virtio_input_get_key() + { ++ if (gKeyboardDev == NULL) ++ return 0; ++ + IORequest* req = gKeyboardDev->ConsumeIO(); + if (req == NULL) + return 0; +-- +2.30.2 + diff --git a/patchset-hrev55144/0084-bus_managers-pci-add-riscv64-support.patch b/patchset-hrev55144/0084-bus_managers-pci-add-riscv64-support.patch new file mode 100644 index 0000000..cd0fd43 --- /dev/null +++ b/patchset-hrev55144/0084-bus_managers-pci-add-riscv64-support.patch @@ -0,0 +1,1526 @@ +From b03fc2bb49369363154406c64cc052dd7ca3843d Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 00:47:56 +0900 +Subject: bus_managers/pci: add riscv64 support + +Change-Id: I2b1324cd7af6ed203eb2fd07ec765da53b122387 +--- + .../bus_managers/pci/arch/riscv64/Jamfile | 8 +- + .../pci/arch/riscv64/pci_controller.cpp | 894 +++++++++++++++++- + .../pci/arch/riscv64/pci_controller_private.h | 104 ++ + .../bus_managers/pci/arch/riscv64/pci_io.c | 61 -- + .../bus_managers/pci/arch/riscv64/pci_io.cpp | 76 ++ + .../bus_managers/pci/arch/riscv64/pci_msi.cpp | 80 ++ + .../bus_managers/pci/arch/riscv64/pci_msi.h | 18 + + src/add-ons/kernel/bus_managers/pci/pci.cpp | 23 +- + .../kernel/bus_managers/pci/pci_private.h | 2 + + .../kernel/bus_managers/pci/pci_root.cpp | 52 +- + 10 files changed, 1220 insertions(+), 98 deletions(-) + create mode 100644 src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_controller_private.h + delete mode 100644 src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_io.c + create mode 100644 src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_io.cpp + create mode 100644 src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_msi.cpp + create mode 100644 src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_msi.h + +diff --git a/src/add-ons/kernel/bus_managers/pci/arch/riscv64/Jamfile b/src/add-ons/kernel/bus_managers/pci/arch/riscv64/Jamfile +index a09b7cbb37..21cf545281 100644 +--- a/src/add-ons/kernel/bus_managers/pci/arch/riscv64/Jamfile ++++ b/src/add-ons/kernel/bus_managers/pci/arch/riscv64/Jamfile +@@ -1,10 +1,12 @@ + SubDir HAIKU_TOP src add-ons kernel bus_managers pci arch $(TARGET_ARCH) ; + + SubDirHdrs [ FDirName $(SUBDIR) $(DOTDOT) $(DOTDOT) ] ; +-UsePrivateHeaders kernel [ FDirName kernel arch $(TARGET_ARCH) ] +- [ FDirName kernel boot platform $(HAIKU_BOOT_PLATFORM) ] ; ++UsePrivateKernelHeaders ; ++UsePrivateHeaders shared ; ++UsePrivateHeaders [ FDirName kernel util ] ; + + KernelStaticLibrary pci_arch_bus_manager : + pci_controller.cpp +- pci_io.c ++ pci_io.cpp ++ pci_msi.cpp + ; +diff --git a/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_controller.cpp b/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_controller.cpp +index 91f81c0169..fa361d16aa 100644 +--- a/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_controller.cpp ++++ b/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_controller.cpp +@@ -5,23 +5,903 @@ + + + #include "pci_controller.h" ++#include "pci.h" + +-//#include ++#include "pci_controller_private.h" ++#include "pci_msi.h" ++ ++#include ++ ++#include ++#include ++#include + + #include "pci_private.h" + + +-status_t +-pci_controller_init(void) ++extern PCI *gPCI; ++ ++ ++enum { ++ kRegIo, ++ kRegMmio32, ++ kRegMmio64, ++}; ++ ++ ++uint32 gHostCtrlType = 0; ++ ++AreaDeleter sPCIeConfigArea; ++addr_t gPCIeConfigPhysBase = 0; ++addr_t gPCIeConfigBase = 0; ++size_t gPCIeConfigSize = 0; ++ ++AreaDeleter sPCIeDbiArea; ++addr_t gPCIeDbiPhysBase = 0; ++addr_t gPCIeDbiBase = 0; ++size_t gPCIeDbiSize = 0; ++ ++AreaDeleter sPCIeIoArea; ++addr_t gPCIeIoBase = 0; ++ ++ ++struct { ++ phys_addr_t parentBase; ++ phys_addr_t childBase; ++ size_t size; ++ phys_addr_t free; ++} sPCIeRegisterRanges[3]; ++ ++ ++struct { ++ uint32_t childAdr; ++ uint32_t childIrq; ++} sInterruptMapMask; ++ ++struct InterruptMap { ++ uint32_t childAdr; ++ uint32_t childIrq; ++ uint32_t parentIrqCtrl; ++ uint32_t parentIrq; ++}; ++ ++ArrayDeleter sInterruptMap; ++uint32_t sInterruptMapLen = 0; ++ ++ ++static void ++SetRegisterRange(int kind, phys_addr_t parentBase, phys_addr_t childBase, ++ size_t size) ++{ ++ auto& range = sPCIeRegisterRanges[kind]; ++ ++ range.parentBase = parentBase; ++ range.childBase = childBase; ++ range.size = size; ++ // Avoid allocating zero address. ++ range.free = (childBase != 0) ? childBase : 1; ++} ++ ++ ++static phys_addr_t ++AllocRegister(int kind, size_t size) + { +- /* no support yet */ +-#warning RISCV64: WRITEME ++ auto& range = sPCIeRegisterRanges[kind]; ++ ++ phys_addr_t adr = ROUNDUP(range.free, size); ++ if (adr - range.childBase + size > range.size) ++ return 0; ++ ++ range.free = adr + size; ++ ++ return adr; ++} ++ ++ ++static InterruptMap* ++LookupInterruptMap(uint32_t childAdr, uint32_t childIrq) ++{ ++ childAdr &= sInterruptMapMask.childAdr; ++ childIrq &= sInterruptMapMask.childIrq; ++ for (uint32 i = 0; i < sInterruptMapLen; i++) { ++ if ((sInterruptMap[i].childAdr) == childAdr ++ && (sInterruptMap[i].childIrq) == childIrq) ++ return &sInterruptMap[i]; ++ } ++ return NULL; ++} ++ ++ ++static void ++WriteAtu() ++{ ++ dprintf("ATU:\n"); ++ for (uint32 direction = 0; direction < 2; direction++) { ++ switch (direction) { ++ case kPciAtuOutbound: dprintf(" outbound:\n"); break; ++ case kPciAtuInbound: dprintf(" inbound:\n"); break; ++ } ++ for (uint32 index = 0; index < 8; index++) { ++ volatile PciAtuRegs* atu = (PciAtuRegs*)(gPCIeDbiBase + kPciAtuOffset + (2*index + direction)*sizeof(PciAtuRegs)); ++ dprintf(" %" B_PRIu32 ": ", index); ++ dprintf("base: %#08" B_PRIx64, atu->baseLo + ((uint64)atu->baseHi << 32)); ++ dprintf(", limit: %#08" B_PRIx32, atu->limit); ++ dprintf(", target: %#08" B_PRIx64, atu->targetLo + ((uint64)atu->targetHi << 32)); ++ dprintf(", ctrl1: "); ++ uint32 ctrl1 = atu->ctrl1; ++ switch (ctrl1) { ++ case kPciAtuTypeMem: dprintf("mem"); break; ++ case kPciAtuTypeIo: dprintf("io"); break; ++ case kPciAtuTypeCfg0: dprintf("cfg0"); break; ++ case kPciAtuTypeCfg1: dprintf("cfg1"); break; ++ default: dprintf("? (%#" B_PRIx32 ")", ctrl1); ++ } ++ dprintf(", ctrl2: {"); ++ uint32 ctrl2 = atu->ctrl2; ++ bool first = true; ++ for (uint32 i = 0; i < 32; i++) { ++ if (((1 << i) & ctrl2) != 0) { ++ if (first) first = false; else dprintf(", "); ++ switch (i) { ++ case 30: dprintf("barModeEnable"); break; ++ case 31: dprintf("enable"); break; ++ default: dprintf("? (%" B_PRIu32 ")", i); break; ++ } ++ } ++ } ++ dprintf("}\n"); ++ } ++ } ++} ++ ++ ++static status_t ++AtuMap(uint32 index, uint32 direction, uint32 type, uint64 parentAdr, uint64 childAdr, uint32 size) ++{ ++/* ++ dprintf("AtuMap(%" B_PRIu32 ", %" B_PRIu32 ", %#" B_PRIx64 ", %#" B_PRIx64 ", %#" B_PRIx32 ")\n", ++ index, type, parentAdr, childAdr, size ++ ); ++*/ ++ volatile PciAtuRegs* atu = (PciAtuRegs*)(gPCIeDbiBase + kPciAtuOffset + (2*index + direction)*sizeof(PciAtuRegs)); ++ atu->baseLo = (uint32)parentAdr; ++ atu->baseHi = (uint32)(parentAdr >> 32); ++ atu->limit = (uint32)(parentAdr + size - 1); ++ atu->targetLo = (uint32)childAdr; ++ atu->targetHi = (uint32)(childAdr >> 32); ++ atu->ctrl1 = type; ++ atu->ctrl2 = kPciAtuEnable; ++ ++ for (;;) { ++ if ((atu->ctrl2 & kPciAtuEnable) != 0) ++ break; ++ } ++ + return B_OK; + } + + ++static uint32_t ++EncodePciAddress(uint8 bus, uint8 device, uint8 function) ++{ ++ return bus % (1 << 8) * (1 << 16) ++ + device % (1 << 5) * (1 << 11) ++ + function % (1 << 3) * (1 << 8); ++} ++ ++ ++static void ++DecodePciAddress(uint32_t adr, uint8& bus, uint8& device, uint8& function) ++{ ++ bus = adr / (1 << 16) % (1 << 8); ++ device = adr / (1 << 11) % (1 << 5); ++ function = adr / (1 << 8) % (1 << 3); ++} ++ ++ ++static inline addr_t ++PciConfigAdrEcam(uint8 bus, uint8 device, uint8 function, uint16 offset) ++{ ++ addr_t address = gPCIeConfigBase + EncodePciAddress(bus, device, function) * (1 << 4) + offset; ++ if (address < gPCIeConfigBase ++ || address /*+ size*/ > gPCIeConfigBase + gPCIeConfigSize) ++ return 0; ++ ++ return address; ++} ++ ++ ++static inline addr_t ++PciConfigAdrSifive(uint8 bus, uint8 device, uint8 function, uint16 offset) ++{ ++ uint32 atuType; ++ if (bus == 0) { ++ if (device != 0 || function != 0) ++ return 0; ++ ++ return gPCIeDbiBase + offset; ++ } else if (bus == 1) ++ atuType = kPciAtuTypeCfg0; ++ else ++ atuType = kPciAtuTypeCfg1; ++ ++ status_t res = AtuMap(1, kPciAtuOutbound, atuType, gPCIeConfigPhysBase, EncodePciAddress(bus, device, function) << 8, gPCIeConfigSize); ++ if (res < B_OK) ++ return 0; ++ ++ return gPCIeConfigBase + offset; ++} ++ ++ ++static inline addr_t ++PciConfigAdr(uint8 bus, uint8 device, uint8 function, uint16 offset) ++{ ++ switch (gHostCtrlType) { ++ case kHostCtrlEcam: ++ return PciConfigAdrEcam(bus, device, function, offset); ++ case kHostCtrlSifive: ++ return PciConfigAdrSifive(bus, device, function, offset); ++ default: ++ return 0; ++ } ++} ++ ++ ++static status_t ++read_pci_config(void *cookie, uint8 bus, uint8 device, uint8 function, ++ uint16 offset, uint8 size, uint32 *value) ++{ ++ // PciConfigAdr may use sliding window ++ // TODO: SMP ++ InterruptsLocker locker; ++ ++ addr_t address = PciConfigAdr(bus, device, function, offset); ++ if (address == 0) ++ return B_ERROR; ++ ++ switch (size) { ++ case 1: *value = *(uint8 *)address; break; ++ case 2: *value = *(uint16*)address; break; ++ case 4: *value = *(uint32*)address; break; ++ default: ++ return B_ERROR; ++ } ++ ++ return B_OK; ++} ++ ++ ++static status_t ++write_pci_config(void *cookie, uint8 bus, uint8 device, uint8 function, ++ uint16 offset, uint8 size, uint32 value) ++{ ++ // PciConfigAdr may use sliding window ++ // TODO: SMP ++ InterruptsLocker locker; ++/* ++ dprintf("write_pci_config(%d:%d:%d, 0x%04x, %d, 0x%08x)\n", bus, device, ++ function, offset, size, value); ++*/ ++ addr_t address = PciConfigAdr(bus, device, function, offset); ++ if (address == 0) ++ return B_ERROR; ++ ++ switch (size) { ++ case 1: *(uint8 *)address = value; break; ++ case 2: *(uint16*)address = value; break; ++ case 4: *(uint32*)address = value; break; ++ default: ++ return B_ERROR; ++ } ++ ++ return B_OK; ++} ++ ++ ++static status_t ++get_max_bus_devices(void *cookie, int32 *count) ++{ ++ *count = 32; ++ return B_OK; ++} ++ ++status_t ++read_pci_irq(void *cookie, uint8 bus, uint8 device, uint8 function, uint8 pin, ++ uint8 *irq) ++{ ++ return B_NOT_SUPPORTED; ++} ++ ++ ++status_t ++write_pci_irq(void *cookie, uint8 bus, uint8 device, uint8 function, uint8 pin, ++ uint8 irq) ++{ ++ return B_NOT_SUPPORTED; ++} ++ ++ ++pci_controller pci_controller_riscv64 = ++{ ++ read_pci_config, ++ write_pci_config, ++ get_max_bus_devices, ++ read_pci_irq, ++ write_pci_irq, ++}; ++ ++ ++static void ++InitMsiForDevice(uint8 bus, uint8 device, uint8 function) ++{ ++#if 0 ++ uint32 status; ++ uint32 capPtr; ++ uint32 capId; ++ int i; ++ ++ uint32 offset; ++ dprintf(" %02x", 0); ++ for (offset = 0; offset < 0x100; offset += 4) { ++ uint32 value; ++ read_pci_config(NULL, bus, device, function, offset, 4, &value); ++ dprintf(" %08" B_PRIx32, B_BENDIAN_TO_HOST_INT32(value)); ++ if (offset % 0x10 == 0x10 - 4) ++ dprintf("\n %02x", offset + 4); ++ } ++ dprintf("\n"); ++ ++ read_pci_config(NULL, bus, device, function, PCI_status, 2, &status); ++ if (!(status & PCI_status_capabilities)) { ++ return; ++ } ++ ++ dprintf(" capabilities: "); ++ ++ uint32 headerType; ++ read_pci_config(NULL, bus, device, function, ++ PCI_header_type, 1, &headerType); ++ ++ switch (headerType & PCI_header_type_mask) { ++ case PCI_header_type_generic: ++ case PCI_header_type_PCI_to_PCI_bridge: ++ read_pci_config(NULL, bus, device, function, PCI_capabilities_ptr, 1, &capPtr); ++ break; ++ case PCI_header_type_cardbus: ++ read_pci_config(NULL, bus, device, function, PCI_capabilities_ptr_2, 1, &capPtr); ++ break; ++ default: ++ dprintf("(unknown header type)\n"); ++ return; ++ } ++ ++ capPtr &= ~3; ++ if (capPtr == 0) { ++ dprintf("\n"); ++ return; ++ } ++ ++ for (i = 0; i < 48; i++) { ++ read_pci_config(NULL, bus, device, function, capPtr + 0, 1, &capId); ++ if (i > 0) ++ dprintf(", "); ++ ++ dprintf("%#" B_PRIx32 ":%#" B_PRIx32, capPtr, capId); ++ ++ read_pci_config(NULL, bus, device, function, capPtr + 1, 1, &capPtr); ++ capPtr &= ~3; ++ if (capPtr == 0) ++ break; ++ } ++ dprintf("\n"); ++#endif ++ uint32 status; ++ uint32 capPtr; ++ uint32 capId; ++ ++ read_pci_config(NULL, bus, device, function, PCI_status, 2, &status); ++ if ((status & PCI_status_capabilities) == 0) ++ return; ++ ++ uint32 headerType; ++ read_pci_config(NULL, bus, device, function, ++ PCI_header_type, 1, &headerType); ++ ++ switch (headerType & PCI_header_type_mask) { ++ case PCI_header_type_generic: ++ case PCI_header_type_PCI_to_PCI_bridge: ++ read_pci_config(NULL, bus, device, function, PCI_capabilities_ptr, 1, &capPtr); ++ break; ++ case PCI_header_type_cardbus: ++ read_pci_config(NULL, bus, device, function, PCI_capabilities_ptr_2, 1, &capPtr); ++ break; ++ default: ++ return; ++ } ++ ++ capPtr &= ~3; ++ if (capPtr == 0) ++ return; ++ ++ for (int i = 0; i < 48; i++) { ++ read_pci_config(NULL, bus, device, function, capPtr + 0, 1, &capId); ++ ++ if (capId == PCI_cap_id_msi) ++ break; ++ ++ read_pci_config(NULL, bus, device, function, capPtr + 1, 1, &capPtr); ++ capPtr &= ~3; ++ if (capPtr == 0) ++ return; ++ } ++ ++ dprintf(" MSI offset: %#x\n", capPtr); ++ ++ int32 msiIrq = AllocMsiInterrupt(); ++ dprintf(" msiIrq: %" B_PRId32 "\n", msiIrq); ++ ++ uint32 control; ++ read_pci_config(NULL, bus, device, function, capPtr + PCI_msi_control, 2, &control); ++ ++ write_pci_config(NULL, bus, device, function, capPtr + PCI_msi_address, 4, (uint32)gMsiPhysAddr); ++ if ((control & PCI_msi_control_64bit) != 0) { ++ write_pci_config(NULL, bus, device, function, capPtr + PCI_msi_address_high, 4, (uint32)(gMsiPhysAddr >> 32)); ++ write_pci_config(NULL, bus, device, function, capPtr + PCI_msi_data_64bit, 2, msiIrq); ++ } else ++ write_pci_config(NULL, bus, device, function, capPtr + PCI_msi_data, 2, msiIrq); ++ ++ control &= ~PCI_msi_control_mme_mask; ++ control |= (ffs(1) - 1) << 4; ++ control |= PCI_msi_control_enable; ++ write_pci_config(NULL, bus, device, function, capPtr + PCI_msi_control, 2, control); ++ ++ write_pci_config(NULL, bus, device, function, PCI_interrupt_line, 1, gStartMsiIrq + msiIrq); ++} ++ ++ ++static void ++AllocRegsForDevice(uint8 bus, uint8 device, uint8 function) ++{ ++ dprintf("AllocRegsForDevice(bus: %d, device: %d, function: %d)\n", bus, ++ device, function); ++ ++ bool allocBars = gHostCtrlType == kHostCtrlEcam; ++ ++ uint32 vendorID, deviceID; ++ read_pci_config(NULL, bus, device, function, PCI_vendor_id, 2, &vendorID); ++ read_pci_config(NULL, bus, device, function, PCI_device_id, 2, &deviceID); ++ dprintf(" vendorID: %#04" B_PRIx32 "\n", vendorID); ++ dprintf(" deviceID: %#04" B_PRIx32 "\n", deviceID); ++ ++ uint32 headerType; ++ read_pci_config(NULL, bus, device, function, ++ PCI_header_type, 1, &headerType); ++ headerType = headerType % 0x80; ++ ++ dprintf(" headerType: "); ++ switch (headerType) { ++ case PCI_header_type_generic: dprintf("generic"); break; ++ case PCI_header_type_PCI_to_PCI_bridge: dprintf("bridge"); break; ++ case PCI_header_type_cardbus: dprintf("cardbus"); break; ++ default: dprintf("?(%u)", headerType); ++ } ++ dprintf("\n"); ++ ++ if (headerType == PCI_header_type_PCI_to_PCI_bridge) { ++ uint32 primaryBus, secondaryBus, subordinateBus; ++ read_pci_config(NULL, bus, device, function, PCI_primary_bus, 1, &primaryBus); ++ read_pci_config(NULL, bus, device, function, PCI_secondary_bus, 1, &secondaryBus); ++ read_pci_config(NULL, bus, device, function, PCI_subordinate_bus, 1, &subordinateBus); ++ dprintf(" primaryBus: %u\n", primaryBus); ++ dprintf(" secondaryBus: %u\n", secondaryBus); ++ dprintf(" subordinateBus: %u\n", subordinateBus); ++ } ++ ++ uint32 oldValLo = 0, oldValHi = 0, sizeLo = 0, sizeHi = 0; ++ uint64 val, size; ++ for (int i = 0; i < ((headerType == PCI_header_type_PCI_to_PCI_bridge) ? 2 : 6); i++) { ++ ++ dprintf(" bar[%d]: ", i); ++ ++ read_pci_config(NULL, bus, device, function, ++ PCI_base_registers + i*4, 4, &oldValLo); ++ ++ int regKind; ++ if (oldValLo % 2 == 1) { ++ regKind = kRegIo; ++ dprintf("IOPORT"); ++ } else if (oldValLo / 2 % 4 == 0) { ++ regKind = kRegMmio32; ++ dprintf("MMIO32"); ++ } else if (oldValLo / 2 % 4 == 2) { ++ regKind = kRegMmio64; ++ dprintf("MMIO64"); ++ } else { ++ dprintf("?(%d)", oldValLo / 2 % 4); ++ dprintf("\n"); ++ continue; ++ } ++ ++ read_pci_config (NULL, bus, device, function, ++ PCI_base_registers + i*4, 4, &oldValLo); ++ write_pci_config(NULL, bus, device, function, ++ PCI_base_registers + i*4, 4, 0xffffffff); ++ read_pci_config (NULL, bus, device, function, ++ PCI_base_registers + i*4, 4, &sizeLo); ++ write_pci_config(NULL, bus, device, function, ++ PCI_base_registers + i*4, 4, oldValLo); ++ val = oldValLo; ++ size = sizeLo; ++ if (regKind == kRegMmio64) { ++ read_pci_config (NULL, bus, device, function, ++ PCI_base_registers + (i + 1)*4, 4, &oldValHi); ++ write_pci_config(NULL, bus, device, function, ++ PCI_base_registers + (i + 1)*4, 4, 0xffffffff); ++ read_pci_config (NULL, bus, device, function, ++ PCI_base_registers + (i + 1)*4, 4, &sizeHi); ++ write_pci_config(NULL, bus, device, function, ++ PCI_base_registers + (i + 1)*4, 4, oldValHi); ++ val += ((uint64)oldValHi) << 32; ++ size += ((uint64)sizeHi ) << 32; ++ } else { ++ if (sizeLo != 0) ++ size += ((uint64)0xffffffff) << 32; ++ } ++ val &= ~(uint64)0xf; ++ size = ~(size & ~(uint64)0xf) + 1; ++/* ++ dprintf(", oldValLo: 0x%" B_PRIx32 ", sizeLo: 0x%" B_PRIx32, oldValLo, ++ sizeLo); ++ if (regKind == regMmio64) { ++ dprintf(", oldValHi: 0x%" B_PRIx32 ", sizeHi: 0x%" B_PRIx32, ++ oldValHi, sizeHi); ++ } ++*/ ++ dprintf(", adr: 0x%" B_PRIx64 ", size: 0x%" B_PRIx64, val, size); ++ ++ if (allocBars && /*val == 0 &&*/ size != 0) { ++ if (regKind == kRegMmio64) { ++ val = AllocRegister(regKind, size); ++ write_pci_config(NULL, bus, device, function, ++ PCI_base_registers + (i + 0)*4, 4, (uint32)val); ++ write_pci_config(NULL, bus, device, function, ++ PCI_base_registers + (i + 1)*4, 4, ++ (uint32)(val >> 32)); ++ dprintf(" -> 0x%" B_PRIx64, val); ++ } else { ++ val = AllocRegister(regKind, size); ++ write_pci_config(NULL, bus, device, function, ++ PCI_base_registers + i*4, 4, (uint32)val); ++ dprintf(" -> 0x%" B_PRIx64, val); ++ } ++ } ++ ++ dprintf("\n"); ++ ++ if (regKind == kRegMmio64) ++ i++; ++ } ++ ++ // ROM ++ dprintf(" rom_bar: "); ++ uint32 romBaseOfs = (headerType == PCI_header_type_PCI_to_PCI_bridge) ? PCI_bridge_rom_base : PCI_rom_base; ++ read_pci_config (NULL, bus, device, function, romBaseOfs, 4, &oldValLo); ++ write_pci_config(NULL, bus, device, function, romBaseOfs, 4, 0xfffffffe); ++ read_pci_config (NULL, bus, device, function, romBaseOfs, 4, &sizeLo); ++ write_pci_config(NULL, bus, device, function, romBaseOfs, 4, oldValLo); ++ ++ val = oldValLo & PCI_rom_address_mask; ++ size = ~(sizeLo & ~(uint32)0xf) + 1; ++ dprintf("adr: 0x%" B_PRIx64 ", size: 0x%" B_PRIx64, val, size); ++ if (allocBars && /*val == 0 &&*/ size != 0) { ++ val = AllocRegister(kRegMmio32, size); ++ write_pci_config(NULL, bus, device, function, ++ PCI_rom_base, 4, (uint32)val); ++ dprintf(" -> 0x%" B_PRIx64, val); ++ } ++ dprintf("\n"); ++ ++ uint32 intPin; ++ read_pci_config(NULL, bus, device, function, ++ PCI_interrupt_pin, 1, &intPin); ++ ++ InterruptMap* intMap = LookupInterruptMap(EncodePciAddress(bus, device, function), intPin); ++ if (intMap == NULL) ++ dprintf("no interrupt mapping for childAdr: (%d:%d:%d), childIrq: %d)\n", bus, device, function, intPin); ++ else { ++ write_pci_config(NULL, bus, device, function, ++ PCI_interrupt_line, 1, intMap->parentIrq); ++ } ++ ++ if (gHostCtrlType == kHostCtrlSifive) ++ InitMsiForDevice(bus, device, function); ++ ++ uint32 intLine; ++ read_pci_config(NULL, bus, device, function, ++ PCI_interrupt_line, 1, &intLine); ++ dprintf(" intLine: %u\n", intLine); ++ dprintf(" intPin: "); ++ switch (intPin) { ++ case 0: dprintf("-"); break; ++ case 1: dprintf("INTA#"); break; ++ case 2: dprintf("INTB#"); break; ++ case 3: dprintf("INTC#"); break; ++ case 4: dprintf("INTD#"); break; ++ default: dprintf("?(%u)", intPin); break; ++ } ++ dprintf("\n"); ++} ++ ++ ++static void ++AllocRegs() ++{ ++ dprintf("AllocRegs()\n"); ++ // TODO: improve enumeration ++ for (int j = 0; j < 8; j++) { ++ for (int i = 0; i < 32; i++) { ++ uint32 vendorID; ++ status_t res = read_pci_config(NULL, j, i, 0, PCI_vendor_id, 2, &vendorID); ++ if (res >= B_OK && vendorID != 0xffff) { ++ uint32 headerType; ++ read_pci_config(NULL, j, i, 0, ++ PCI_header_type, 1, &headerType); ++ if ((headerType & 0x80) != 0) { ++ for (int k = 0; k < 8; k++) ++ AllocRegsForDevice(j, i, k); ++ } else ++ AllocRegsForDevice(j, i, 0); ++ } ++ } ++ } ++} ++ ++ ++//#pragma mark - ++ ++status_t ++pci_controller_init() ++{ ++ dprintf("pci_controller_init()\n"); ++ ++ dprintf("sizeof(PciDbi): %#" B_PRIxSIZE "\n", sizeof(PciDbiRegs)); ++ ++ if (gPCIRootNode == NULL) ++ return B_OK; ++ ++ DeviceNodePutter<&gDeviceManager> parent( ++ gDeviceManager->get_parent_node(gPCIRootNode)); ++ fdt_device_module_info *parentModule; ++ fdt_device* parentDev; ++ if (gDeviceManager->get_driver(parent.Get(), ++ (driver_module_info**)&parentModule, (void**)&parentDev)) ++ panic("can't get parent node driver"); ++ ++ const char* compatible; ++ if (gDeviceManager->get_attr_string(parent.Get(), "fdt/compatible", &compatible, ++ false) < B_OK) ++ return B_ERROR; ++ ++ dprintf("hostCtrlType: "); ++ if (strcmp(compatible, "pci-host-ecam-generic") == 0) { ++ gHostCtrlType = kHostCtrlEcam; ++ dprintf("ecam\n"); ++ } else if (strcmp(compatible, "sifive,fu740-pcie") == 0) { ++ gHostCtrlType = kHostCtrlSifive; ++ dprintf("sifive\n"); ++ } else { ++ gHostCtrlType = kHostCtrlUnknown; ++ dprintf("unknown\n"); ++ return B_ERROR; ++ } ++ ++ uint64 regs; ++ uint64 regsLen; ++ for (uint32 i = 0; parentModule->get_reg(parentDev, i, ®s, ®sLen); ++ i++) { ++ dprintf(" reg[%" B_PRIu32 "]: (0x%" B_PRIx64 ", 0x%" B_PRIx64 ")\n", ++ i, regs, regsLen); ++ } ++ ++ uint64 configRegs = 0; ++ uint64 configRegsLen = 0; ++ uint64 dbiRegs = 0; ++ uint64 dbiRegsLen = 0; ++ switch (gHostCtrlType) { ++ case kHostCtrlEcam: ++ if (!parentModule->get_reg(parentDev, 0, &configRegs, &configRegsLen)) { ++ dprintf(" no regs\n"); ++ return B_ERROR; ++ } ++ break; ++ case kHostCtrlSifive: ++ if ( ++ !parentModule->get_reg(parentDev, 0, &dbiRegs, &dbiRegsLen) || ++ !parentModule->get_reg(parentDev, 1, &configRegs, &configRegsLen) ++ ) { ++ dprintf(" no regs\n"); ++ return B_ERROR; ++ } ++/* ++ // !!! ++ configRegs = 0x60070000; ++ configRegsLen = 0x10000; ++*/ ++ break; ++ } ++ ++ dprintf(" configRegs: (0x%" B_PRIx64 ", 0x%" B_PRIx64 ")\n", ++ configRegs, configRegsLen); ++ dprintf(" dbiRegs: (0x%" B_PRIx64 ", 0x%" B_PRIx64 ")\n", ++ dbiRegs, dbiRegsLen); ++ ++ int intMapLen; ++ const void* intMapAdr = parentModule->get_prop(parentDev, "interrupt-map", ++ &intMapLen); ++ if (intMapAdr == NULL) { ++ dprintf(" \"interrupt-map\" property not found"); ++ return B_ERROR; ++ } else { ++ int intMapMaskLen; ++ const void* intMapMask = parentModule->get_prop(parentDev, "interrupt-map-mask", ++ &intMapMaskLen); ++ ++ if (intMapMask == NULL || intMapMaskLen != 4 * 4) { ++ dprintf(" \"interrupt-map-mask\" property not found or invalid"); ++ return B_ERROR; ++ } ++ ++ sInterruptMapMask.childAdr = B_BENDIAN_TO_HOST_INT32(*((uint32*)intMapMask + 0)); ++ sInterruptMapMask.childIrq = B_BENDIAN_TO_HOST_INT32(*((uint32*)intMapMask + 3)); ++ ++ sInterruptMapLen = (uint32)intMapLen / (6 * 4); ++ sInterruptMap.SetTo(new(std::nothrow) InterruptMap[sInterruptMapLen]); ++ if (!sInterruptMap.IsSet()) ++ return B_NO_MEMORY; ++ ++ for (uint32_t *it = (uint32_t*)intMapAdr; ++ (uint8_t*)it - (uint8_t*)intMapAdr < intMapLen; it += 6) { ++ size_t i = (it - (uint32_t*)intMapAdr) / 6; ++ ++ sInterruptMap[i].childAdr = B_BENDIAN_TO_HOST_INT32(*(it + 0)); ++ sInterruptMap[i].childIrq = B_BENDIAN_TO_HOST_INT32(*(it + 3)); ++ sInterruptMap[i].parentIrqCtrl = B_BENDIAN_TO_HOST_INT32(*(it + 4)); ++ sInterruptMap[i].parentIrq = B_BENDIAN_TO_HOST_INT32(*(it + 5)); ++ } ++ ++ dprintf(" interrupt-map:\n"); ++ for (size_t i = 0; i < sInterruptMapLen; i++) { ++ dprintf(" "); ++ // child unit address ++ uint8 bus, device, function; ++ DecodePciAddress(sInterruptMap[i].childAdr, bus, device, function); ++ dprintf("bus: %" B_PRIu32, bus); ++ dprintf(", dev: %" B_PRIu32, device); ++ dprintf(", fn: %" B_PRIu32, function); ++ ++ dprintf(", childIrq: %" B_PRIu32, ++ sInterruptMap[i].childIrq); ++ dprintf(", parentIrq: (%" B_PRIu32, ++ sInterruptMap[i].parentIrqCtrl); ++ dprintf(", %" B_PRIu32, sInterruptMap[i].parentIrq); ++ dprintf(")\n"); ++ if (i % 4 == 3 && (i + 1 < sInterruptMapLen)) ++ dprintf("\n"); ++ } ++ } ++ ++ memset(sPCIeRegisterRanges, 0, sizeof(sPCIeRegisterRanges)); ++ int rangesLen; ++ const void* rangesAdr = parentModule->get_prop(parentDev, "ranges", ++ &rangesLen); ++ if (rangesAdr == NULL) { ++ dprintf(" \"ranges\" property not found"); ++ } else { ++ dprintf(" ranges:\n"); ++ for (uint32_t *it = (uint32_t*)rangesAdr; ++ (uint8_t*)it - (uint8_t*)rangesAdr < rangesLen; it += 7) { ++ dprintf(" "); ++ uint32_t kind = B_BENDIAN_TO_HOST_INT32(*(it + 0)); ++ uint64_t childAdr = B_BENDIAN_TO_HOST_INT64(*(uint64_t*)(it + 1)); ++ uint64_t parentAdr = B_BENDIAN_TO_HOST_INT64(*(uint64_t*)(it + 3)); ++ uint64_t len = B_BENDIAN_TO_HOST_INT64(*(uint64_t*)(it + 5)); ++ ++ switch (kind & 0x03000000) { ++ case 0x01000000: ++ SetRegisterRange(kRegIo, parentAdr, childAdr, len); ++ break; ++ case 0x02000000: ++ SetRegisterRange(kRegMmio32, parentAdr, childAdr, len); ++ break; ++ case 0x03000000: ++ SetRegisterRange(kRegMmio64, parentAdr, childAdr, len); ++ break; ++ } ++ ++ switch (kind & 0x03000000) { ++ case 0x00000000: dprintf("CONFIG"); break; ++ case 0x01000000: dprintf("IOPORT"); break; ++ case 0x02000000: dprintf("MMIO32"); break; ++ case 0x03000000: dprintf("MMIO64"); break; ++ } ++ ++ dprintf(" (0x%08" B_PRIx32 "): ", kind); ++ dprintf("child: %08" B_PRIx64, childAdr); ++ dprintf(", parent: %08" B_PRIx64, parentAdr); ++ dprintf(", len: %" B_PRIx64 "\n", len); ++ } ++ } ++ ++ ++ gPCIeConfigPhysBase = configRegs; ++ gPCIeConfigSize = configRegsLen; ++ sPCIeConfigArea.SetTo(map_physical_memory( ++ "PCI Config MMIO", ++ configRegs, gPCIeConfigSize, B_ANY_KERNEL_ADDRESS, ++ B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA, ++ (void**)&gPCIeConfigBase ++ )); ++ ++ if (dbiRegs != 0) { ++ gPCIeDbiPhysBase = dbiRegs; ++ gPCIeDbiSize = dbiRegsLen; ++ sPCIeDbiArea.SetTo(map_physical_memory( ++ "PCI DBI MMIO", ++ dbiRegs, gPCIeDbiSize, B_ANY_KERNEL_ADDRESS, ++ B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA, ++ (void**)&gPCIeDbiBase ++ )); ++ } ++ ++ sPCIeIoArea.SetTo(map_physical_memory( ++ "PCI IO", ++ sPCIeRegisterRanges[kRegIo].parentBase, ++ sPCIeRegisterRanges[kRegIo].size, ++ B_ANY_KERNEL_ADDRESS, B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA, ++ (void**)&gPCIeIoBase ++ )); ++ ++ if (!sPCIeConfigArea.IsSet()) { ++ dprintf(" can't map Config MMIO\n"); ++ return sPCIeConfigArea.Get(); ++ } ++ ++ if (!sPCIeIoArea.IsSet()) { ++ dprintf(" can't map IO\n"); ++ return sPCIeIoArea.Get(); ++ } ++ ++ if (gHostCtrlType == kHostCtrlSifive) { ++ WriteAtu(); ++ // TODO read MSI IRQ from FDT ++ InitPciMsi(0x38); ++ } ++ ++ AllocRegs(); ++ ++ if (gHostCtrlType == kHostCtrlSifive) ++ WriteAtu(); ++ ++ return pci_controller_add(&pci_controller_riscv64, NULL); ++} ++ ++ + phys_addr_t +-pci_ram_address(phys_addr_t physical_address_in_system_memory) ++pci_ram_address(phys_addr_t childAdr) + { +- return physical_address_in_system_memory; ++ // dprintf("pci_ram_address(0x%" B_PRIxPHYSADDR "): ", childAdr); ++ phys_addr_t parentAdr = 0; ++ for (int kind = kRegIo; kind <= kRegMmio64; kind++) { ++ auto& range = sPCIeRegisterRanges[kind]; ++ if (childAdr >= range.childBase ++ && childAdr < range.childBase + range.size) { ++ parentAdr = childAdr - range.childBase; ++ if (kind != kRegIo) ++ parentAdr += range.parentBase; ++ // dprintf("0x%" B_PRIxPHYSADDR "\n", parentAdr); ++ return parentAdr; ++ } ++ } ++ // dprintf("?\n"); ++ return 0; + } +diff --git a/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_controller_private.h b/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_controller_private.h +new file mode 100644 +index 0000000000..875af6d4c3 +--- /dev/null ++++ b/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_controller_private.h +@@ -0,0 +1,104 @@ ++#ifndef _PCI_CONTROLLER_PRIVATE_H_ ++#define _PCI_CONTROLLER_PRIVATE_H_ ++ ++ ++#include ++ ++ ++struct PciDbiRegs { ++ uint8 unknown0[0x700]; ++ ++ uint32 unknown1[3]; ++ uint32 portAfr; ++ uint32 linkControl; ++ uint32 unknown2[5]; ++ uint32 portDebug0; ++ uint32 portDebug1; ++ uint32 unknown3[55]; ++ uint32 linkWidthSpeedControl; ++ uint32 unknown4[4]; ++ uint32 msiAddrLo; ++ uint32 msiAddrHi; ++ struct { ++ uint32 enable; ++ uint32 mask; ++ uint32 status; ++ } msiIntr[8]; ++ uint32 unknown5[13]; ++ uint32 miscControl1Off; ++ uint32 miscPortMultiLaneCtrl; ++ uint32 unknown6[15]; ++ ++ uint32 atuViewport; ++ uint32 atuCr1; ++ uint32 atuCr2; ++ uint32 atuBaseLo; ++ uint32 atuBaseHi; ++ uint32 atuLimit; ++ uint32 atuTargetLo; ++ uint32 atuTargetHi; ++ uint32 unknown7; ++ uint32 atuLimitHi; ++ uint32 unknown8[8]; ++ ++ uint32 msixDoorbell; ++ uint32 unknown9[117]; ++ ++ uint32 plChkRegControlStatus; ++ uint32 unknown10; ++ uint32 plChkRegErrAddr; ++ uint32 unknown11[309]; ++}; ++ ++ ++enum { ++ kPciAtuOffset = 0x300000, ++}; ++ ++enum { ++ kPciAtuOutbound = 0, ++ kPciAtuInbound = 1, ++}; ++ ++enum { ++ // ctrl1 ++ kPciAtuTypeMem = 0, ++ kPciAtuTypeIo = 2, ++ kPciAtuTypeCfg0 = 4, ++ kPciAtuTypeCfg1 = 5, ++ // ctrl2 ++ kPciAtuBarModeEnable = 1 << 30, ++ kPciAtuEnable = 1 << 31, ++}; ++ ++struct PciAtuRegs { ++ uint32 ctrl1; ++ uint32 ctrl2; ++ uint32 baseLo; ++ uint32 baseHi; ++ uint32 limit; ++ uint32 targetLo; ++ uint32 targetHi; ++ uint32 unused[57]; ++}; ++ ++ ++enum { ++ kHostCtrlUnknown = 0, ++ kHostCtrlEcam = 1, ++ kHostCtrlSifive = 2, ++}; ++ ++extern uint32 gHostCtrlType; ++ ++ ++extern addr_t gPCIeConfigPhysBase; ++extern addr_t gPCIeConfigBase; ++extern size_t sPCIeConfigSize; ++ ++extern addr_t gPCIeDbiPhysBase; ++extern addr_t gPCIeDbiBase; ++extern size_t gPCIeDbiSize; ++ ++ ++#endif // _PCI_CONTROLLER_PRIVATE_H_ +diff --git a/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_io.c b/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_io.c +deleted file mode 100644 +index 79738743dd..0000000000 +--- a/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_io.c ++++ /dev/null +@@ -1,61 +0,0 @@ +-/* +- * Copyright 2009-2020, Haiku Inc., All rights reserved. +- * Distributed under the terms of the MIT License. +- */ +- +- +-#include "pci_io.h" +-#include "pci_private.h" +-#warning RISCV64: WRITEME +- +- +-status_t +-pci_io_init() +-{ +- return B_OK; +-} +- +- +-uint8 +-pci_read_io_8(int mapped_io_addr) +-{ +- /* NOT IMPLEMENTED */ +- return 0; +-} +- +- +-void +-pci_write_io_8(int mapped_io_addr, uint8 value) +-{ +- /* NOT IMPLEMENTED */ +-} +- +- +-uint16 +-pci_read_io_16(int mapped_io_addr) +-{ +- /* NOT IMPLEMENTED */ +- return 0; +-} +- +- +-void +-pci_write_io_16(int mapped_io_addr, uint16 value) +-{ +- /* NOT IMPLEMENTED */ +-} +- +- +-uint32 +-pci_read_io_32(int mapped_io_addr) +-{ +- /* NOT IMPLEMENTED */ +- return 0; +-} +- +- +-void +-pci_write_io_32(int mapped_io_addr, uint32 value) +-{ +- /* NOT IMPLEMENTED */ +-} +diff --git a/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_io.cpp b/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_io.cpp +new file mode 100644 +index 0000000000..b82c659e71 +--- /dev/null ++++ b/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_io.cpp +@@ -0,0 +1,76 @@ ++/* ++ * Copyright 2009-2020, Haiku Inc., All rights reserved. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++ ++#include "pci_io.h" ++#include "pci_private.h" ++ ++#include ++ ++ ++extern addr_t gPCIeIoBase; ++extern size_t gPCIeIoSize; ++ ++ ++status_t ++pci_io_init() ++{ ++ dprintf("pci_io_init()\n"); ++ return B_OK; ++} ++ ++ ++uint8 ++pci_read_io_8(int mapped_io_addr) ++{ ++ dprintf("pci_read_io_8(%d)\n", mapped_io_addr); ++ volatile uint8* ptr = (uint8*)(gPCIeIoBase + mapped_io_addr); ++ return *ptr; ++} ++ ++ ++void ++pci_write_io_8(int mapped_io_addr, uint8 value) ++{ ++ dprintf("pci_write_io_8(%d)\n", mapped_io_addr); ++ volatile uint8* ptr = (uint8*)(gPCIeIoBase + mapped_io_addr); ++ *ptr = value; ++} ++ ++ ++uint16 ++pci_read_io_16(int mapped_io_addr) ++{ ++ dprintf("pci_read_io_16(%d)\n", mapped_io_addr); ++ volatile uint16* ptr = (uint16*)(gPCIeIoBase + mapped_io_addr); ++ return *ptr; ++} ++ ++ ++void ++pci_write_io_16(int mapped_io_addr, uint16 value) ++{ ++ dprintf("pci_write_io_16(%d)\n", mapped_io_addr); ++ volatile uint16* ptr = (uint16*)(gPCIeIoBase + mapped_io_addr); ++ *ptr = value; ++} ++ ++ ++uint32 ++pci_read_io_32(int mapped_io_addr) ++{ ++ dprintf("pci_read_io_32(%d)\n", mapped_io_addr); ++ volatile uint32* ptr = (uint32*)(gPCIeIoBase + mapped_io_addr); ++ return *ptr; ++} ++ ++ ++void ++pci_write_io_32(int mapped_io_addr, uint32 value) ++{ ++ dprintf("pci_write_io_32(%d)\n", mapped_io_addr); ++ volatile uint32* ptr = (uint32*)(gPCIeIoBase + mapped_io_addr); ++ *ptr = value; ++} +diff --git a/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_msi.cpp b/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_msi.cpp +new file mode 100644 +index 0000000000..d7ff27dc2f +--- /dev/null ++++ b/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_msi.cpp +@@ -0,0 +1,80 @@ ++#include "pci_msi.h" ++#include "pci_controller_private.h" ++#include ++ ++#include ++ ++ ++long gStartMsiIrq = 0; ++static uint32 sAllocatedMsiIrqs[1] = {0}; ++static uint64 sMsiData = 0; ++phys_addr_t gMsiPhysAddr = 0; ++ ++ ++static inline volatile PciDbiRegs* ++GetDbuRegs() ++{ ++ return (PciDbiRegs*)gPCIeDbiBase; ++} ++ ++ ++int32 ++AllocMsiInterrupt() ++{ ++ for (int i = 0; i < 32; i++) { ++ if (((1 << i) & sAllocatedMsiIrqs[0]) == 0) { ++ sAllocatedMsiIrqs[0] |= (1 << i); ++ GetDbuRegs()->msiIntr[0].mask &= ~(1 << i); ++ return i; ++ } ++ } ++ return B_ERROR; ++} ++ ++ ++void ++FreeMsiInterrupt(int32 irq) ++{ ++ if (irq >= 0 && irq < 32 && ((1 << irq) & sAllocatedMsiIrqs[0]) != 0) { ++ GetDbuRegs()->msiIntr[0].mask |= (1 << (uint32)irq); ++ sAllocatedMsiIrqs[0] &= ~(1 << (uint32)irq); ++ } ++} ++ ++ ++static int32 ++MsiInterruptHandler(void* arg) ++{ ++// dprintf("MsiInterruptHandler()\n"); ++ uint32 status = GetDbuRegs()->msiIntr[0].status; ++ for (int i = 0; i < 32; i++) { ++ if (((1 << i) & status) != 0) { ++// dprintf("MSI IRQ: %d (%ld)\n", i, gStartMsiIrq + i); ++ int_io_interrupt_handler(gStartMsiIrq + i, false); ++ GetDbuRegs()->msiIntr[0].status = (1 << i); ++ } ++ } ++ return B_HANDLED_INTERRUPT; ++} ++ ++ ++void ++InitPciMsi(int32 msiIrq) ++{ ++ dprintf("InitPciMsi()\n"); ++ dprintf(" msiIrq: %" B_PRId32 "\n", msiIrq); ++ ++ physical_entry pe; ++ ASSERT_ALWAYS(get_memory_map(&sMsiData, sizeof(sMsiData), &pe, 1) >= B_OK); ++ gMsiPhysAddr = pe.address; ++ dprintf(" gMsiPhysAddr: %#" B_PRIxADDR "\n", gMsiPhysAddr); ++ GetDbuRegs()->msiAddrLo = (uint32)gMsiPhysAddr; ++ GetDbuRegs()->msiAddrHi = (uint32)(gMsiPhysAddr >> 32); ++ ++ GetDbuRegs()->msiIntr[0].enable = 0xffffffff; ++ GetDbuRegs()->msiIntr[0].mask = 0xffffffff; ++ ++ ASSERT_ALWAYS(install_io_interrupt_handler(msiIrq, MsiInterruptHandler, NULL, 0) >= B_OK); ++ ASSERT_ALWAYS(allocate_io_interrupt_vectors(32, &gStartMsiIrq, INTERRUPT_TYPE_IRQ) >= B_OK); ++ dprintf(" gStartMsiIrq: %ld\n", gStartMsiIrq); ++} +diff --git a/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_msi.h b/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_msi.h +new file mode 100644 +index 0000000000..4f7a9ba991 +--- /dev/null ++++ b/src/add-ons/kernel/bus_managers/pci/arch/riscv64/pci_msi.h +@@ -0,0 +1,18 @@ ++#ifndef _PCI_MSI_H_ ++#define _PCI_MSI_H_ ++ ++ ++#include ++ ++ ++extern long gStartMsiIrq; ++extern phys_addr_t gMsiPhysAddr; ++ ++ ++int32 AllocMsiInterrupt(); ++void FreeMsiInterrupt(int32 irq); ++ ++void InitPciMsi(int32 msiIrq); ++ ++ ++#endif // _PCI_MSI_H_ +diff --git a/src/add-ons/kernel/bus_managers/pci/pci.cpp b/src/add-ons/kernel/bus_managers/pci/pci.cpp +index 346d8b5452..baa1e76a79 100644 +--- a/src/add-ons/kernel/bus_managers/pci/pci.cpp ++++ b/src/add-ons/kernel/bus_managers/pci/pci.cpp +@@ -123,10 +123,6 @@ pci_reserve_device(uchar virtualBus, uchar device, uchar function, + //TRACE(("%s(%d [%d:%d], %d, %d, %s, %p)\n", __FUNCTION__, virtualBus, + // domain, bus, device, function, driverName, nodeCookie)); + +- device_attr matchPCIRoot[] = { +- {B_DEVICE_PRETTY_NAME, B_STRING_TYPE, {string: "PCI"}}, +- {NULL} +- }; + device_attr matchThis[] = { + // info about device + {B_DEVICE_BUS, B_STRING_TYPE, {string: "pci"}}, +@@ -152,19 +148,14 @@ pci_reserve_device(uchar virtualBus, uchar device, uchar function, + {"legacy_driver_cookie", B_UINT64_TYPE, {ui64: (uint64)nodeCookie}}, + {NULL} + }; +- device_node *root, *pci, *node, *legacy; ++ device_node *node, *legacy; + + status = B_DEVICE_NOT_FOUND; +- root = gDeviceManager->get_root_node(); +- if (!root) +- return status; +- +- pci = NULL; +- if (gDeviceManager->get_next_child_node(root, matchPCIRoot, &pci) < B_OK) +- goto err0; ++ if (gPCIRootNode == NULL) ++ goto err1; + + node = NULL; +- if (gDeviceManager->get_next_child_node(pci, matchThis, &node) < B_OK) ++ if (gDeviceManager->get_next_child_node(gPCIRootNode, matchThis, &node) < B_OK) + goto err1; + + // common API for all legacy modules ? +@@ -181,8 +172,6 @@ pci_reserve_device(uchar virtualBus, uchar device, uchar function, + goto err3; + + gDeviceManager->put_node(node); +- gDeviceManager->put_node(pci); +- gDeviceManager->put_node(root); + + return B_OK; + +@@ -191,9 +180,6 @@ err3: + err2: + gDeviceManager->put_node(node); + err1: +- gDeviceManager->put_node(pci); +-err0: +- gDeviceManager->put_node(root); + TRACE(("pci_reserve_device for driver %s failed: %s\n", driverName, + strerror(status))); + return status; +@@ -488,7 +474,6 @@ pci_init(void) + + if (pci_controller_init() != B_OK) { + TRACE(("PCI: pci_controller_init failed\n")); +- panic("PCI: pci_controller_init failed\n"); + return B_ERROR; + } + +diff --git a/src/add-ons/kernel/bus_managers/pci/pci_private.h b/src/add-ons/kernel/bus_managers/pci/pci_private.h +index 0958ab6bb4..0787b40c6d 100644 +--- a/src/add-ons/kernel/bus_managers/pci/pci_private.h ++++ b/src/add-ons/kernel/bus_managers/pci/pci_private.h +@@ -39,6 +39,8 @@ typedef struct pci_root_module_info { + extern pci_root_module_info gPCIRootModule; + extern pci_device_module_info gPCIDeviceModule; + ++extern device_node* gPCIRootNode; ++ + + #ifdef __cplusplus + extern "C" { +diff --git a/src/add-ons/kernel/bus_managers/pci/pci_root.cpp b/src/add-ons/kernel/bus_managers/pci/pci_root.cpp +index 84382fb6db..7a7131eec4 100644 +--- a/src/add-ons/kernel/bus_managers/pci/pci_root.cpp ++++ b/src/add-ons/kernel/bus_managers/pci/pci_root.cpp +@@ -8,6 +8,7 @@ + + #include + #include ++#include + + #include + +@@ -19,16 +20,34 @@ + #define PCI_ROOT_MODULE_NAME "bus_managers/pci/root/driver_v1" + + ++device_node* gPCIRootNode = NULL; ++ ++ + static float + pci_root_supports_device(device_node* parent) + { +- // make sure parent is really device root + const char* bus; +- if (gDeviceManager->get_attr_string(parent, B_DEVICE_BUS, &bus, false)) +- return B_ERROR; +- +- if (strcmp(bus, "root")) +- return 0.0; ++ if (gDeviceManager->get_attr_string(parent, B_DEVICE_BUS, &bus, false) < B_OK) ++ return -1.0f; ++ ++#ifdef __riscv ++ const char* compatible; ++ if (gDeviceManager->get_attr_string(parent, "fdt/compatible", &compatible, ++ false) < B_OK) ++ return -1.0f; ++ ++ if (strcmp(bus, "fdt") != 0) ++ return 0.0f; ++ ++ if ( ++ strcmp(compatible, "pci-host-ecam-generic") != 0 && ++ strcmp(compatible, "sifive,fu740-pcie") != 0 ++ ) ++ return 0.0f; ++#else ++ if (strcmp(bus, "root") != 0) ++ return 0.0f; ++#endif + + return 1.0; + } +@@ -37,6 +56,7 @@ pci_root_supports_device(device_node* parent) + static status_t + pci_root_register_device(device_node* parent) + { ++ dprintf("pci_root_register_device()\n"); + // XXX how do we handle this for PPC? + // I/O port for PCI config space address + #define PCI_CONFIG_ADDRESS 0xcf8 +@@ -59,6 +79,7 @@ pci_root_register_device(device_node* parent) + static status_t + pci_root_register_child_devices(void* cookie) + { ++ dprintf("pci_root_register_child_devices()\n"); + device_node* node = (device_node*)cookie; + + pci_info info; +@@ -66,7 +87,7 @@ pci_root_register_child_devices(void* cookie) + uint8 domain; + uint8 bus; + if (gPCI->ResolveVirtualBus(info.bus, &domain, &bus) != B_OK) { +-dprintf("FAILED!!!!\n"); ++ dprintf("ResolveVirtualBus(%u) failed\n", info.bus); + continue; + } + +@@ -103,7 +124,16 @@ dprintf("FAILED!!!!\n"); + static status_t + pci_root_init(device_node* node, void** _cookie) + { ++ dprintf("pci_root_init()\n"); + *_cookie = node; ++ ++ gPCIRootNode = node; ++ ++ module_info *module; ++ status_t res = get_module(B_PCI_MODULE_NAME, &module); ++ if (res < B_OK) ++ return res; ++ + return B_OK; + } + +@@ -114,13 +144,19 @@ pci_root_std_ops(int32 op, ...) + switch (op) { + case B_MODULE_INIT: + { ++ dprintf("+pci_root\n"); ++/* + module_info *module; + return get_module(B_PCI_MODULE_NAME, &module); + // this serializes our module initialization ++*/ ++ return B_OK; + } + + case B_MODULE_UNINIT: +- return put_module(B_PCI_MODULE_NAME); ++ dprintf("-pci_root\n"); ++ // return put_module(B_PCI_MODULE_NAME); ++ return B_OK; + } + + return B_BAD_VALUE; +-- +2.30.2 + diff --git a/patchset-hrev55144/0085-boot_loader.efi-update-for-riscv64.patch b/patchset-hrev55144/0085-boot_loader.efi-update-for-riscv64.patch new file mode 100644 index 0000000..31f79fa --- /dev/null +++ b/patchset-hrev55144/0085-boot_loader.efi-update-for-riscv64.patch @@ -0,0 +1,2055 @@ +From 42bc1ffdc7741a1a1ff41cd0dcb9a960f0a6f4a0 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 02:27:06 +0900 +Subject: boot_loader.efi: update for riscv64 + +* Added MMU page table generation. + +* Added FDT device detection and passin to kernel. + +Change-Id: I89257c93c84404fd988f621b29f927ed0df3c3b1 +--- + src/system/boot/loader/Jamfile | 1 + + src/system/boot/loader/elf.cpp | 8 +- + src/system/boot/loader/kernel_args.cpp | 4 +- + src/system/boot/loader/main.cpp | 8 +- + src/system/boot/loader/vfs.cpp | 4 +- + src/system/boot/platform/efi/Jamfile | 5 +- + .../boot/platform/efi/arch/riscv64/Jamfile | 2 + + .../platform/efi/arch/riscv64/arch_mmu.cpp | 447 +++++++++++++++++- + .../platform/efi/arch/riscv64/arch_smp.cpp | 95 +++- + .../platform/efi/arch/riscv64/arch_start.cpp | 109 ++++- + .../platform/efi/arch/riscv64/arch_traps.cpp | 176 +++++++ + .../platform/efi/arch/riscv64/arch_traps.h | 55 +++ + .../efi/arch/riscv64/arch_traps_asm.S | 26 + + .../boot/platform/efi/arch/riscv64/entry.S | 24 +- + src/system/boot/platform/efi/console.cpp | 1 + + src/system/boot/platform/efi/debug.cpp | 5 +- + src/system/boot/platform/efi/dtb.cpp | 433 ++++++++++++++++- + src/system/boot/platform/efi/mmu.cpp | 25 +- + src/system/boot/platform/efi/mmu.h | 2 + + src/system/boot/platform/efi/serial.cpp | 23 +- + src/system/boot/platform/efi/serial.h | 4 + + src/system/boot/platform/efi/start.cpp | 51 +- + src/system/boot/platform/efi/video.cpp | 1 + + 23 files changed, 1444 insertions(+), 65 deletions(-) + create mode 100644 src/system/boot/platform/efi/arch/riscv64/arch_traps.cpp + create mode 100644 src/system/boot/platform/efi/arch/riscv64/arch_traps.h + create mode 100644 src/system/boot/platform/efi/arch/riscv64/arch_traps_asm.S + +diff --git a/src/system/boot/loader/Jamfile b/src/system/boot/loader/Jamfile +index a1bc9e7651..9cf9de3671 100644 +--- a/src/system/boot/loader/Jamfile ++++ b/src/system/boot/loader/Jamfile +@@ -74,6 +74,7 @@ for platform in [ MultiBootSubDirSetup ] { + { + DEFINES += + BOOT_SUPPORT_ELF64 ++ BOOT_SUPPORT_PARTITION_EFI + ; + if $(TARGET_BOOT_PLATFORM) = efi { + DEFINES += +diff --git a/src/system/boot/loader/elf.cpp b/src/system/boot/loader/elf.cpp +index 99495aaf93..450e3ec2dc 100644 +--- a/src/system/boot/loader/elf.cpp ++++ b/src/system/boot/loader/elf.cpp +@@ -299,7 +299,8 @@ ELFLoader::Load(int fd, preloaded_image* _image) + { + AddrType address = firstRegion->start; + if (Class::AllocateRegion(&address, totalSize, +- B_READ_AREA | B_WRITE_AREA, &mappedRegion) != B_OK) { ++ B_READ_AREA | B_WRITE_AREA | B_EXECUTE_AREA, &mappedRegion) ++ != B_OK) { + status = B_NO_MEMORY; + goto error1; + } +@@ -727,13 +728,12 @@ elf_relocate_image(preloaded_image* image) + #ifdef BOOT_SUPPORT_ELF64 + if (image->elf_class == ELFCLASS64) + return ELF64Loader::Relocate(image); +- else + #endif + #ifdef BOOT_SUPPORT_ELF32 ++ if (image->elf_class == ELFCLASS32) + return ELF32Loader::Relocate(image); +-#else +- return B_ERROR; + #endif ++ return B_ERROR; + } + + +diff --git a/src/system/boot/loader/kernel_args.cpp b/src/system/boot/loader/kernel_args.cpp +index b114b9eebf..5d32c3b136 100644 +--- a/src/system/boot/loader/kernel_args.cpp ++++ b/src/system/boot/loader/kernel_args.cpp +@@ -397,7 +397,7 @@ kernel_args_malloc(size_t size) + return NULL; + } + +-#ifdef _BOOT_PLATFORM_EFI ++#if defined(_BOOT_PLATFORM_EFI) || defined(__riscv) + addr_t translated_block; + platform_bootloader_address_to_kernel_address(block, &translated_block); + if (add_kernel_args_range((void *)translated_block, size) != B_OK) +@@ -418,7 +418,7 @@ kernel_args_malloc(size_t size) + sFirstFree = (void*)((addr_t)block + size); + sLast = block; + sFree = kChunkSize - size; +-#ifdef _BOOT_PLATFORM_EFI ++#if defined(_BOOT_PLATFORM_EFI) || defined(__riscv) + addr_t translated_block; + platform_bootloader_address_to_kernel_address(block, &translated_block); + if (add_kernel_args_range((void *)translated_block, kChunkSize) != B_OK) +diff --git a/src/system/boot/loader/main.cpp b/src/system/boot/loader/main.cpp +index 85c5466a26..d6b81182f9 100644 +--- a/src/system/boot/loader/main.cpp ++++ b/src/system/boot/loader/main.cpp +@@ -87,8 +87,11 @@ main(stage2_args *args) + + if (bootVolume.IsValid()) { + // we got a volume to boot from! +- load_driver_settings(args, bootVolume.RootDirectory()); + ++ // TODO: fix for riscv64 ++#ifndef __riscv ++ load_driver_settings(args, bootVolume.RootDirectory()); ++#endif + status_t status; + while ((status = load_kernel(args, bootVolume)) < B_OK) { + // loading the kernel failed, so let the user choose another +@@ -130,8 +133,11 @@ main(stage2_args *args) + gKernelArgs.ucode_data_size = 0; + platform_load_ucode(bootVolume); + ++ // TODO: fix for riscv64 ++#ifndef __riscv + // apply boot settings + apply_boot_settings(); ++#endif + + // set up kernel args version info + gKernelArgs.kernel_args_size = sizeof(kernel_args); +diff --git a/src/system/boot/loader/vfs.cpp b/src/system/boot/loader/vfs.cpp +index 403878b063..cab1e85f51 100644 +--- a/src/system/boot/loader/vfs.cpp ++++ b/src/system/boot/loader/vfs.cpp +@@ -167,7 +167,7 @@ status_t + Node::Acquire() + { + fRefCount++; +- TRACE(("%p::Acquire(), fRefCount = %ld\n", this, fRefCount)); ++ TRACE(("%p::Acquire(), fRefCount = %" B_PRId32 "\n", this, fRefCount)); + return B_OK; + } + +@@ -175,7 +175,7 @@ Node::Acquire() + status_t + Node::Release() + { +- TRACE(("%p::Release(), fRefCount = %ld\n", this, fRefCount)); ++ TRACE(("%p::Release(), fRefCount = %" B_PRId32 "\n", this, fRefCount)); + if (--fRefCount == 0) { + TRACE(("delete node: %p\n", this)); + delete this; +diff --git a/src/system/boot/platform/efi/Jamfile b/src/system/boot/platform/efi/Jamfile +index b9581b9c4c..1c615192a1 100644 +--- a/src/system/boot/platform/efi/Jamfile ++++ b/src/system/boot/platform/efi/Jamfile +@@ -4,6 +4,7 @@ UsePrivateHeaders [ FDirName kernel boot ] ; + UsePrivateHeaders [ FDirName kernel platform ] ; + UsePrivateHeaders [ FDirName kernel boot platform efi ] ; + UsePrivateHeaders [ FDirName kernel boot arch $(TARGET_KERNEL_ARCH) ] ; ++UseLibraryHeaders [ FDirName libfdt ] ; + + SubDirHdrs $(HAIKU_TOP) src add-ons kernel partitioning_systems gpt ; + +@@ -32,7 +33,9 @@ local platform_src = + serial.cpp + ; + +-local support_libs ; ++local support_libs = ++ boot_fdt.a ++; + + local platform ; + for platform in [ MultiBootSubDirSetup efi ] { +diff --git a/src/system/boot/platform/efi/arch/riscv64/Jamfile b/src/system/boot/platform/efi/arch/riscv64/Jamfile +index 464c7e47ae..f98215fb58 100644 +--- a/src/system/boot/platform/efi/arch/riscv64/Jamfile ++++ b/src/system/boot/platform/efi/arch/riscv64/Jamfile +@@ -17,6 +17,8 @@ for platform in [ MultiBootSubDirSetup efi ] { + arch_smp.cpp + arch_mmu.cpp + arch_timer.cpp ++ arch_traps.cpp ++ arch_traps_asm.S + ; + + BootMergeObject boot_platform_efi_riscv64.o : +diff --git a/src/system/boot/platform/efi/arch/riscv64/arch_mmu.cpp b/src/system/boot/platform/efi/arch/riscv64/arch_mmu.cpp +index 9a86a8590b..91a0b4a21c 100644 +--- a/src/system/boot/platform/efi/arch/riscv64/arch_mmu.cpp ++++ b/src/system/boot/platform/efi/arch/riscv64/arch_mmu.cpp +@@ -3,8 +3,453 @@ + * Released under the terms of the MIT License. + */ + ++ ++#include ++ ++#include ++#include ++#include ++#include ++ ++#include ++#include ++ ++#include "mmu.h" ++#include "efi_platform.h" ++ ++ ++extern addr_t gStackBase; ++ ++phys_addr_t sPageTable = 0; ++ ++ ++static inline ++void *VirtFromPhys(uint64_t physAdr) ++{ ++ return (void*)physAdr; ++} ++ ++ ++static uint64_t ++SignExtendVirtAdr(uint64_t virtAdr) ++{ ++ if (((uint64_t)1 << 38) & virtAdr) ++ return virtAdr | 0xFFFFFF8000000000; ++ return virtAdr; ++} ++ ++ ++static void ++WritePteFlags(uint32 flags) ++{ ++ bool first = true; ++ dprintf("{"); ++ for (uint32 i = 0; i < 32; i++) { ++ if ((1 << i) & flags) { ++ if (first) first = false; else dprintf(", "); ++ switch (i) { ++ case pteValid: dprintf("valid"); break; ++ case pteRead: dprintf("read"); break; ++ case pteWrite: dprintf("write"); break; ++ case pteExec: dprintf("exec"); break; ++ case pteUser: dprintf("user"); break; ++ case pteGlobal: dprintf("global"); break; ++ case pteAccessed: dprintf("accessed"); break; ++ case pteDirty: dprintf("dirty"); break; ++ default: dprintf("%" B_PRIu32, i); ++ } ++ } ++ } ++ dprintf("}"); ++} ++ ++ ++static void ++DumpPageWrite(uint64_t virtAdr, uint64_t physAdr, size_t size, uint64 flags, uint64& firstVirt, uint64& firstPhys, uint64& firstFlags, uint64& len) ++{ ++ if (virtAdr == firstVirt + len && physAdr == firstPhys + len && flags == firstFlags) { ++ len += size; ++ } else { ++ if (len != 0) { ++ dprintf(" 0x%08" B_PRIxADDR " - 0x%08" B_PRIxADDR, ++ firstVirt, firstVirt + (len - 1)); ++ dprintf(": 0x%08" B_PRIxADDR " - 0x%08" B_PRIxADDR ", %#" B_PRIxADDR ", ", firstPhys, firstPhys + (len - 1), len); ++ WritePteFlags(firstFlags); dprintf("\n"); ++ } ++ firstVirt = virtAdr; ++ firstPhys = physAdr; ++ firstFlags = flags; ++ len = size; ++ } ++} ++ ++ ++static void ++DumpPageTableInt(Pte* pte, uint64_t virtAdr, uint32_t level, uint64& firstVirt, uint64& firstPhys, uint64& firstFlags, uint64& len) ++{ ++ for (uint32 i = 0; i < pteCount; i++) { ++ if (((1 << pteValid) & pte[i].flags) != 0) { ++ if ((((1 << pteRead) | (1 << pteWrite) | (1 << pteExec)) & pte[i].flags) == 0) { ++ if (level == 0) ++ panic("internal page table on level 0"); ++ ++ DumpPageTableInt((Pte*)VirtFromPhys(pageSize*pte[i].ppn), ++ virtAdr + ((uint64_t)i << (pageBits + pteIdxBits*level)), ++ level - 1, firstVirt, firstPhys, firstFlags, len); ++ } else { ++ DumpPageWrite( ++ SignExtendVirtAdr(virtAdr + ((uint64_t)i << (pageBits + pteIdxBits*level))), ++ pte[i].ppn * B_PAGE_SIZE, ++ 1 << (pageBits + pteIdxBits*level), ++ pte[i].flags, ++ firstVirt, firstPhys, firstFlags, len); ++ } ++ } ++ } ++} ++ ++ ++static int ++DumpPageTable(uint64 satp) ++{ ++ SatpReg satpReg(satp); ++ Pte* root = (Pte*)VirtFromPhys(satpReg.ppn * B_PAGE_SIZE); ++ ++ dprintf("PageTable:\n"); ++ uint64 firstVirt = 0; ++ uint64 firstPhys = 0; ++ uint64 firstFlags = 0; ++ uint64 len = 0; ++ DumpPageTableInt(root, 0, 2, firstVirt, firstPhys, firstFlags, len); ++ DumpPageWrite(0, 0, 0, 0, firstVirt, firstPhys, firstFlags, len); ++ ++ return 0; ++} ++ ++ ++static Pte* ++LookupPte(addr_t virtAdr, bool alloc) ++{ ++ Pte *pte = (Pte*)VirtFromPhys(sPageTable); ++ for (int level = 2; level > 0; level --) { ++ pte += VirtAdrPte(virtAdr, level); ++ if (((1 << pteValid) & pte->flags) == 0) { ++ if (!alloc) ++ return NULL; ++ pte->ppn = mmu_allocate_page() / B_PAGE_SIZE; ++ if (pte->ppn == 0) ++ return NULL; ++ memset((Pte*)VirtFromPhys(B_PAGE_SIZE * pte->ppn), 0, B_PAGE_SIZE); ++ pte->flags |= (1 << pteValid); ++ } ++ pte = (Pte*)VirtFromPhys(B_PAGE_SIZE * pte->ppn); ++ } ++ pte += VirtAdrPte(virtAdr, 0); ++ return pte; ++} ++ ++ ++static void ++Map(addr_t virtAdr, phys_addr_t physAdr, uint64 flags) ++{ ++ // dprintf("Map(%#" B_PRIxADDR ", %#" B_PRIxADDR ")\n", virtAdr, physAdr); ++ Pte* pte = LookupPte(virtAdr, true); ++ if (pte == NULL) panic("can't allocate page table"); ++ ++ pte->ppn = physAdr / B_PAGE_SIZE; ++ pte->flags = (1 << pteValid) | (1 << pteAccessed) | (1 << pteDirty) | flags; ++} ++ ++ ++static void ++MapRange(addr_t virtAdr, phys_addr_t physAdr, size_t size, uint64 flags) ++{ ++ dprintf("MapRange(%#" B_PRIxADDR " - %#" B_PRIxADDR ", %#" B_PRIxADDR " - %#" B_PRIxADDR ", %#" ++ B_PRIxADDR ")\n", virtAdr, virtAdr + (size - 1), physAdr, physAdr + (size - 1), size); ++ for (size_t i = 0; i < size; i += B_PAGE_SIZE) ++ Map(virtAdr + i, physAdr + i, flags); ++ ++ ASSERT_ALWAYS(insert_virtual_allocated_range(virtAdr, size) >= B_OK); ++} ++ ++ ++static void ++MapAddrRange(addr_range& range, uint64 flags) ++{ ++ if (range.size == 0) { ++ range.start = 0; ++ return; ++ } ++ ++ phys_addr_t physAdr = range.start; ++ range.start = get_next_virtual_address(range.size); ++ ++ MapRange(range.start, physAdr, range.size, flags); ++ ++ if (gKernelArgs.arch_args.num_virtual_ranges_to_keep ++ >= MAX_VIRTUAL_RANGES_TO_KEEP) ++ panic("too many virtual ranges to keep"); ++ ++ gKernelArgs.arch_args.virtual_ranges_to_keep[ ++ gKernelArgs.arch_args.num_virtual_ranges_to_keep++] = range; ++} ++ ++ ++static void ++PreallocKernelRange() ++{ ++ Pte* root = (Pte*)VirtFromPhys(sPageTable); ++ for (uint64 i = VirtAdrPte(KERNEL_BASE, 2); i <= VirtAdrPte(KERNEL_TOP, 2); ++ i++) { ++ Pte *pte = &root[i]; ++ pte->ppn = mmu_allocate_page() / B_PAGE_SIZE; ++ if (pte->ppn == 0) panic("can't alloc early physical page"); ++ memset(VirtFromPhys(B_PAGE_SIZE * pte->ppn), 0, B_PAGE_SIZE); ++ pte->flags |= (1 << pteValid); ++ } ++} ++ ++ ++uint64 ++GetSatp() ++{ ++ SatpReg satp; ++ satp.ppn = sPageTable / B_PAGE_SIZE; ++ satp.asid = 0; ++ satp.mode = satpModeSv39; ++ return satp.val; ++} ++ ++ ++static void ++GetPhysMemRange(addr_range& range) ++{ ++ phys_addr_t beg = (phys_addr_t)(-1), end = 0; ++ if (gKernelArgs.num_physical_memory_ranges <= 0) ++ beg = 0; ++ else { ++ for (size_t i = 0; i < gKernelArgs.num_physical_memory_ranges; i++) { ++ beg = std::min(beg, gKernelArgs.physical_memory_range[i].start); ++ end = std::max(end, gKernelArgs.physical_memory_range[i].start + gKernelArgs.physical_memory_range[i].size); ++ } ++ } ++ range.start = beg; ++ range.size = end - beg; ++} ++ ++ ++static void ++FillPhysicalMemoryMap(size_t memory_map_size, ++ efi_memory_descriptor *memory_map, size_t descriptor_size, ++ uint32_t descriptor_version) ++{ ++ // Add physical memory to the kernel args and update virtual addresses for ++ // EFI regions. ++ gKernelArgs.num_physical_memory_ranges = 0; ++ ++ // First scan: Add all usable ranges ++ for (size_t i = 0; i < memory_map_size / descriptor_size; ++i) { ++ efi_memory_descriptor* entry = &memory_map[i]; ++ switch (entry->Type) { ++ case EfiLoaderCode: ++ case EfiLoaderData: ++ case EfiBootServicesCode: ++ case EfiBootServicesData: ++ case EfiConventionalMemory: { ++ // Usable memory. ++ uint64_t base = entry->PhysicalStart; ++ uint64_t end = entry->PhysicalStart + entry->NumberOfPages * 4096; ++ uint64_t originalSize = end - base; ++ ++ // PMP protected memory, unusable ++ if (base == 0x80000000) ++ break; ++ ++ gKernelArgs.ignored_physical_memory ++ += originalSize - (std::max(end, base) - base); ++ ++ if (base >= end) ++ break; ++ uint64_t size = end - base; ++ ++ insert_physical_memory_range(base, size); ++ break; ++ } ++ case EfiACPIReclaimMemory: ++ // ACPI reclaim -- physical memory we could actually use later ++ break; ++ case EfiRuntimeServicesCode: ++ case EfiRuntimeServicesData: ++ entry->VirtualStart = entry->PhysicalStart; ++ break; ++ } ++ } ++ ++ uint64_t initialPhysicalMemory = total_physical_memory(); ++ ++ // Second scan: Remove everything reserved that may overlap ++ for (size_t i = 0; i < memory_map_size / descriptor_size; ++i) { ++ efi_memory_descriptor* entry = &memory_map[i]; ++ switch (entry->Type) { ++ case EfiLoaderCode: ++ case EfiLoaderData: ++ case EfiBootServicesCode: ++ case EfiBootServicesData: ++ case EfiConventionalMemory: ++ break; ++ default: ++ uint64_t base = entry->PhysicalStart; ++ uint64_t end = entry->PhysicalStart + entry->NumberOfPages * 4096; ++ remove_physical_memory_range(base, end - base); ++ } ++ } ++ ++ gKernelArgs.ignored_physical_memory ++ += initialPhysicalMemory - total_physical_memory(); ++ ++ sort_address_ranges(gKernelArgs.physical_memory_range, ++ gKernelArgs.num_physical_memory_ranges); ++} ++ ++ ++static void ++FillPhysicalAllocatedMemoryMap(size_t memory_map_size, ++ efi_memory_descriptor *memory_map, size_t descriptor_size, ++ uint32_t descriptor_version) ++{ ++ for (size_t i = 0; i < memory_map_size / descriptor_size; ++i) { ++ efi_memory_descriptor* entry = &memory_map[i]; ++ switch (entry->Type) { ++ case EfiLoaderData: ++ insert_physical_allocated_range(entry->PhysicalStart, entry->NumberOfPages * B_PAGE_SIZE); ++ break; ++ default: ++ ; ++ } ++ } ++ sort_address_ranges(gKernelArgs.physical_allocated_range, ++ gKernelArgs.num_physical_allocated_ranges); ++} ++ ++ ++static void ++IdentityMap() ++{ ++ Pte* pte = (Pte*)VirtFromPhys(sPageTable); ++ for (size_t i = 0; i < pteCount / 2; i++) { ++ pte[i].flags = (1 << pteValid) | (1 << pteRead) | (1 << pteWrite) | (1 << pteWrite) | (1 << pteExec); ++ pte[i].ppn = i * (pteCount * pteCount); ++ } ++} ++ ++ ++//#pragma mark - ++ + void + arch_mmu_init() + { +- // Stub ++} ++ ++ ++void ++arch_mmu_post_efi_setup(size_t memory_map_size, ++ efi_memory_descriptor *memory_map, size_t descriptor_size, ++ uint32_t descriptor_version) ++{ ++ FillPhysicalAllocatedMemoryMap(memory_map_size, memory_map, descriptor_size, descriptor_version); ++ ++ // Switch EFI to virtual mode, using the kernel pmap. ++ // Something involving ConvertPointer might need to be done after this? ++ // http://wiki.phoenix.com/wiki/index.php/EFI_RUNTIME_SERVICES ++ kRuntimeServices->SetVirtualAddressMap(memory_map_size, descriptor_size, ++ descriptor_version, memory_map); ++} ++ ++ ++uint64 ++arch_mmu_generate_post_efi_page_tables(size_t memory_map_size, ++ efi_memory_descriptor *memory_map, size_t descriptor_size, ++ uint32_t descriptor_version) ++{ ++ sPageTable = mmu_allocate_page(); ++ memset(VirtFromPhys(sPageTable), 0, B_PAGE_SIZE); ++ dprintf("sPageTable: %#" B_PRIxADDR "\n", sPageTable); ++ ++ if (false) { ++ IdentityMap(); ++ DumpPageTable(GetSatp()); ++ return GetSatp(); ++ } ++ ++ PreallocKernelRange(); ++ ++ gKernelArgs.num_virtual_allocated_ranges = 0; ++ gKernelArgs.arch_args.num_virtual_ranges_to_keep = 0; ++ FillPhysicalMemoryMap(memory_map_size, memory_map, descriptor_size, descriptor_version); ++ ++ addr_range physMemRange; ++ GetPhysMemRange(physMemRange); ++ dprintf("physMemRange: %#" B_PRIxADDR ", %#" B_PRIxSIZE "\n", physMemRange.start, physMemRange.size); ++ ++ // Physical memory mapping ++ gKernelArgs.arch_args.physMap.start = KERNEL_TOP + 1 - physMemRange.size; ++ gKernelArgs.arch_args.physMap.size = physMemRange.size; ++ MapRange(gKernelArgs.arch_args.physMap.start, physMemRange.start, physMemRange.size, (1 << pteRead) | (1 << pteWrite)); ++ ++ // Boot loader ++ dprintf("Boot loader:\n"); ++ for (size_t i = 0; i < memory_map_size / descriptor_size; ++i) { ++ efi_memory_descriptor* entry = &memory_map[i]; ++ switch (entry->Type) { ++ case EfiLoaderCode: ++ case EfiLoaderData: ++ MapRange(entry->VirtualStart, entry->PhysicalStart, entry->NumberOfPages * B_PAGE_SIZE, (1 << pteRead) | (1 << pteWrite) | (1 << pteExec)); ++ break; ++ default: ++ ; ++ } ++ } ++ dprintf("Boot loader stack\n"); ++ addr_t sp = Sp(); ++ addr_t stackTop = ROUNDDOWN(sp - 1024*64, B_PAGE_SIZE); ++ dprintf(" SP: %#" B_PRIxADDR "\n", sp); ++ dprintf(" gStackBase: %#" B_PRIxADDR "\n", gStackBase); ++ // MapRange(stackTop, stackTop, ROUNDUP(gStackBase, B_PAGE_SIZE) - stackTop, (1 << pteRead) | (1 << pteWrite)); ++ ++ // EFI runtime services ++ dprintf("EFI runtime services:\n"); ++ for (size_t i = 0; i < memory_map_size / descriptor_size; ++i) { ++ efi_memory_descriptor* entry = &memory_map[i]; ++ if ((entry->Attribute & EFI_MEMORY_RUNTIME) != 0) ++ MapRange(entry->VirtualStart, entry->PhysicalStart, entry->NumberOfPages * B_PAGE_SIZE, (1 << pteRead) | (1 << pteWrite) | (1 << pteExec)); ++ } ++ ++ // Memory regions ++ dprintf("Regions:\n"); ++ void* cookie = NULL; ++ addr_t virtAdr; ++ phys_addr_t physAdr; ++ size_t size; ++ while (mmu_next_region(&cookie, &virtAdr, &physAdr, &size)) { ++ MapRange(virtAdr, physAdr, size, (1 << pteRead) | (1 << pteWrite) | (1 << pteExec)); ++ } ++ ++ // Devices ++ dprintf("Devices:\n"); ++ MapAddrRange(gKernelArgs.arch_args.clint, (1 << pteRead) | (1 << pteWrite)); ++ MapAddrRange(gKernelArgs.arch_args.htif, (1 << pteRead) | (1 << pteWrite)); ++ MapAddrRange(gKernelArgs.arch_args.plic, (1 << pteRead) | (1 << pteWrite)); ++ if (gKernelArgs.arch_args.uart.kind != kUartKindNone) { ++ // !!! ++ MapRange(gKernelArgs.arch_args.uart.regs.start, gKernelArgs.arch_args.uart.regs.start, gKernelArgs.arch_args.uart.regs.size, (1 << pteRead) | (1 << pteWrite)); ++ ++ MapAddrRange(gKernelArgs.arch_args.uart.regs, ++ (1 << pteRead) | (1 << pteWrite)); ++ } ++ ++ sort_address_ranges(gKernelArgs.virtual_allocated_range, gKernelArgs.num_virtual_allocated_ranges); ++ ++ DumpPageTable(GetSatp()); ++ ++ return GetSatp(); + } +diff --git a/src/system/boot/platform/efi/arch/riscv64/arch_smp.cpp b/src/system/boot/platform/efi/arch/riscv64/arch_smp.cpp +index 84e25b57ac..f35ec105d7 100644 +--- a/src/system/boot/platform/efi/arch/riscv64/arch_smp.cpp ++++ b/src/system/boot/platform/efi/arch/riscv64/arch_smp.cpp +@@ -15,6 +15,9 @@ + #include + #include + #include ++#include ++ ++#include "mmu.h" + + + //#define TRACE_SMP +@@ -25,27 +28,108 @@ + #endif + + ++extern "C" void arch_enter_kernel(uint64 satp, struct kernel_args *kernelArgs, ++ addr_t kernelEntry, addr_t kernelStackTop); ++ ++ ++struct CpuEntryInfo { ++ uint64 satp; ++ uint64 kernelEntry; ++}; ++ ++ ++static CpuInfo sCpus[SMP_MAX_CPUS]; ++uint32 sCpuCount = 0; ++ ++ ++static void ++CpuEntry(int hartId, CpuEntryInfo* info) ++{ ++ arch_enter_kernel(info->satp, &gKernelArgs, info->kernelEntry, ++ gKernelArgs.cpu_kstack[hartId].start ++ + gKernelArgs.cpu_kstack[hartId].size); ++} ++ ++ ++void ++arch_smp_register_cpu(CpuInfo** cpu) ++{ ++ dprintf("arch_smp_register_cpu()\n"); ++ uint32 newCount = sCpuCount + 1; ++ if (newCount > SMP_MAX_CPUS) { ++ *cpu = NULL; ++ return; ++ } ++ *cpu = &sCpus[sCpuCount]; ++ sCpuCount = newCount; ++} ++ ++ + int + arch_smp_get_current_cpu(void) + { +- // One cpu for now. +- return 0; ++ return Mhartid(); + } + + + void + arch_smp_init_other_cpus(void) + { +- // One cpu for now. + gKernelArgs.num_cpus = 1; + return; ++ ++ if (get_safemode_boolean(B_SAFEMODE_DISABLE_SMP, false)) { ++ // SMP has been disabled! ++ TRACE(("smp disabled per safemode setting\n")); ++ gKernelArgs.num_cpus = 1; ++ } ++ ++ gKernelArgs.num_cpus = sCpuCount; ++ ++ if (gKernelArgs.num_cpus < 2) ++ return; ++ ++ for (uint32 i = 1; i < gKernelArgs.num_cpus; i++) { ++ // create a final stack the trampoline code will put the ap processor on ++ void * stack = NULL; ++ const size_t size = KERNEL_STACK_SIZE + KERNEL_STACK_GUARD_PAGES * B_PAGE_SIZE; ++ if (platform_allocate_region(&stack, size, 0, false) != B_OK) { ++ panic("Unable to allocate AP stack"); ++ } ++ memset(stack, 0, size); ++ gKernelArgs.cpu_kstack[i].start = fix_address((uint64_t)stack); ++ gKernelArgs.cpu_kstack[i].size = size; ++ } + } + + + void +-arch_smp_boot_other_cpus(uint32 pml4, uint64 kernel_entry) ++arch_smp_boot_other_cpus(uint64 satp, uint64 kernel_entry) + { +- // One cpu for now. ++ return; ++ ++ dprintf("arch_smp_boot_other_cpus()\n"); ++ for (uint32 i = 0; i < sCpuCount; i++) { ++ if (0 != sCpus[i].id) { ++ sbiret res; ++ dprintf("starting CPU %" B_PRIu32 "\n", sCpus[i].id); ++ ++ res = sbi_hart_get_status(sCpus[i].id); ++ dprintf("[PRE] sbi_hart_get_status() -> (%ld, %ld)\n", res.error, res.value); ++ ++ CpuEntryInfo info = {.satp = satp, .kernelEntry = kernel_entry}; ++ res = sbi_hart_start(sCpus[i].id, (addr_t)&CpuEntry, (addr_t)&info); ++ dprintf("sbi_hart_start() -> (%ld, %ld)\n", res.error, res.value); ++ ++ for (;;) { ++ res = sbi_hart_get_status(sCpus[i].id); ++ if (res.error < 0 || res.value == SBI_HART_STATE_STARTED) ++ break; ++ } ++ ++ dprintf("[POST] sbi_hart_get_status() -> (%ld, %ld)\n", res.error, res.value); ++ } ++ } + } + + +@@ -68,5 +152,4 @@ arch_smp_add_safemode_menus(Menu *menu) + void + arch_smp_init(void) + { +- // One cpu for now. + } +diff --git a/src/system/boot/platform/efi/arch/riscv64/arch_start.cpp b/src/system/boot/platform/efi/arch/riscv64/arch_start.cpp +index 17a25044f7..4b654752c2 100644 +--- a/src/system/boot/platform/efi/arch/riscv64/arch_start.cpp ++++ b/src/system/boot/platform/efi/arch/riscv64/arch_start.cpp +@@ -8,11 +8,60 @@ + #include + #include + ++#include ++ ++#include "mmu.h" ++#include "serial.h" ++#include "smp.h" + #include "efi_platform.h" ++#include "arch_traps.h" ++ ++ ++// From entry.S ++extern "C" void arch_enter_kernel(uint64 satp, struct kernel_args *kernelArgs, ++ addr_t kernelEntry, addr_t kernelStackTop); ++ ++// From arch_mmu.cpp ++extern void arch_mmu_post_efi_setup(size_t memory_map_size, ++ efi_memory_descriptor *memory_map, size_t descriptor_size, ++ uint32_t descriptor_version); ++ ++extern uint64_t arch_mmu_generate_post_efi_page_tables(size_t memory_map_size, ++ efi_memory_descriptor *memory_map, size_t descriptor_size, ++ uint32_t descriptor_version); ++ ++ ++#include + + +-extern "C" void arch_enter_kernel(struct kernel_args *kernelArgs, +- addr_t kernelEntry, addr_t kernelStackTop); ++static void UartWriteChar(volatile UARTSifiveRegs* uart, const char ch) ++{ ++ while (uart->txdata.isFull) {} ++ uart->txdata.val = ch; ++} ++ ++ ++static void UartWrite(volatile UARTSifiveRegs* uart, const char* str) ++{ ++ for (; *str != '\0'; str++) ++ UartWriteChar(uart, *str); ++} ++ ++ ++void ++MmuTest(volatile UARTSifiveRegs* uart, uint64 satp) ++{ ++ UartWrite(uart, "MmuTest()\n"); ++ ++ UartWriteChar(uart, '1'); UartWriteChar(uart, '\n'); ++ SetSatp(satp); ++ UartWriteChar(uart, '2'); UartWriteChar(uart, '\n'); ++ FlushTlbAll(); ++ UartWriteChar(uart, '3'); UartWriteChar(uart, '\n'); ++ ++ for (;;) Wfi(); ++} ++ + + void + arch_start_kernel(addr_t kernelEntry) +@@ -27,7 +76,7 @@ arch_start_kernel(addr_t kernelEntry) + size_t descriptor_size; + uint32_t descriptor_version; + if (kBootServices->GetMemoryMap(&memory_map_size, &dummy, &map_key, +- &descriptor_size, &descriptor_version) != EFI_BUFFER_TOO_SMALL) { ++ &descriptor_size, &descriptor_version) != EFI_BUFFER_TOO_SMALL) { + panic("Unable to determine size of system memory map"); + } + +@@ -43,7 +92,7 @@ arch_start_kernel(addr_t kernelEntry) + // Read (and print) the memory map. + memory_map_size = actual_memory_map_size; + if (kBootServices->GetMemoryMap(&memory_map_size, memory_map, &map_key, +- &descriptor_size, &descriptor_version) != EFI_SUCCESS) { ++ &descriptor_size, &descriptor_version) != EFI_SUCCESS) { + panic("Unable to fetch system memory map."); + } + +@@ -52,11 +101,29 @@ arch_start_kernel(addr_t kernelEntry) + for (size_t i = 0; i < memory_map_size / descriptor_size; ++i) { + efi_memory_descriptor *entry + = (efi_memory_descriptor *)(addr + i * descriptor_size); +- dprintf(" %#lx-%#lx %#lx %#x %#lx\n", entry->PhysicalStart, +- entry->PhysicalStart + entry->NumberOfPages * B_PAGE_SIZE, +- entry->VirtualStart, entry->Type, entry->Attribute); ++ dprintf(" phys: %#lx, virt: %#lx, size: %#lx, ", ++ entry->PhysicalStart, entry->VirtualStart, ++ entry->NumberOfPages * B_PAGE_SIZE); ++ switch (entry->Type) { ++ case EfiReservedMemoryType: dprintf("reservedMemoryType"); break; ++ case EfiLoaderCode: dprintf("loaderCode"); break; ++ case EfiLoaderData: dprintf("loaderData"); break; ++ case EfiBootServicesCode: dprintf("bootServicesCode"); break; ++ case EfiBootServicesData: dprintf("bootServicesData"); break; ++ case EfiConventionalMemory: dprintf("conventionalMemory"); break; ++ case EfiACPIReclaimMemory: dprintf("ACPIReclaimMemory"); break; ++ case EfiRuntimeServicesCode: dprintf("runtimeServicesCode"); break; ++ case EfiRuntimeServicesData: dprintf("runtimeServicesData"); break; ++ default: dprintf("?(%d)", entry->Type); ++ } ++ dprintf(", attrs: %#lx\n", entry->Attribute); + } + ++ // Generate page tables for use after ExitBootServices. ++ uint64_t satp = arch_mmu_generate_post_efi_page_tables( ++ memory_map_size, memory_map, descriptor_size, descriptor_version); ++ dprintf("SATP: 0x%016" B_PRIx64 "\n", satp); ++ + // Attempt to fetch the memory map and exit boot services. + // This needs to be done in a loop, as ExitBootServices can change the + // memory map. +@@ -67,14 +134,17 @@ arch_start_kernel(addr_t kernelEntry) + // A changing memory map shouldn't affect the generated page tables, as + // they only needed to know about the maximum address, not any specific + // entry. ++#if 1 + dprintf("Calling ExitBootServices. So long, EFI!\n"); + while (true) { + if (kBootServices->ExitBootServices(kImage, map_key) == EFI_SUCCESS) { + // The console was provided by boot services, disable it. + stdout = NULL; + stderr = NULL; +- // Can we adjust gKernelArgs.platform_args.serial_base_ports[0] +- // to something fixed in qemu for debugging? ++ // Also switch to legacy serial output ++ // (may not work on all systems) ++ serial_switch_to_legacy(); ++ dprintf("Switched to legacy serial output\n"); + break; + } + +@@ -84,14 +154,27 @@ arch_start_kernel(addr_t kernelEntry) + panic("Unable to fetch system memory map."); + } + } ++#endif ++ arch_traps_init(); + + // Update EFI, generate final kernel physical memory map, etc. +- //arch_mmu_post_efi_setup(memory_map_size, memory_map, +- // descriptor_size, descriptor_version); ++ arch_mmu_post_efi_setup(memory_map_size, memory_map, ++ descriptor_size, descriptor_version); ++ ++ if (false) ++ MmuTest((volatile UARTSifiveRegs*)gKernelArgs.arch_args.uart.regs.start, satp); ++ ++ dprintf("[PRE] SetSatp()\n"); ++ SetSatp(satp); ++ dprintf("[POST] SetSatp()\n"); ++ FlushTlbAll(); ++ dprintf("[POST] FlushTlbAll()\n"); + +- //smp_boot_other_cpus(final_pml4, kernelEntry); ++ smp_boot_other_cpus(satp, kernelEntry); + + // Enter the kernel! +- arch_enter_kernel(&gKernelArgs, kernelEntry, ++ dprintf("arch_enter_kernel(satp: %#" B_PRIxADDR ", kernelArgs: %#" B_PRIxADDR ", kernelEntry: %#" B_PRIxADDR ", sp: %#" B_PRIxADDR ")\n", ++ satp, (addr_t)&gKernelArgs, (addr_t)kernelEntry, gKernelArgs.cpu_kstack[0].start + gKernelArgs.cpu_kstack[0].size); ++ arch_enter_kernel(satp, &gKernelArgs, kernelEntry, + gKernelArgs.cpu_kstack[0].start + gKernelArgs.cpu_kstack[0].size); + } +diff --git a/src/system/boot/platform/efi/arch/riscv64/arch_traps.cpp b/src/system/boot/platform/efi/arch/riscv64/arch_traps.cpp +new file mode 100644 +index 0000000000..2ffeed09ff +--- /dev/null ++++ b/src/system/boot/platform/efi/arch/riscv64/arch_traps.cpp +@@ -0,0 +1,176 @@ ++#include "arch_traps.h" ++ ++#include ++#include ++ ++ ++void ++WriteMode(int mode) ++{ ++ switch (mode) { ++ case modeU: dprintf("u"); break; ++ case modeS: dprintf("s"); break; ++ case modeM: dprintf("m"); break; ++ default: dprintf("%d", mode); ++ } ++} ++ ++ ++void ++WriteModeSet(uint32_t val) ++{ ++ bool first = true; ++ dprintf("{"); ++ for (int i = 0; i < 32; i++) { ++ if (((1LL << i) & val) != 0) { ++ if (first) first = false; else dprintf(", "); ++ WriteMode(i); ++ } ++ } ++ dprintf("}"); ++} ++ ++ ++void ++WriteExt(uint64_t val) ++{ ++ switch (val) { ++ case 0: dprintf("off"); break; ++ case 1: dprintf("initial"); break; ++ case 2: dprintf("clean"); break; ++ case 3: dprintf("dirty"); break; ++ default: dprintf("%" B_PRId64, val); ++ } ++} ++ ++ ++void ++WriteSstatus(uint64_t val) ++{ ++ SstatusReg status(val); ++ dprintf("%#" B_PRIx64, val); ++ dprintf(" ("); ++ dprintf("ie: "); WriteModeSet(status.ie); ++ dprintf(", pie: "); WriteModeSet(status.pie); ++ dprintf(", spp: "); WriteMode(status.spp); ++ dprintf(", fs: "); WriteExt(status.fs); ++ dprintf(", xs: "); WriteExt(status.xs); ++ dprintf(", sum: %d", (int)status.sum); ++ dprintf(", mxr: %d", (int)status.mxr); ++ dprintf(", uxl: %d", (int)status.uxl); ++ dprintf(", sd: %d", (int)status.sd); ++ dprintf(")"); ++} ++ ++ ++void ++WriteInterrupt(uint64_t val) ++{ ++ switch (val) { ++ case 0 + modeU: dprintf("uSoft"); break; ++ case 0 + modeS: dprintf("sSoft"); break; ++ case 0 + modeM: dprintf("mSoft"); break; ++ case 4 + modeU: dprintf("uTimer"); break; ++ case 4 + modeS: dprintf("sTimer"); break; ++ case 4 + modeM: dprintf("mTimer"); break; ++ case 8 + modeU: dprintf("uExtern"); break; ++ case 8 + modeS: dprintf("sExtern"); break; ++ case 8 + modeM: dprintf("mExtern"); break; ++ default: dprintf("%" B_PRId64, val); ++ } ++} ++ ++ ++void ++WriteInterruptSet(uint64_t val) ++{ ++ bool first = true; ++ dprintf("{"); ++ for (int i = 0; i < 64; i++) { ++ if (((1LL << i) & val) != 0) { ++ if (first) first = false; else dprintf(", "); ++ WriteInterrupt(i); ++ } ++ } ++ dprintf("}"); ++} ++ ++ ++void ++WriteCause(uint64_t cause) ++{ ++ if ((cause & causeInterrupt) == 0) { ++ dprintf("exception "); ++ switch (cause) { ++ case causeExecMisalign: dprintf("execMisalign"); break; ++ case causeExecAccessFault: dprintf("execAccessFault"); break; ++ case causeIllegalInst: dprintf("illegalInst"); break; ++ case causeBreakpoint: dprintf("breakpoint"); break; ++ case causeLoadMisalign: dprintf("loadMisalign"); break; ++ case causeLoadAccessFault: dprintf("loadAccessFault"); break; ++ case causeStoreMisalign: dprintf("storeMisalign"); break; ++ case causeStoreAccessFault: dprintf("storeAccessFault"); break; ++ case causeUEcall: dprintf("uEcall"); break; ++ case causeSEcall: dprintf("sEcall"); break; ++ case causeMEcall: dprintf("mEcall"); break; ++ case causeExecPageFault: dprintf("execPageFault"); break; ++ case causeLoadPageFault: dprintf("loadPageFault"); break; ++ case causeStorePageFault: dprintf("storePageFault"); break; ++ default: dprintf("%" B_PRId64, cause); ++ } ++ } else { ++ dprintf("interrupt "); WriteInterrupt(cause & ~causeInterrupt); ++ } ++} ++ ++ ++void ++WritePC(addr_t pc) ++{ ++ dprintf("0x%" B_PRIxADDR, pc); ++} ++ ++ ++void ++DoStackTrace(addr_t fp, addr_t pc) ++{ ++ dprintf("Stack:\n"); ++ dprintf("FP: 0x%" B_PRIxADDR, fp); ++ if (pc != 0) { ++ dprintf(", PC: "); WritePC(pc); ++ } ++ dprintf("\n"); ++ while (fp != 0) { ++ pc = *((uint64*)fp - 1); ++ fp = *((uint64*)fp - 2); ++ dprintf("FP: 0x%" B_PRIxADDR, fp); ++ dprintf(", PC: "); WritePC(pc); ++ dprintf("\n"); ++ if (pc == 0) break; ++ } ++} ++ ++ ++void ++STrap(iframe* frame) ++{ ++ uint64 cause = Scause(); ++ ++ dprintf("STrap("); WriteCause(Scause()); dprintf(")\n"); ++ dprintf(" sstatus: "); WriteSstatus(Sstatus()); dprintf("\n"); ++ dprintf(" sie: "); WriteInterruptSet(Sie()); dprintf("\n"); ++ dprintf(" sip: "); WriteInterruptSet(Sip()); dprintf("\n"); ++ dprintf(" sepc: 0x%" B_PRIxADDR "\n", Sepc()); ++ dprintf(" stval: 0x%" B_PRIxADDR "\n", Stval()); ++ dprintf(" sscratch: 0x%" B_PRIxADDR "\n", Sscratch()); ++ DoStackTrace(Fp(), Sepc()); ++ for (;;) Wfi(); ++} ++ ++ ++void ++arch_traps_init() ++{ ++ dprintf("init_arch_traps()\n"); ++ SetStvec((uint64)SVec); ++} +diff --git a/src/system/boot/platform/efi/arch/riscv64/arch_traps.h b/src/system/boot/platform/efi/arch/riscv64/arch_traps.h +new file mode 100644 +index 0000000000..20d253c749 +--- /dev/null ++++ b/src/system/boot/platform/efi/arch/riscv64/arch_traps.h +@@ -0,0 +1,55 @@ ++#ifndef _ARCH_TRAPS_H_ ++#define _ARCH_TRAPS_H_ ++ ++ ++#include ++ ++ ++struct iframe { ++ uint64 ra; ++ uint64 t6; ++ uint64 sp; ++ uint64 gp; ++ uint64 tp; ++ uint64 t0; ++ uint64 t1; ++ uint64 t2; ++ uint64 t5; ++ uint64 s1; ++ uint64 a0; ++ uint64 a1; ++ uint64 a2; ++ uint64 a3; ++ uint64 a4; ++ uint64 a5; ++ uint64 a6; ++ uint64 a7; ++ uint64 s2; ++ uint64 s3; ++ uint64 s4; ++ uint64 s5; ++ uint64 s6; ++ uint64 s7; ++ uint64 s8; ++ uint64 s9; ++ uint64 s10; ++ uint64 s11; ++ uint64 t3; ++ uint64 t4; ++ uint64 fp; ++ uint64 epc; ++}; ++ ++ ++extern "C" { ++ ++void SVec(); ++void STrap(iframe* frame); ++ ++}; ++ ++ ++void arch_traps_init(); ++ ++ ++#endif // _ARCH_TRAPS_H_ +diff --git a/src/system/boot/platform/efi/arch/riscv64/arch_traps_asm.S b/src/system/boot/platform/efi/arch/riscv64/arch_traps_asm.S +new file mode 100644 +index 0000000000..aecd1987d6 +--- /dev/null ++++ b/src/system/boot/platform/efi/arch/riscv64/arch_traps_asm.S +@@ -0,0 +1,26 @@ ++/* ++ * Copyright 2021, Haiku, Inc. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++ ++#include ++ ++ ++.globl SVec ++.type SVec, @function ++.align 4 ++SVec: ++ PushTrapFrame ++ sd fp, 2*8(sp) ++ csrr t0, sepc ++ sd t0, 31*8(sp) ++ ++ mv a0, sp ++ call STrap ++ ++ ld t0, 31*8(sp) ++ csrw sepc, t0 ++ PopTrapFrame ++ sret ++.size SVec, .-SVec +diff --git a/src/system/boot/platform/efi/arch/riscv64/entry.S b/src/system/boot/platform/efi/arch/riscv64/entry.S +index 7ae5221a49..f847b77d85 100644 +--- a/src/system/boot/platform/efi/arch/riscv64/entry.S ++++ b/src/system/boot/platform/efi/arch/riscv64/entry.S +@@ -7,24 +7,30 @@ + + .text + +-/* status_t arch_enter_kernel(struct kernel_args *kernelArgs, ++/* status_t arch_enter_kernel(addr_t satp, struct kernel_args *kernelArgs, + addr_t kernelEntry, addr_t kernelStackTop); + +- a0 - kernelArgs +- a1 - kernelEntry +- a2 - kernelStackTop ++ a0 - SATP register value ++ a1 - kernelArgs ++ a2 - kernelEntry ++ a3 - kernelStackTop + */ + FUNCTION(arch_enter_kernel): ++ csrw satp, a0 ++ sfence.vma ++ + // set the kernel stack +- mv sp,a2 ++ mv sp, a3 ++ li fp, 0 ++ li ra, 0 + + // Setup kernel args +- //mv a0,a0 // kernelArgs +- mv a4,a1 +- li a1,0 // currentCPU=0 ++ mv a0, a1 // kernelArgs ++ mv t0, a2 ++ li a1, 0 // currentCPU=0 + + // call the kernel +- jr a4 ++ jr t0 + + // return + li a0,-1 // B_ERROR +diff --git a/src/system/boot/platform/efi/console.cpp b/src/system/boot/platform/efi/console.cpp +index 1c0fea642f..b81dbadd88 100644 +--- a/src/system/boot/platform/efi/console.cpp ++++ b/src/system/boot/platform/efi/console.cpp +@@ -165,6 +165,7 @@ console_wait_for_key(void) + kBootServices->WaitForEvent(1, &event, &index); + status = kSystemTable->ConIn->ReadKeyStroke(kSystemTable->ConIn, &key); + } while (status == EFI_NOT_READY); ++ // printf("key: (char: %d, code: %d)\n", key.UnicodeChar, key.ScanCode); + + if (key.UnicodeChar > 0) + return (int) key.UnicodeChar; +diff --git a/src/system/boot/platform/efi/debug.cpp b/src/system/boot/platform/efi/debug.cpp +index 48724ad3ce..ac84fb8b75 100644 +--- a/src/system/boot/platform/efi/debug.cpp ++++ b/src/system/boot/platform/efi/debug.cpp +@@ -47,7 +47,10 @@ dprintf(const char *format, ...) + va_list args; + + va_start(args, format); +- dprintf_args(format, args); ++ if (true) ++ dprintf_args(format, args); ++ else ++ vprintf(format, args); + va_end(args); + } + +diff --git a/src/system/boot/platform/efi/dtb.cpp b/src/system/boot/platform/efi/dtb.cpp +index 1c8744523a..4df865413d 100644 +--- a/src/system/boot/platform/efi/dtb.cpp ++++ b/src/system/boot/platform/efi/dtb.cpp +@@ -11,10 +11,18 @@ + #include + #include + #include ++#include ++#include ++#include + + #include + ++extern "C" { ++#include ++} ++ + #include "efi_platform.h" ++#include "serial.h" + + + #define INFO(x...) dprintf("efi/fdt: " x) +@@ -24,23 +32,377 @@ + static void* sDtbTable = NULL; + static uint32 sDtbSize = 0; + ++static uint32 sBootHart = 0; ++static uint64 sTimerFrequrency = 10000000; ++ ++static addr_range sPlic = {0}; ++static addr_range sClint = {0}; ++static ArchUart sUart = {.kind = kUartKindNone}; ++ ++ ++DebugUART8250* ++arch_get_uart_8250(addr_t base, int64 clock) ++{ ++ static char buffer[sizeof(DebugUART8250)]; ++ DebugUART8250* uart = new(buffer) DebugUART8250(base, clock); ++ return uart; ++} ++ ++ ++ArchUARTSifive* ++arch_get_uart_sifive(addr_t base, int64 clock) ++{ ++ static char buffer[sizeof(ArchUARTSifive)]; ++ ArchUARTSifive* uart = new(buffer) ArchUARTSifive(base, clock); ++ return uart; ++} ++ ++ ++static void WriteString(const char *str) {dprintf("%s", str);} ++static void WriteLn() {dprintf("\n");} ++static void WriteHex(uint64_t val, int n) {dprintf("%08" B_PRIx64, val);} ++static void WriteInt(int64_t val) {dprintf("%" B_PRId64, val);} ++ ++ ++static void WriteStringList(const char* prop, size_t size) ++{ ++ bool first = true; ++ const char* propEnd = prop + size; ++ while (propEnd - prop > 0) { ++ if (first) first = false; else WriteString(", "); ++ int curLen = strlen(prop); ++ WriteString("'"); ++ WriteString(prop); ++ WriteString("'"); ++ prop += curLen + 1; ++ } ++} ++ ++ ++static void DumpFdt(const void *fdt) ++{ ++ if (!fdt) ++ return; ++ ++ int err = fdt_check_header(fdt); ++ if (err) { ++ WriteString("fdt error: "); ++ WriteString(fdt_strerror(err)); ++ WriteLn(); ++ return; ++ } ++ ++ WriteString("fdt tree:"); WriteLn(); ++ ++ int node = -1; ++ int depth = -1; ++ while ((node = fdt_next_node(fdt, node, &depth)) >= 0 && depth >= 0) { ++ for (int i = 0; i < depth; i++) WriteString(" "); ++ // WriteInt(node); WriteString(", "); WriteInt(depth); WriteString(": "); ++ WriteString("node('"); ++ WriteString(fdt_get_name(fdt, node, NULL)); ++ WriteString("')"); WriteLn(); ++ depth++; ++ for (int prop = fdt_first_property_offset(fdt, node); prop >= 0; prop = fdt_next_property_offset(fdt, prop)) { ++ int len; ++ const struct fdt_property *property = fdt_get_property_by_offset(fdt, prop, &len); ++ if (property == NULL) { ++ for (int i = 0; i < depth; i++) WriteString(" "); ++ WriteString("getting prop at "); ++ WriteInt(prop); ++ WriteString(": "); ++ WriteString(fdt_strerror(len)); ++ WriteLn(); ++ break; ++ } ++ for (int i = 0; i < depth; i++) WriteString(" "); ++ WriteString("prop('"); ++ WriteString(fdt_string(fdt, fdt32_to_cpu(property->nameoff))); ++ WriteString("'): "); ++ if ( ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "compatible") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "model") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "serial-number") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "status") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "device_type") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "riscv,isa") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "mmu-type") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "format") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "bootargs") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "stdout-path") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "reg-names") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "reset-names") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "clock-names") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "clock-output-names") == 0 ++ ) { ++ WriteStringList((const char*)property->data, fdt32_to_cpu(property->len)); ++ } else if (strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "reg") == 0) { ++ for (uint64_t *it = (uint64_t*)property->data; (uint8_t*)it - (uint8_t*)property->data < fdt32_to_cpu(property->len); it += 2) { ++ if (it != (uint64_t*)property->data) WriteString(", "); ++ WriteString("(0x"); ++ WriteHex(fdt64_to_cpu(*it), 8); ++ WriteString(", 0x"); ++ WriteHex(fdt64_to_cpu(*(it + 1)), 8); ++ WriteString(")"); ++ } ++ } else if ( ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "phandle") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "clock-frequency") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "timebase-frequency") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "#address-cells") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "#size-cells") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "#interrupt-cells") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "interrupts") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "interrupt-parent") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "boot-hartid") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "riscv,ndev") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "value") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "offset") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "regmap") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "bank-width") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "width") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "height") == 0 || ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "stride") == 0 ++ ) { ++ WriteInt(fdt32_to_cpu(*(uint32_t*)property->data)); ++ } else if ( ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "interrupts-extended") == 0 ++ ) { ++ for (uint32_t *it = (uint32_t*)property->data; (uint8_t*)it - (uint8_t*)property->data < fdt32_to_cpu(property->len); it += 2) { ++ if (it != (uint32_t*)property->data) WriteString(", "); ++ WriteString("("); ++ WriteInt(fdt32_to_cpu(*it)); ++ WriteString(", "); ++ WriteInt(fdt32_to_cpu(*(it + 1))); ++ WriteString(")"); ++ } ++ } else if ( ++ strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "ranges") == 0 ++ ) { ++ WriteLn(); ++ depth++; ++ // kind ++ // child address ++ // parent address ++ // size ++ for (uint32_t *it = (uint32_t*)property->data; (uint8_t*)it - (uint8_t*)property->data < fdt32_to_cpu(property->len); it += 7) { ++ for (int i = 0; i < depth; i++) WriteString(" "); ++ uint32_t kind = fdt32_to_cpu(*(it + 0)); ++ switch (kind & 0x03000000) { ++ case 0x00000000: WriteString("CONFIG"); break; ++ case 0x01000000: WriteString("IOPORT"); break; ++ case 0x02000000: WriteString("MMIO"); break; ++ case 0x03000000: WriteString("MMIO_64BIT"); break; ++ } ++ WriteString(" (0x"); WriteHex(kind, 8); ++ WriteString("), "); ++ WriteString("child: 0x"); WriteHex(fdt64_to_cpu(*(uint64_t*)(it + 1)), 8); ++ WriteString(", "); ++ WriteString("parent: 0x"); WriteHex(fdt64_to_cpu(*(uint64_t*)(it + 3)), 8); ++ WriteString(", "); ++ WriteString("len: 0x"); WriteHex(fdt64_to_cpu(*(uint64_t*)(it + 5)), 8); ++ WriteLn(); ++ } ++ for (int i = 0; i < depth; i++) WriteString(" "); ++ depth--; ++ } else if (strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "bus-range") == 0) { ++ uint32_t *it = (uint32_t*)property->data; ++ WriteInt(fdt32_to_cpu(*it)); ++ WriteString(", "); ++ WriteInt(fdt32_to_cpu(*(it + 1))); ++ } else if (strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "interrupt-map-mask") == 0) { ++ WriteLn(); ++ depth++; ++ for (uint32_t *it = (uint32_t*)property->data; (uint8_t*)it - (uint8_t*)property->data < fdt32_to_cpu(property->len); it++) { ++ for (int i = 0; i < depth; i++) WriteString(" "); ++ WriteString("0x"); WriteHex(fdt32_to_cpu(*(uint32_t*)it), 8); ++ WriteLn(); ++ } ++ for (int i = 0; i < depth; i++) WriteString(" "); ++ depth--; ++ } else if (strcmp(fdt_string(fdt, fdt32_to_cpu(property->nameoff)), "interrupt-map") == 0) { ++ WriteLn(); ++ depth++; ++ for (uint32_t *it = (uint32_t*)property->data; (uint8_t*)it - (uint8_t*)property->data < fdt32_to_cpu(property->len); it += 6) { ++ for (int i = 0; i < depth; i++) WriteString(" "); ++ // child unit address ++ WriteString("0x"); WriteHex(fdt32_to_cpu(*(it + 0)), 8); ++ WriteString(", "); ++ WriteString("0x"); WriteHex(fdt32_to_cpu(*(it + 1)), 8); ++ WriteString(", "); ++ WriteString("0x"); WriteHex(fdt32_to_cpu(*(it + 2)), 8); ++ WriteString(", "); ++ WriteString("0x"); WriteHex(fdt32_to_cpu(*(it + 3)), 8); ++ ++ WriteString(", bus: "); WriteInt(fdt32_to_cpu(*(it + 0)) / (1 << 16) % (1 << 8)); ++ WriteString(", dev: "); WriteInt(fdt32_to_cpu(*(it + 0)) / (1 << 11) % (1 << 5)); ++ WriteString(", fn: "); WriteInt(fdt32_to_cpu(*(it + 0)) % (1 << 3)); ++ ++ WriteString(", childIrq: "); ++ // child interrupt specifier ++ WriteInt(fdt32_to_cpu(*(it + 3))); ++ WriteString(", parentIrq: ("); ++ // interrupt-parent ++ WriteInt(fdt32_to_cpu(*(it + 4))); ++ WriteString(", "); ++ WriteInt(fdt32_to_cpu(*(it + 5))); ++ WriteString(")"); ++ WriteLn(); ++ if (((it - (uint32_t*)property->data) / 6) % 4 == 3 && ((uint8_t*)(it + 6) - (uint8_t*)property->data < fdt32_to_cpu(property->len))) ++ WriteLn(); ++ } ++ for (int i = 0; i < depth; i++) WriteString(" "); ++ depth--; ++ } else { ++ WriteString("?"); ++ } ++ WriteString(" (len "); ++ WriteInt(fdt32_to_cpu(property->len)); ++ WriteString(")"); WriteLn(); ++/* ++ dump_hex(property->data, fdt32_to_cpu(property->len), depth); ++*/ ++ } ++ depth--; ++ } ++} ++ ++ + + static bool +-fdt_valid(void* fdt, uint32* size) ++HasFdtString(const char* prop, int size, const char* pattern) + { +- if (fdt == NULL) +- return false; +- uint32* words = (uint32*)fdt; +- if (B_BENDIAN_TO_HOST_INT32(words[0]) != 0xd00dfeed) ++ int patternLen = strlen(pattern); ++ const char* propEnd = prop + size; ++ while (propEnd - prop > 0) { ++ int curLen = strlen(prop); ++ if (curLen == patternLen && memcmp(prop, pattern, curLen + 1) == 0) ++ return true; ++ prop += curLen + 1; ++ } ++ return false; ++} ++ ++ ++static bool ++GetReg(const void* fdt, int node, uint32 addressCells, uint32 sizeCells, size_t idx, addr_range& range) ++{ ++ int propSize; ++ const uint8* prop = (const uint8*)fdt_getprop(fdt, node, "reg", &propSize); ++ if (prop == NULL) + return false; +- *size = B_BENDIAN_TO_HOST_INT32(words[1]); +- if (size == 0) ++ ++ size_t entrySize = 4*(addressCells + sizeCells); ++ if ((idx + 1)*entrySize > (size_t)propSize) + return false; + ++ prop += idx*entrySize; ++ ++ switch (addressCells) { ++ case 1: range.start = fdt32_to_cpu(*(uint32*)prop); prop += 4; break; ++ case 2: range.start = fdt64_to_cpu(*(uint64*)prop); prop += 8; break; ++ default: panic("unsupported addressCells"); ++ } ++ switch (sizeCells) { ++ case 1: range.size = fdt32_to_cpu(*(uint32*)prop); prop += 4; break; ++ case 2: range.size = fdt64_to_cpu(*(uint64*)prop); prop += 8; break; ++ default: panic("unsupported sizeCells"); ++ } + return true; + } + + ++static uint32 ++GetInterrupt(const void* fdt, int node, uint32 interruptCells) ++{ ++ if (uint32* prop = (uint32*)fdt_getprop(fdt, node, "interrupts-extended", NULL)) { ++ return fdt32_to_cpu(*(prop + 1)); ++ } ++ if (uint32* prop = (uint32*)fdt_getprop(fdt, node, "interrupts", NULL)) { ++ return fdt32_to_cpu(*prop); ++ } ++ dprintf("[!] no interrupt field\n"); ++ return 0; ++} ++ ++ ++static void ++HandleFdt(const void* fdt, int node, uint32 addressCells, uint32 sizeCells, ++ uint32 interruptCells /* from parent node */) ++{ ++ // TODO: handle different field sizes ++ ++ const char* name = fdt_get_name(fdt, node, NULL); ++ if (strcmp(name, "chosen") == 0) { ++ if (uint32* prop = (uint32*)fdt_getprop(fdt, node, "boot-hartid", NULL)) ++ sBootHart = fdt32_to_cpu(*prop); ++ } else if (strcmp(name, "cpus") == 0) { ++ if (uint32* prop = (uint32*)fdt_getprop(fdt, node, "timebase-frequency", NULL)) ++ sTimerFrequrency = fdt32_to_cpu(*prop); ++ } ++ ++ const char* deviceType = (const char*)fdt_getprop(fdt, node, ++ "device_type", NULL); ++ ++ if (deviceType != NULL) { ++ if (strcmp(deviceType, "cpu") == 0) { ++ CpuInfo* info; ++ arch_smp_register_cpu(&info); ++ if (info == NULL) ++ return; ++ info->id = fdt32_to_cpu(*(uint32*)fdt_getprop(fdt, node, "reg", NULL)); ++ dprintf("cpu\n"); ++ dprintf(" id: %" B_PRIu32 "\n", info->id); ++ } ++ } ++ ++ int compatibleLen; ++ const char* compatible = (const char*)fdt_getprop(fdt, node, ++ "compatible", &compatibleLen); ++ if (compatible == NULL) return; ++ if (HasFdtString(compatible, compatibleLen, "riscv,clint0")) { ++ GetReg(fdt, node, addressCells, sizeCells, 0, sClint); ++ } else if ( ++ HasFdtString(compatible, compatibleLen, "riscv,plic0") || ++ HasFdtString(compatible, compatibleLen, "sifive,plic-1.0.0") ++ ) { ++ GetReg(fdt, node, addressCells, sizeCells, 0, sPlic); ++ } else if ( ++ sUart.kind == kUartKindNone && ( ++ HasFdtString(compatible, compatibleLen, "ns16550a") || ++ HasFdtString(compatible, compatibleLen, "sifive,uart0") || ++ HasFdtString(compatible, compatibleLen, "arm,pl011") ++ ) ++ ) { ++ if (HasFdtString(compatible, compatibleLen, "ns16550a")) ++ sUart.kind = kUartKind8250; ++ else if (HasFdtString(compatible, compatibleLen, "sifive,uart0")) ++ sUart.kind = kUartKindSifive; ++ else if (HasFdtString(compatible, compatibleLen, "arm,pl011")) ++ sUart.kind = kUartKindPl011; ++ ++ GetReg(fdt, node, addressCells, sizeCells, 0, sUart.regs); ++ sUart.irq = GetInterrupt(fdt, node, interruptCells); ++ const void* prop = fdt_getprop(fdt, node, "clock-frequency", NULL); ++ sUart.clock = (prop == NULL) ? 0 : fdt32_to_cpu(*(uint32*)prop); ++ ++ switch (sUart.kind) { ++ case kUartKind8250: ++ gUART = arch_get_uart_8250(sUart.regs.start, sUart.clock); ++ break; ++ case kUartKindSifive: ++ gUART = arch_get_uart_sifive(sUart.regs.start, sUart.clock); ++ break; ++ default: ++ ; ++ } ++ ++ if (gUART != NULL) ++ gUART->InitEarly(); ++ } ++} ++ ++ + void + dtb_init() + { +@@ -56,17 +418,26 @@ dtb_init() + + void* dtbPtr = (void*)(table[i].VendorTable); + +- uint32 fdtSize = 0; +- if (!fdt_valid(dtbPtr, &fdtSize)) { +- ERROR("Invalid FDT from UEFI table %d\n", i); +- break; +- } else { +- INFO("Valid FDT from UEFI table %d (%d)\n", i, fdtSize); ++ int res = fdt_check_header(dtbPtr); ++ if (res != 0) { ++ ERROR("Invalid FDT from UEFI table %d: %s\n", i, fdt_strerror(res)); ++ continue; ++ } ++ ++ sDtbTable = dtbPtr; ++ sDtbSize = fdt_totalsize(dtbPtr); ++ ++ INFO("Valid FDT from UEFI table %d, size: %" B_PRIu32 "\n", i, sDtbSize); + +- sDtbTable = dtbPtr; +- sDtbSize = fdtSize; +- break; ++ if (false) ++ DumpFdt(sDtbTable); ++ ++ int node = -1; ++ int depth = -1; ++ while ((node = fdt_next_node(sDtbTable, node, &depth)) >= 0 && depth >= 0) { ++ HandleFdt(sDtbTable, node, 2, 2, 1); + } ++ break; + } + } + +@@ -76,7 +447,7 @@ dtb_set_kernel_args() + { + // pack into proper location if the architecture cares + if (sDtbTable != NULL) { +- #ifdef __ARM__ ++ #if defined(__ARM__) || defined(__riscv) + gKernelArgs.arch_args.fdt = kernel_args_malloc(sDtbSize); + if (gKernelArgs.arch_args.fdt != NULL) + memcpy(gKernelArgs.arch_args.fdt, sDtbTable, sDtbSize); +@@ -84,4 +455,32 @@ dtb_set_kernel_args() + ERROR("unable to malloc for fdt!\n"); + #endif + } ++ ++#ifdef __riscv ++ dprintf("bootHart: %" B_PRIu32 "\n", sBootHart); ++ gKernelArgs.arch_args.bootHart = sBootHart; ++ dprintf("timerFrequrency: %" B_PRIu64 "\n", sTimerFrequrency); ++ gKernelArgs.arch_args.timerFrequrency = sTimerFrequrency; ++ ++// gKernelArgs.arch_args.htif = {.start = 0x40008000, .size = 0x10}; ++ gKernelArgs.arch_args.htif = {.start = 0, .size = 0}; ++ gKernelArgs.arch_args.plic = sPlic; ++ gKernelArgs.arch_args.clint = sClint; ++#endif ++#if defined(__ARM__) || defined(__riscv) ++ gKernelArgs.arch_args.uart = sUart; ++ dprintf("UART:\n"); ++ dprintf(" kind: "); ++ switch (sUart.kind) { ++ case kUartKindNone: dprintf("none"); break; ++ case kUartKind8250: dprintf("8250"); break; ++ case kUartKindSifive: dprintf("sifive"); break; ++ case kUartKindPl011: dprintf("pl011"); break; ++ default: ; ++ } ++ dprintf("\n"); ++ dprintf(" regs: %#" B_PRIx64 ", %#" B_PRIx64 "\n", sUart.regs.start, sUart.regs.size); ++ dprintf(" irq: %" B_PRIu32 "\n", sUart.irq); ++ dprintf(" clock: %" B_PRIu64 "\n", sUart.clock); ++#endif + } +diff --git a/src/system/boot/platform/efi/mmu.cpp b/src/system/boot/platform/efi/mmu.cpp +index 60461b6b89..f40a5f2770 100644 +--- a/src/system/boot/platform/efi/mmu.cpp ++++ b/src/system/boot/platform/efi/mmu.cpp +@@ -124,7 +124,7 @@ platform_allocate_region(void **_address, size_t size, uint8 /* protection */, + + memory_region *region = new(std::nothrow) memory_region { + next: allocated_regions, +- vaddr: *_address == NULL ? 0 : (addr_t)*_address, ++ vaddr: 0 /* *_address == NULL ? 0 : (addr_t)*_address */, + paddr: (phys_addr_t)addr, + size: size + }; +@@ -133,6 +133,7 @@ platform_allocate_region(void **_address, size_t size, uint8 /* protection */, + kBootServices->FreePages(addr, pages); + return B_NO_MEMORY; + } ++ + //region->dprint("Allocated"); + allocated_regions = region; + *_address = (void *)region->paddr; +@@ -269,3 +270,25 @@ platform_free_region(void *address, size_t size) + panic("platform_free_region: Unknown region to free??"); + return B_ERROR; // NOT Reached + } ++ ++ ++bool ++mmu_next_region(void** cookie, addr_t* vaddr, phys_addr_t* paddr, size_t* size) ++{ ++ if (*cookie == NULL) ++ *cookie = &allocated_regions; ++ else ++ *cookie = ((memory_region*)*cookie)->next; ++ ++ memory_region* region = (memory_region*)*cookie; ++ if (region == NULL) ++ return false; ++ ++ if (region->vaddr == 0) ++ region->vaddr = get_next_virtual_address(region->size); ++ ++ *vaddr = region->vaddr; ++ *paddr = region->paddr; ++ *size = region->size; ++ return true; ++} +diff --git a/src/system/boot/platform/efi/mmu.h b/src/system/boot/platform/efi/mmu.h +index afb237dd3f..bc56fdcca6 100644 +--- a/src/system/boot/platform/efi/mmu.h ++++ b/src/system/boot/platform/efi/mmu.h +@@ -36,6 +36,8 @@ extern void mmu_init(); + + extern phys_addr_t mmu_allocate_page(); + ++bool mmu_next_region(void** cookie, addr_t* vaddr, phys_addr_t* paddr, size_t* size); ++ + extern addr_t mmu_map_physical_memory(addr_t physicalAddress, size_t size, + uint32 flags); + +diff --git a/src/system/boot/platform/efi/serial.cpp b/src/system/boot/platform/efi/serial.cpp +index 54f40ace57..f1deecf81d 100644 +--- a/src/system/boot/platform/efi/serial.cpp ++++ b/src/system/boot/platform/efi/serial.cpp +@@ -12,6 +12,7 @@ + + #include + #include ++#include + #include + #include + +@@ -41,18 +42,34 @@ enum serial_register_offsets { + static uint16 sSerialBasePort = 0x3f8; + + ++DebugUART* gUART = NULL; ++ ++ + static void + serial_putc(char ch) + { + if (!sSerialEnabled) + return; + ++ if (sSerialUsesEFI) { ++ char16_t ucsBuffer[2]; ++ ucsBuffer[0] = ch; ++ ucsBuffer[1] = 0; ++ kSystemTable->ConOut->OutputString(kSystemTable->ConOut, ucsBuffer); ++ return; ++ } ++ + if (sSerialUsesEFI) { + size_t bufSize = 1; + sSerial->Write(sSerial, &bufSize, &ch); + return; + } + ++ if (gUART != NULL) { ++ gUART->PutChar(ch); ++ return; ++ } ++ + #if defined(__x86__) || defined(__x86_64__) + while ((in8(sSerialBasePort + SERIAL_LINE_STATUS) & 0x20) == 0) + asm volatile ("pause;"); +@@ -65,7 +82,7 @@ serial_putc(char ch) + extern "C" void + serial_puts(const char* string, size_t size) + { +- if (!sSerialEnabled || (sSerial == NULL && sSerialUsesEFI)) ++ if (!sSerialEnabled /*|| (sSerial == NULL && sSerialUsesEFI)*/) + return; + + while (size-- != 0) { +@@ -118,13 +135,13 @@ serial_init(void) + } + + +-#if defined(__x86__) || defined(__x86_64__) + extern "C" void + serial_switch_to_legacy(void) + { + sSerial = NULL; + sSerialUsesEFI = false; + ++#if defined(__x86__) || defined(__x86_64__) + memset(gKernelArgs.platform_args.serial_base_ports, 0, + sizeof(uint16) * MAX_SERIAL_PORTS); + +@@ -138,5 +155,5 @@ serial_switch_to_legacy(void) + out8(divisor >> 8, sSerialBasePort + SERIAL_DIVISOR_LATCH_HIGH); + out8(3, sSerialBasePort + SERIAL_LINE_CONTROL); + // 8N1 +-} + #endif ++} +diff --git a/src/system/boot/platform/efi/serial.h b/src/system/boot/platform/efi/serial.h +index 14fd158428..3b5be8a36d 100644 +--- a/src/system/boot/platform/efi/serial.h ++++ b/src/system/boot/platform/efi/serial.h +@@ -9,6 +9,10 @@ + #include + + ++class DebugUART; ++extern DebugUART* gUART; ++ ++ + #ifdef __cplusplus + extern "C" { + #endif +diff --git a/src/system/boot/platform/efi/start.cpp b/src/system/boot/platform/efi/start.cpp +index 11659feb3d..406e99583d 100644 +--- a/src/system/boot/platform/efi/start.cpp ++++ b/src/system/boot/platform/efi/start.cpp +@@ -12,6 +12,7 @@ + #include + + #include ++#include + #include + + #include +@@ -50,6 +51,11 @@ extern "C" void _start(void); + extern "C" void efi_enter_kernel(uint64 pml4, uint64 entry_point, uint64 stack); + + ++#ifdef __riscv ++addr_t gStackBase; ++#endif ++ ++ + static void + call_ctors(void) + { +@@ -142,20 +148,53 @@ get_kernel_entry(void) + } + + ++static void ++get_kernel_regions(addr_range& text, addr_range& data) ++{ ++ if (gKernelArgs.kernel_image->elf_class == ELFCLASS64) { ++ preloaded_elf64_image *image = static_cast( ++ gKernelArgs.kernel_image.Pointer()); ++ text.start = image->text_region.start; ++ text.size = image->text_region.size; ++ data.start = image->data_region.start; ++ data.size = image->data_region.size; ++ return; ++ } else if (gKernelArgs.kernel_image->elf_class == ELFCLASS32) { ++ preloaded_elf32_image *image = static_cast( ++ gKernelArgs.kernel_image.Pointer()); ++ text.start = image->text_region.start; ++ text.size = image->text_region.size; ++ data.start = image->data_region.start; ++ data.size = image->data_region.size; ++ return; ++ } ++ panic("Unknown kernel format! Not 32-bit or 64-bit!"); ++} ++ ++ + extern "C" void + platform_start_kernel(void) + { ++#ifdef __riscv ++ gKernelArgs.arch_args.platform1 = kPlatform1Sbi; ++ gKernelArgs.arch_args.platform2 = kPlatform2Efi; ++#endif ++ + smp_init_other_cpus(); + dtb_set_kernel_args(); + + addr_t kernelEntry = get_kernel_entry(); + ++ addr_range textRegion = {.start = 0, .size = 0}, dataRegion = {.start = 0, .size = 0}; ++ get_kernel_regions(textRegion, dataRegion); ++ dprintf("kernel:\n"); ++ dprintf(" text: %#" B_PRIx64 ", %#" B_PRIx64 "\n", textRegion.start, textRegion.size); ++ dprintf(" data: %#" B_PRIx64 ", %#" B_PRIx64 "\n", dataRegion.start, dataRegion.size); ++ dprintf(" entry: %#lx\n", kernelEntry); ++ + arch_mmu_init(); + convert_kernel_args(); + +- // Save the kernel entry point address. +- dprintf("kernel entry at %#lx\n", kernelEntry); +- + // map in a kernel stack + void *stack_address = NULL; + if (platform_allocate_region(&stack_address, +@@ -166,7 +205,7 @@ platform_start_kernel(void) + gKernelArgs.cpu_kstack[0].start = fix_address((addr_t)stack_address); + gKernelArgs.cpu_kstack[0].size = KERNEL_STACK_SIZE + + KERNEL_STACK_GUARD_PAGES * B_PAGE_SIZE; +- dprintf("Kernel stack at %#lx\n", gKernelArgs.cpu_kstack[0].start); ++ dprintf("Kernel stack at %#" B_PRIx64 "\n", gKernelArgs.cpu_kstack[0].start); + + // Apply any weird EFI quirks + quirks_init(); +@@ -194,6 +233,10 @@ platform_exit(void) + extern "C" efi_status + efi_main(efi_handle image, efi_system_table *systemTable) + { ++#ifdef __riscv ++ gStackBase = Sp(); ++#endif ++ + stage2_args args; + + memset(&args, 0, sizeof(stage2_args)); +diff --git a/src/system/boot/platform/efi/video.cpp b/src/system/boot/platform/efi/video.cpp +index 3c89b570f0..168dd825d8 100644 +--- a/src/system/boot/platform/efi/video.cpp ++++ b/src/system/boot/platform/efi/video.cpp +@@ -161,6 +161,7 @@ platform_init_video(void) + efi_status status = kBootServices->LocateProtocol(&sGraphicsOutputGuid, + NULL, (void **)&sGraphicsOutput); + if (sGraphicsOutput == NULL || status != EFI_SUCCESS) { ++ dprintf("GOP protocol not found\n"); + gKernelArgs.frame_buffer.enabled = false; + sGraphicsOutput = NULL; + return B_ERROR; +-- +2.30.2 + diff --git a/patchset-hrev55144/0086-kernel-add-SiFive-UART-driver-for-riscv64.patch b/patchset-hrev55144/0086-kernel-add-SiFive-UART-driver-for-riscv64.patch new file mode 100644 index 0000000..14f52c9 --- /dev/null +++ b/patchset-hrev55144/0086-kernel-add-SiFive-UART-driver-for-riscv64.patch @@ -0,0 +1,258 @@ +From db0baf29cdd154acb09c96bea72e27f01b474bd7 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 02:29:21 +0900 +Subject: kernel: add SiFive UART driver for riscv64 + +Change-Id: I37a909b5bcdb18b3fa062961eca9ff2f5187867c +--- + .../kernel/arch/riscv64/arch_uart_sifive.h | 100 +++++++++++++++++ + src/system/kernel/arch/riscv64/Jamfile | 5 + + .../kernel/arch/riscv64/arch_uart_sifive.cpp | 106 ++++++++++++++++++ + 3 files changed, 211 insertions(+) + create mode 100644 headers/private/kernel/arch/riscv64/arch_uart_sifive.h + create mode 100644 src/system/kernel/arch/riscv64/arch_uart_sifive.cpp + +diff --git a/headers/private/kernel/arch/riscv64/arch_uart_sifive.h b/headers/private/kernel/arch/riscv64/arch_uart_sifive.h +new file mode 100644 +index 0000000000..9c236a3502 +--- /dev/null ++++ b/headers/private/kernel/arch/riscv64/arch_uart_sifive.h +@@ -0,0 +1,100 @@ ++/* ++ * Copyright 2021, Haiku, Inc. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++#ifndef _ARCH_UART_SIFIVE_H_ ++#define _ARCH_UART_SIFIVE_H_ ++ ++ ++#include ++ ++ ++// UARTSifiveRegs.ie, ip ++enum { ++ kUartSifiveTxwm = 1 << 0, ++ kUartSifiveRxwm = 1 << 1, ++}; ++ ++ ++struct UARTSifiveRegs { ++ union Txdata { ++ struct { ++ uint32 data: 8; ++ uint32 reserved: 23; ++ uint32 isFull: 1; ++ }; ++ uint32 val; ++ } txdata; ++ ++ union Rxdata { ++ struct { ++ uint32 data: 8; ++ uint32 reserved: 23; ++ uint32 isEmpty: 1; ++ }; ++ uint32 val; ++ } rxdata; ++ ++ union Txctrl { ++ struct { ++ uint32 enable: 1; ++ uint32 nstop: 1; ++ uint32 reserved1: 14; ++ uint32 cnt: 3; ++ uint32 reserved2: 13; ++ }; ++ uint32 val; ++ } txctrl; ++ ++ union Rxctrl { ++ struct { ++ uint32 enable: 1; ++ uint32 reserved1: 15; ++ uint32 cnt: 3; ++ uint32 reserved2: 13; ++ }; ++ uint32 val; ++ } rxctrl; ++ ++ uint32 ie; // interrupt enable ++ uint32 ip; // interrupt pending ++ uint32 div; ++ uint32 unused; ++}; ++ ++ ++class ArchUARTSifive : public DebugUART { ++public: ++ ArchUARTSifive(addr_t base, int64 clock); ++ ~ArchUARTSifive(); ++ ++ virtual void InitEarly(); ++ virtual void Init(); ++ virtual void InitPort(uint32 baud); ++ ++ virtual void Enable(); ++ virtual void Disable(); ++ ++ virtual int PutChar(char ch); ++ virtual int GetChar(bool wait); ++ ++ virtual void FlushTx(); ++ virtual void FlushRx(); ++ ++protected: ++ virtual void Barrier(); ++ ++ inline volatile UARTSifiveRegs* ++ Regs(); ++}; ++ ++ ++volatile UARTSifiveRegs* ++ArchUARTSifive::Regs() ++{ ++ return (volatile UARTSifiveRegs*)Base(); ++} ++ ++ ++#endif // _ARCH_UART_SIFIVE_H_ +diff --git a/src/system/kernel/arch/riscv64/Jamfile b/src/system/kernel/arch/riscv64/Jamfile +index 1a6b74b5dd..305bed6e73 100644 +--- a/src/system/kernel/arch/riscv64/Jamfile ++++ b/src/system/kernel/arch/riscv64/Jamfile +@@ -3,6 +3,8 @@ SubDir HAIKU_TOP src system kernel arch riscv64 ; + SubDirHdrs $(SUBDIR) $(DOTDOT) generic ; + UsePrivateKernelHeaders ; + ++SEARCH_SOURCE += [ FDirName $(SUBDIR) $(DOTDOT) generic ] ; ++ + KernelMergeObject kernel_arch_riscv64.o : + arch_asm.S + arch_traps.S +@@ -24,6 +26,9 @@ KernelMergeObject kernel_arch_riscv64.o : + RISCV64VMTranslationMap.cpp + Htif.cpp + sbi_syscalls.S ++ ++ debug_uart_8250.cpp ++ arch_uart_sifive.cpp + : + $(TARGET_KERNEL_PIC_CCFLAGS) -Wno-unused + : +diff --git a/src/system/kernel/arch/riscv64/arch_uart_sifive.cpp b/src/system/kernel/arch/riscv64/arch_uart_sifive.cpp +new file mode 100644 +index 0000000000..97a5ddd383 +--- /dev/null ++++ b/src/system/kernel/arch/riscv64/arch_uart_sifive.cpp +@@ -0,0 +1,106 @@ ++/* ++ * Copyright 2021, Haiku, Inc. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++#include ++ ++ ++ArchUARTSifive::ArchUARTSifive(addr_t base, int64 clock) ++ : ++ DebugUART(base, clock) ++{ ++} ++ ++ ++ArchUARTSifive::~ArchUARTSifive() ++{ ++} ++ ++ ++void ++ArchUARTSifive::InitEarly() ++{ ++ //Regs()->ie = 0; ++ //Enable(); ++} ++ ++ ++void ++ArchUARTSifive::Init() ++{ ++} ++ ++ ++void ++ArchUARTSifive::InitPort(uint32 baud) ++{ ++ uint64 quotient = (Clock() + baud - 1) / baud; ++ ++ if (quotient == 0) ++ Regs()->div = 0; ++ else ++ Regs()->div = (uint32)(quotient - 1); ++} ++ ++ ++void ++ArchUARTSifive::Enable() ++{ ++ //Regs()->txctrl.enable = 1; ++ //Regs()->rxctrl.enable = 1; ++ DebugUART::Enable(); ++} ++ ++ ++void ++ArchUARTSifive::Disable() ++{ ++ //Regs()->txctrl.enable = 0; ++ //Regs()->rxctrl.enable = 0; ++ DebugUART::Disable(); ++} ++ ++ ++int ++ArchUARTSifive::PutChar(char ch) ++{ ++ while (Regs()->txdata.isFull) {} ++ Regs()->txdata.val = ch; ++ return 0; ++} ++ ++ ++int ++ArchUARTSifive::GetChar(bool wait) ++{ ++ if (wait) { ++ uint32 val; ++ while ((val = GetChar(false)) < 0) {} ++ return val; ++ } ++ UARTSifiveRegs::Rxdata data = {.val = Regs()->rxdata.val}; ++ if (data.isEmpty) ++ return -1; ++ ++ return data.data; ++} ++ ++ ++void ++ArchUARTSifive::FlushTx() ++{ ++} ++ ++ ++void ++ArchUARTSifive::FlushRx() ++{ ++} ++ ++ ++void ++ArchUARTSifive::Barrier() ++{ ++ asm volatile ("" : : : "memory"); ++} +-- +2.30.2 + diff --git a/patchset-hrev55144/0087-radeon_hd-64-bit-fixes.patch b/patchset-hrev55144/0087-radeon_hd-64-bit-fixes.patch new file mode 100644 index 0000000..42f0c74 --- /dev/null +++ b/patchset-hrev55144/0087-radeon_hd-64-bit-fixes.patch @@ -0,0 +1,110 @@ +From 15750bfe0ffe2ff148e9f137c9f7fec1fe01bc80 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 02:39:09 +0900 +Subject: radeon_hd: 64 bit fixes + +Change-Id: If14dc31bf4c9360b5e1d0b477ba375cec8f75ba7 +--- + src/add-ons/accelerants/radeon_hd/gpu.cpp | 2 +- + src/add-ons/accelerants/radeon_hd/mode.cpp | 12 ++++++++++++ + .../drivers/graphics/radeon_hd/radeon_hd.cpp | 17 ++++++++++++++--- + 3 files changed, 27 insertions(+), 4 deletions(-) + +diff --git a/src/add-ons/accelerants/radeon_hd/gpu.cpp b/src/add-ons/accelerants/radeon_hd/gpu.cpp +index 67b4fce42a..4c3f03ac74 100644 +--- a/src/add-ons/accelerants/radeon_hd/gpu.cpp ++++ b/src/add-ons/accelerants/radeon_hd/gpu.cpp +@@ -570,7 +570,7 @@ radeon_gpu_mc_init() + } + + gInfo->fb.vramStart = vramBase; +- gInfo->fb.vramSize = gInfo->shared_info->frame_buffer_size * 1024; ++ gInfo->fb.vramSize = (uint64)gInfo->shared_info->frame_buffer_size * 1024; + gInfo->fb.vramEnd = (vramBase + gInfo->fb.vramSize) - 1; + } + +diff --git a/src/add-ons/accelerants/radeon_hd/mode.cpp b/src/add-ons/accelerants/radeon_hd/mode.cpp +index ec4fb04723..c122a8db21 100644 +--- a/src/add-ons/accelerants/radeon_hd/mode.cpp ++++ b/src/add-ons/accelerants/radeon_hd/mode.cpp +@@ -179,6 +179,14 @@ radeon_set_display_mode(display_mode* mode) + // TODO: multi-monitor? For now we set the mode on + // the first display found. + ++ TRACE("%s\n", __func__); ++ TRACE(" mode->space: %#" B_PRIx32 "\n", mode->space); ++ TRACE(" mode->virtual_width: %" B_PRIu16 "\n", mode->virtual_width); ++ TRACE(" mode->virtual_height: %" B_PRIu16 "\n", mode->virtual_height); ++ TRACE(" mode->h_display_start: %" B_PRIu16 "\n", mode->h_display_start); ++ TRACE(" mode->v_display_start: %" B_PRIu16 "\n", mode->v_display_start); ++ TRACE(" mode->flags: %#" B_PRIx32 "\n", mode->flags); ++ + uint8 crtcID = 0; + + if (gDisplay[crtcID]->attached == false) +@@ -277,6 +285,10 @@ radeon_get_frame_buffer_config(frame_buffer_config* config) + + config->bytes_per_row = gInfo->shared_info->bytes_per_row; + ++ TRACE(" config->frame_buffer: %#" B_PRIxADDR "\n", (addr_t)config->frame_buffer); ++ TRACE(" config->frame_buffer_dma: %#" B_PRIxADDR "\n", (addr_t)config->frame_buffer_dma); ++ TRACE(" config->bytes_per_row: %" B_PRIu32 "\n", config->bytes_per_row); ++ + return B_OK; + } + +diff --git a/src/add-ons/kernel/drivers/graphics/radeon_hd/radeon_hd.cpp b/src/add-ons/kernel/drivers/graphics/radeon_hd/radeon_hd.cpp +index eeb76d228a..03df04822f 100644 +--- a/src/add-ons/kernel/drivers/graphics/radeon_hd/radeon_hd.cpp ++++ b/src/add-ons/kernel/drivers/graphics/radeon_hd/radeon_hd.cpp +@@ -538,6 +538,9 @@ radeon_hd_init(radeon_info &info) + "Radeon %s 1002:%" B_PRIX32 "\n", __func__, info.id, + radeon_chip_name[info.chipsetID], info.pciID); + ++ set_pci_config(info.pci, PCI_command, 2, get_pci_config(info.pci, PCI_command, 2) ++ | PCI_command_io | PCI_command_memory | PCI_command_master); ++ + // *** Map shared info + AreaKeeper sharedCreator; + info.shared_area = sharedCreator.Create("radeon hd shared info", +@@ -629,9 +632,15 @@ radeon_hd_init(radeon_info &info) + info.shared_info->graphics_memory_size / 1024); + + // *** Framebuffer mapping ++ phys_addr_t frambufferPhysAdr = info.pci->u.h0.base_registers[PCI_BAR_FB]; ++ if ((info.pci->u.h0.base_register_flags[PCI_BAR_FB] & PCI_address_type) ++ == PCI_address_type_64) { ++ frambufferPhysAdr |= (uint64)info.pci->u.h0.base_registers[PCI_BAR_FB + 1] << 32; ++ } ++ TRACE("frambufferPhysAdr: %#" B_PRIxADDR "\n", frambufferPhysAdr); + AreaKeeper frambufferMapper; + info.framebuffer_area = frambufferMapper.Map("radeon hd frame buffer", +- info.pci->u.h0.base_registers[PCI_BAR_FB], ++ frambufferPhysAdr, + info.shared_info->frame_buffer_size * 1024, + B_ANY_KERNEL_ADDRESS, B_READ_AREA | B_WRITE_AREA, + (void**)&info.shared_info->frame_buffer); +@@ -640,16 +649,18 @@ radeon_hd_init(radeon_info &info) + __func__, info.id); + return info.framebuffer_area; + } ++ TRACE("frambufferVirtAdr: %#" B_PRIxADDR "\n", (addr_t)info.shared_info->frame_buffer); ++ TRACE("frambufferSize: %#" B_PRIxSIZE "\n", (size_t)info.shared_info->frame_buffer_size * 1024); + + // Turn on write combining for the frame buffer area + vm_set_area_memory_type(info.framebuffer_area, +- info.pci->u.h0.base_registers[PCI_BAR_FB], B_MTR_WC); ++ frambufferPhysAdr, B_MTR_WC); + + frambufferMapper.Detach(); + + info.shared_info->frame_buffer_area = info.framebuffer_area; + info.shared_info->frame_buffer_phys +- = info.pci->u.h0.base_registers[PCI_BAR_FB]; ++ = frambufferPhysAdr; + + // Pass common information to accelerant + info.shared_info->deviceIndex = info.id; +-- +2.30.2 + diff --git a/patchset-hrev55144/0088-ati-add-register-definition.patch b/patchset-hrev55144/0088-ati-add-register-definition.patch new file mode 100644 index 0000000..48e1a0e --- /dev/null +++ b/patchset-hrev55144/0088-ati-add-register-definition.patch @@ -0,0 +1,25 @@ +From 61812ee12b78558f38c79f66bc811988dfb30893 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 02:40:21 +0900 +Subject: ati: add register definition + +Change-Id: Ia5f786f3bf654c28b945a268ee7d32b8f3d02732 +--- + src/add-ons/accelerants/ati/rage128.h | 1 + + 1 file changed, 1 insertion(+) + +diff --git a/src/add-ons/accelerants/ati/rage128.h b/src/add-ons/accelerants/ati/rage128.h +index 1a876a9531..9444f69291 100644 +--- a/src/add-ons/accelerants/ati/rage128.h ++++ b/src/add-ons/accelerants/ati/rage128.h +@@ -164,6 +164,7 @@ + # define R128_VERT_STRETCH_RESERVED 0xf8e00000 + + #define R128_GEN_INT_CNTL 0x0040 ++#define R128_GEN_INT_STATUS 0x0044 + #define R128_GEN_RESET_CNTL 0x00f0 + # define R128_SOFT_RESET_GUI (1 << 0) + #define R128_GPIO_MONID 0x0068 +-- +2.30.2 + diff --git a/patchset-hrev55144/0089-arm-changes.patch b/patchset-hrev55144/0089-arm-changes.patch new file mode 100644 index 0000000..3c092fc --- /dev/null +++ b/patchset-hrev55144/0089-arm-changes.patch @@ -0,0 +1,579 @@ +From 13464a97c4414f70fafc78e31c2ca6e24f2a4fa4 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 02:48:32 +0900 +Subject: arm changes + +Change-Id: Iccbf199851e1e31315bd5130eb9e54621475223a +--- + headers/private/kernel/arch/arm/arch_kernel.h | 18 +- + .../kernel/arch/arm/arch_kernel_args.h | 20 +- + src/system/boot/arch/arm/Jamfile | 6 - + src/system/kernel/arch/arm/Jamfile | 4 +- + src/system/kernel/arch/arm/arch_int.cpp | 13 +- + src/system/kernel/arch/arm/arch_timer.cpp | 10 +- + src/system/kernel/arch/arm/arch_vm.cpp | 3 - + .../arch/arm/arch_vm_translation_map.cpp | 4 +- + src/system/kernel/arch/arm/soc.h | 28 +-- + src/system/ldscripts/arm/kernel.ld | 231 ++++++++++++++---- + 10 files changed, 229 insertions(+), 108 deletions(-) + +diff --git a/headers/private/kernel/arch/arm/arch_kernel.h b/headers/private/kernel/arch/arm/arch_kernel.h +index 29706219ad..b2367c615e 100644 +--- a/headers/private/kernel/arch/arm/arch_kernel.h ++++ b/headers/private/kernel/arch/arm/arch_kernel.h +@@ -10,9 +10,10 @@ + // memory layout + #define KERNEL_LOAD_BASE 0x80000000 + +-#define KERNEL_BASE 0x80000000 +-#define KERNEL_SIZE 0x80000000 +-#define KERNEL_TOP (KERNEL_BASE + (KERNEL_SIZE - 1)) ++#define USER_BASE 0x80000000 ++#define USER_BASE_ANY USER_BASE ++#define USER_SIZE 0x80000000 ++#define USER_TOP (USER_BASE + (USER_SIZE - 1)) + + /* + ** User space layout is a little special: +@@ -22,13 +23,12 @@ + ** region wont be placed there. The 64kb region assures a user space thread cannot pass + ** a buffer into the kernel as part of a syscall that would cross into kernel space. + */ +-#define USER_BASE 0x100000 +-#define USER_BASE_ANY USER_BASE +-#define USER_SIZE (0x80000000 - (0x10000 + USER_BASE)) +-#define USER_TOP (USER_BASE + (USER_SIZE - 1)) ++#define KERNEL_BASE 0x100000 ++#define KERNEL_SIZE (0x80000000 - (0x10000 + KERNEL_BASE)) ++#define KERNEL_TOP (KERNEL_BASE + (KERNEL_SIZE - 1)) + +-#define KERNEL_USER_DATA_BASE 0x60000000 +-#define USER_STACK_REGION 0x70000000 ++#define KERNEL_USER_DATA_BASE 0xE0000000 ++#define USER_STACK_REGION 0xF0000000 + #define USER_STACK_REGION_SIZE ((USER_TOP - USER_STACK_REGION) + 1) + + #endif /* _KERNEL_ARCH_ARM_KERNEL_H */ +diff --git a/headers/private/kernel/arch/arm/arch_kernel_args.h b/headers/private/kernel/arch/arm/arch_kernel_args.h +index 9758ea7035..fcc34c3fa9 100644 +--- a/headers/private/kernel/arch/arm/arch_kernel_args.h ++++ b/headers/private/kernel/arch/arm/arch_kernel_args.h +@@ -15,6 +15,23 @@ + + #define _PACKED __attribute__((packed)) + ++ ++enum { ++ kUartKindNone, ++ kUartKind8250, ++ kUartKindSifive, ++ kUartKindPl011, ++}; ++ ++ ++typedef struct { ++ uint32 kind; ++ addr_range regs; ++ uint32 irq; ++ int64 clock; ++} _PACKED ArchUart; ++ ++ + // kernel args + typedef struct { + int cpu_type; +@@ -28,9 +45,10 @@ typedef struct { + uint32 vir_pgdir; + uint32 next_pagetable; + +- // needed for UEFI, otherwise kernel acpi support can't find ACPI root + FixedWidthPointer acpi_root; + FixedWidthPointer fdt; ++ ++ ArchUart uart; + } _PACKED arch_kernel_args; + + #endif /* KERNEL_ARCH_ARM_KERNEL_ARGS_H */ +diff --git a/src/system/boot/arch/arm/Jamfile b/src/system/boot/arch/arm/Jamfile +index 01d8481c9a..44b9a114b6 100644 +--- a/src/system/boot/arch/arm/Jamfile ++++ b/src/system/boot/arch/arm/Jamfile +@@ -20,11 +20,6 @@ local kernelArchSources = + arch_uart_8250.cpp + ; + +-local kernelDebugSources = +- blue_screen.cpp +- frame_buffer_console.cpp +-; +- + local kernelGenericDriverSources = + debug_uart_8250.cpp + ; +@@ -42,7 +37,6 @@ for platform in [ MultiBootSubDirSetup u-boot efi ] { + + # Reuse a subset of kernel debugging. + kernel_stubs.cpp +- $(kernelDebugSources) + + $(librootGenericSources) + $(librootArchSources) +diff --git a/src/system/kernel/arch/arm/Jamfile b/src/system/kernel/arch/arm/Jamfile +index e7eca39cee..96675d3085 100644 +--- a/src/system/kernel/arch/arm/Jamfile ++++ b/src/system/kernel/arch/arm/Jamfile +@@ -38,8 +38,8 @@ KernelMergeObject kernel_arch_arm.o : + # SoC minimal kernel-required support + # (timers, interrupts, rtc?) + soc.cpp +- soc_pxa.cpp +- soc_omap3.cpp ++ #soc_pxa.cpp ++ #soc_omap3.cpp + + # paging + arm_physical_page_mapper_large_memory.cpp +diff --git a/src/system/kernel/arch/arm/arch_int.cpp b/src/system/kernel/arch/arm/arch_int.cpp +index d7184dc6f9..7087e1fc71 100644 +--- a/src/system/kernel/arch/arm/arch_int.cpp ++++ b/src/system/kernel/arch/arm/arch_int.cpp +@@ -33,8 +33,8 @@ + #include + #include "soc.h" + +-#include "soc_pxa.h" +-#include "soc_omap3.h" ++//#include "soc_pxa.h" ++//#include "soc_omap3.h" + + #define TRACE_ARCH_INT + #ifdef TRACE_ARCH_INT +@@ -54,7 +54,6 @@ static area_id sVectorPageArea; + static void *sVectorPageAddress; + static area_id sUserVectorPageArea; + static void *sUserVectorPageAddress; +-static fdt_module_info *sFdtModule; + + // An iframe stack used in the early boot process when we don't have + // threads yet. +@@ -116,6 +115,7 @@ arch_int_init(kernel_args *args) + extern "C" void arm_vector_init(void); + + ++#if 0 + static struct fdt_device_info intc_table[] = { + { + .compatible = "marvell,pxa-intc", +@@ -126,6 +126,7 @@ static struct fdt_device_info intc_table[] = { + } + }; + static int intc_count = sizeof(intc_table) / sizeof(struct fdt_device_info); ++#endif + + + status_t +@@ -164,7 +165,7 @@ arch_int_init_post_vm(kernel_args *args) + else + dprintf("Enabled high vectors\n"); + } +- ++#if 0 + status_t rc = get_module(B_FDT_MODULE_NAME, (module_info**)&sFdtModule); + if (rc != B_OK) + panic("Unable to get FDT module: %08lx!\n", rc); +@@ -172,7 +173,7 @@ arch_int_init_post_vm(kernel_args *args) + rc = sFdtModule->setup_devices(intc_table, intc_count, NULL); + if (rc != B_OK) + panic("No interrupt controllers found!\n"); +- ++#endif + return B_OK; + } + +@@ -311,7 +312,7 @@ arch_arm_data_abort(struct iframe *frame) + + enable_interrupts(); + +- vm_page_fault(far, frame->pc, isWrite, false, isUser, &newip); ++ vm_page_fault(far, frame->pc, isWrite, false, isUser, true, &newip); + + if (newip != 0) { + // the page fault handler wants us to modify the iframe to set the +diff --git a/src/system/kernel/arch/arm/arch_timer.cpp b/src/system/kernel/arch/arm/arch_timer.cpp +index f17f106b84..86daa4cd49 100644 +--- a/src/system/kernel/arch/arm/arch_timer.cpp ++++ b/src/system/kernel/arch/arm/arch_timer.cpp +@@ -22,8 +22,8 @@ + #include + #include "soc.h" + +-#include "soc_pxa.h" +-#include "soc_omap3.h" ++//#include "soc_pxa.h" ++//#include "soc_omap3.h" + + //#define TRACE_ARCH_TIMER + #ifdef TRACE_ARCH_TIMER +@@ -32,6 +32,7 @@ + # define TRACE(x) ; + #endif + ++#if 0 + static fdt_module_info *sFdtModule; + + static struct fdt_device_info intc_table[] = { +@@ -44,6 +45,7 @@ static struct fdt_device_info intc_table[] = { + } + }; + static int intc_count = sizeof(intc_table) / sizeof(struct fdt_device_info); ++#endif + + + void +@@ -67,7 +69,7 @@ int + arch_init_timer(kernel_args *args) + { + TRACE(("%s\n", __func__)); +- ++#if 0 + status_t rc = get_module(B_FDT_MODULE_NAME, (module_info**)&sFdtModule); + if (rc != B_OK) + panic("Unable to get FDT module: %08lx!\n", rc); +@@ -75,7 +77,7 @@ arch_init_timer(kernel_args *args) + rc = sFdtModule->setup_devices(intc_table, intc_count, NULL); + if (rc != B_OK) + panic("No interrupt controllers found!\n"); +- ++#endif + return B_OK; + } + +diff --git a/src/system/kernel/arch/arm/arch_vm.cpp b/src/system/kernel/arch/arm/arch_vm.cpp +index a17f317d70..f41719be8d 100644 +--- a/src/system/kernel/arch/arm/arch_vm.cpp ++++ b/src/system/kernel/arch/arm/arch_vm.cpp +@@ -101,8 +101,5 @@ arch_vm_unset_memory_type(VMArea *area) + status_t + arch_vm_set_memory_type(VMArea *area, phys_addr_t physicalBase, uint32 type) + { +- if (type != 0) +- dprintf("%s: undefined type %lx!\n", __PRETTY_FUNCTION__, type); +- + return B_OK; + } +diff --git a/src/system/kernel/arch/arm/arch_vm_translation_map.cpp b/src/system/kernel/arch/arm/arch_vm_translation_map.cpp +index a21a7e3d09..42cace63a0 100644 +--- a/src/system/kernel/arch/arm/arch_vm_translation_map.cpp ++++ b/src/system/kernel/arch/arm/arch_vm_translation_map.cpp +@@ -17,7 +17,7 @@ + //#include "paging/pae/ARMPagingMethodPAE.h" + + +-//#define TRACE_VM_TMAP ++#define TRACE_VM_TMAP + #ifdef TRACE_VM_TMAP + # define TRACE(x...) dprintf(x) + #else +@@ -145,6 +145,8 @@ bool + arch_vm_translation_map_is_kernel_page_accessible(addr_t virtualAddress, + uint32 protection) + { ++ return true; ++ + if (!gARMPagingMethod) + return true; + +diff --git a/src/system/kernel/arch/arm/soc.h b/src/system/kernel/arch/arm/soc.h +index 4b1f4e8add..80398121f1 100644 +--- a/src/system/kernel/arch/arm/soc.h ++++ b/src/system/kernel/arch/arm/soc.h +@@ -20,19 +20,11 @@ public: + return sInstance; + } + +-protected: +- InterruptController(fdt_module_info *fdtModule, fdt_device_node node) +- : fFDT(fdtModule), fNode(node) { +- if (sInstance) { +- panic("Multiple InterruptController objects created; that is currently unsupported!"); +- } +- sInstance = this; ++ static void Install(InterruptController* instance) { ++ sInstance = instance; + } + +- // Keep our node around as we might want to grab attributes from it +- fdt_module_info *fFDT; +- fdt_device_node fNode; +- ++private: + static InterruptController *sInstance; + }; + +@@ -49,19 +41,11 @@ public: + return sInstance; + } + +-protected: +- HardwareTimer(fdt_module_info *fdtModule, fdt_device_node node) +- : fFDT(fdtModule), fNode(node) { +- if (sInstance) { +- panic("Multiple HardwareTimer objects created; that is currently unsupported!"); +- } +- sInstance = this; ++ static void Install(HardwareTimer* instance) { ++ sInstance = instance; + } + +- // Keep our node around as we might want to grab attributes from it +- fdt_module_info *fFDT; +- fdt_device_node fNode; +- ++private: + static HardwareTimer *sInstance; + }; + +diff --git a/src/system/ldscripts/arm/kernel.ld b/src/system/ldscripts/arm/kernel.ld +index c697ca00e2..a54f2bfd86 100644 +--- a/src/system/ldscripts/arm/kernel.ld ++++ b/src/system/ldscripts/arm/kernel.ld +@@ -4,59 +4,182 @@ OUTPUT_ARCH(arm) + ENTRY(_start) + SECTIONS + { +- . = 0x80000000 + SIZEOF_HEADERS; ++ . = 0x80000000 + SIZEOF_HEADERS; + +- .interp : { *(.interp) } +- .hash : { *(.hash) } +- .dynsym : { *(.dynsym) } +- .dynstr : { *(.dynstr) } +- .rela.text : { *(.rela.text .rela.text.* .rela.gnu.linkonce.t.*) } +- .rela.data : { *(.rela.data .rela.data.* .rela.gnu.linkonce.d.*) } +- .rela.rodata : { *(.rela.rodata .rela.rodata.* .rela.gnu.linkonce.r.*) } +- .rela.got : { *(.rela.got) } +- .rela.ctors : { *(.rela.ctors) } +- .rela.dtors : { *(.rela.dtors) } +- .rela.init : { *(.rela.init) } +- .rela.fini : { *(.rela.fini) } +- .rela.bss : { *(.rela.bss .rela.bss.* .rela.gnu.linkonce.b.*) } +- .rela.plt : { *(.rela.plt) } +- .init : { *(.init) } =0x9090 +- .plt : { *(.plt) } +- +- /* text/read-only data */ +- .text : { *(.text .text.* .gnu.linkonce.t.*) } =0x9090 +- +- .rodata : { *(.rodata .rodata.* .gnu.linkonce.r.*) } +- +- /* +- . = ALIGN(0x8); +- altcodepatch_begin = .; +- .altcodepatch : { *(.altcodepatch) } +- altcodepatch_end = .; +- */ +- +- /* writable data */ +- . = ALIGN (0x1000); +- __data_start = .; +- .data : { *(.data .data.* .gnu.linkonce.d.*) } +- +- . = ALIGN(0x8); +- __ctor_list = .; +- .ctors : { *(.init_array) *(.ctors) } +- __ctor_end = .; +- __dtor_list = .; +- .dtors : { *(.fini_array) *(.dtors) } +- __dtor_end = .; +- .got : { *(.got.plt) *(.got) } +- .dynamic : { *(.dynamic) } +- +- /* uninitialized data (in same segment as writable data) */ +- __bss_start = .; +- .bss : { *(.bss .bss.* .gnu.linkonce.b.*) } +- +- . = ALIGN(0x1000); +- _end = . ; +- +- /* Strip unnecessary stuff */ +- /DISCARD/ : { *(.comment .note .eh_frame) } ++ .interp : { *(.interp) } ++ .note.gnu.build-id : { *(.note.gnu.build-id) } ++ .hash : { *(.hash) } ++ .gnu.hash : { *(.gnu.hash) } ++ .dynsym : { *(.dynsym) } ++ .dynstr : { *(.dynstr) } ++ .gnu.version : { *(.gnu.version) } ++ .gnu.version_d : { *(.gnu.version_d) } ++ .gnu.version_r : { *(.gnu.version_r) } ++ .rela.dyn : ++ { ++ *(.rela.init) ++ *(.rela.text .rela.text.* .rela.gnu.linkonce.t.*) ++ *(.rela.fini) ++ *(.rela.rodata .rela.rodata.* .rela.gnu.linkonce.r.*) ++ *(.rela.data .rela.data.* .rela.gnu.linkonce.d.*) ++ *(.rela.tdata .rela.tdata.* .rela.gnu.linkonce.td.*) ++ *(.rela.tbss .rela.tbss.* .rela.gnu.linkonce.tb.*) ++ *(.rela.ctors) ++ *(.rela.dtors) ++ *(.rela.got) ++ *(.rela.sdata .rela.sdata.* .rela.gnu.linkonce.s.*) ++ *(.rela.sbss .rela.sbss.* .rela.gnu.linkonce.sb.*) ++ *(.rela.sdata2 .rela.sdata2.* .rela.gnu.linkonce.s2.*) ++ *(.rela.sbss2 .rela.sbss2.* .rela.gnu.linkonce.sb2.*) ++ *(.rela.bss .rela.bss.* .rela.gnu.linkonce.b.*) ++ PROVIDE_HIDDEN (__rela_iplt_start = .); ++ *(.rela.iplt) ++ PROVIDE_HIDDEN (__rela_iplt_end = .); ++ } ++ .rela.plt : ++ { ++ *(.rela.plt) ++ } ++ .init : ++ { ++ KEEP (*(SORT_NONE(.init))) ++ } ++ .plt : { *(.plt) } ++ .iplt : { *(.iplt) } ++ .text : ++ { ++ *(.text.unlikely .text.*_unlikely .text.unlikely.*) ++ *(.text.exit .text.exit.*) ++ *(.text.startup .text.startup.*) ++ *(.text.hot .text.hot.*) ++ *(.text .stub .text.* .gnu.linkonce.t.*) ++ /* .gnu.warning sections are handled specially by elf32.em. */ ++ *(.gnu.warning) ++ } ++ .fini : ++ { ++ KEEP (*(SORT_NONE(.fini))) ++ } ++ PROVIDE (__etext = .); ++ PROVIDE (_etext = .); ++ PROVIDE (etext = .); ++ .rodata : { *(.rodata .rodata.* .gnu.linkonce.r.*) } ++ .rodata1 : { *(.rodata1) } ++ .sdata2 : ++ { ++ *(.sdata2 .sdata2.* .gnu.linkonce.s2.*) ++ } ++ .sbss2 : { *(.sbss2 .sbss2.* .gnu.linkonce.sb2.*) } ++ .eh_frame_hdr : { *(.eh_frame_hdr) *(.eh_frame_entry .eh_frame_entry.*) } ++ .eh_frame : ONLY_IF_RO { KEEP (*(.eh_frame)) *(.eh_frame.*) } ++ .gcc_except_table : ONLY_IF_RO { *(.gcc_except_table ++ .gcc_except_table.*) } ++ .gnu_extab : ONLY_IF_RO { *(.gnu_extab*) } ++ /* Adjust the address for the data segment. We want to adjust up to ++ * the same address within the page on the next page up. */ ++ . = DATA_SEGMENT_ALIGN (CONSTANT (MAXPAGESIZE), CONSTANT (COMMONPAGESIZE)); ++ /* Exception handling */ ++ .eh_frame : ONLY_IF_RW { KEEP (*(.eh_frame)) *(.eh_frame.*) } ++ .gnu_extab : ONLY_IF_RW { *(.gnu_extab) } ++ .gcc_except_table : ONLY_IF_RW { *(.gcc_except_table .gcc_except_table.*) } ++ .exception_ranges : ONLY_IF_RW { *(.exception_ranges .exception_ranges*) } ++ /* Thread Local Storage sections */ ++ .tdata : { *(.tdata .tdata.* .gnu.linkonce.td.*) } ++ .tbss : { *(.tbss .tbss.* .gnu.linkonce.tb.*) *(.tcommon) } ++ .preinit_array : ++ { ++ PROVIDE_HIDDEN (__preinit_array_start = .); ++ KEEP (*(.preinit_array)) ++ PROVIDE_HIDDEN (__preinit_array_end = .); ++ } ++ .init_array : ++ { ++ PROVIDE_HIDDEN (__init_array_start = .); ++ KEEP (*(SORT_BY_INIT_PRIORITY(.init_array.*) SORT_BY_INIT_PRIORITY(.ctors.*))) ++ KEEP (*(.init_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .ctors)) ++ PROVIDE_HIDDEN (__init_array_end = .); ++ } ++ .fini_array : ++ { ++ PROVIDE_HIDDEN (__fini_array_start = .); ++ KEEP (*(SORT_BY_INIT_PRIORITY(.fini_array.*) SORT_BY_INIT_PRIORITY(.dtors.*))) ++ KEEP (*(.fini_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .dtors)) ++ PROVIDE_HIDDEN (__fini_array_end = .); ++ } ++ .ctors : ++ { ++ /* gcc uses crtbegin.o to find the start of ++ * the constructors, so we make sure it is ++ * first. Because this is a wildcard, it ++ * doesn't matter if the user does not ++ * actually link against crtbegin.o; the ++ * linker won't look for a file to match a ++ * wildcard. The wildcard also means that it ++ * doesn't matter which directory crtbegin.o ++ * is in. */ ++ KEEP (*crtbegin.o(.ctors)) ++ KEEP (*crtbegin?.o(.ctors)) ++ /* We don't want to include the .ctor section from ++ * the crtend.o file until after the sorted ctors. ++ * The .ctor section from the crtend file contains the ++ * end of ctors marker and it must be last */ ++ KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .ctors)) ++ KEEP (*(SORT(.ctors.*))) ++ KEEP (*(.ctors)) ++ } ++ .dtors : ++ { ++ KEEP (*crtbegin.o(.dtors)) ++ KEEP (*crtbegin?.o(.dtors)) ++ KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .dtors)) ++ KEEP (*(SORT(.dtors.*))) ++ KEEP (*(.dtors)) ++ } ++ .jcr : { KEEP (*(.jcr)) } ++ .data.rel.ro : { *(.data.rel.ro.local* .gnu.linkonce.d.rel.ro.local.*) *(.data.rel.ro .data.rel.ro.* .gnu.linkonce.d.rel.ro.*) } ++ .dynamic : { *(.dynamic) } ++ . = DATA_SEGMENT_RELRO_END (0, .); ++ .data : ++ { ++ *(.data .data.* .gnu.linkonce.d.*) ++ SORT(CONSTRUCTORS) ++ } ++ .data1 : { *(.data1) } ++ .got : { *(.got.plt) *(.igot.plt) *(.got) *(.igot) } ++ /* We want the small data sections together, so single-instruction offsets ++ * can access them all, and initialized data all before uninitialized, so ++ * we can shorten the on-disk segment size. */ ++ .sdata : ++ { ++ __global_pointer$ = . + 0x800; ++ *(.srodata.cst16) *(.srodata.cst8) *(.srodata.cst4) *(.srodata.cst2) *(.srodata .srodata.*) ++ *(.sdata .sdata.* .gnu.linkonce.s.*) ++ } ++ _edata = .; PROVIDE (edata = .); ++ . = .; ++ __bss_start = .; ++ .sbss : ++ { ++ *(.dynsbss) ++ *(.sbss .sbss.* .gnu.linkonce.sb.*) ++ *(.scommon) ++ } ++ .bss : ++ { ++ *(.dynbss) ++ *(.bss .bss.* .gnu.linkonce.b.*) ++ *(COMMON) ++ /* Align here to ensure that the .bss section occupies space up to ++ * _end. Align after .bss to ensure correct alignment even if the ++ * .bss section disappears because there are no input sections. ++ * FIXME: Why do we need it? When there is no .bss section, we don't ++ * pad the .data section. */ ++ . = ALIGN(. != 0 ? 64 / 8 : 1); ++ } ++ . = ALIGN(64 / 8); ++ . = SEGMENT_START("ldata-segment", .); ++ . = ALIGN(64 / 8); ++ _end = .; PROVIDE (end = .); ++ . = DATA_SEGMENT_END (.); ++ /DISCARD/ : { *(.note.GNU-stack) *(.gnu_debuglink) *(.gnu.lto_*) } + } +-- +2.30.2 + diff --git a/patchset-hrev55144/0090-kernel-vm_page-add-vm_page-table-dump-debugger-comma.patch b/patchset-hrev55144/0090-kernel-vm_page-add-vm_page-table-dump-debugger-comma.patch new file mode 100644 index 0000000..a132268 --- /dev/null +++ b/patchset-hrev55144/0090-kernel-vm_page-add-vm_page-table-dump-debugger-comma.patch @@ -0,0 +1,90 @@ +From ccb0c74d36da59f63d7c165be650b74733ec6035 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 02:52:02 +0900 +Subject: kernel/vm_page: add vm_page table dump debugger command + +Change-Id: I493228736f90f5e248f1d4fa3e354beb186546cb +--- + src/system/kernel/vm/vm_page.cpp | 59 ++++++++++++++++++++++++++++++++ + 1 file changed, 59 insertions(+) + +diff --git a/src/system/kernel/vm/vm_page.cpp b/src/system/kernel/vm/vm_page.cpp +index 182f791c57..93d0ab7782 100644 +--- a/src/system/kernel/vm/vm_page.cpp ++++ b/src/system/kernel/vm/vm_page.cpp +@@ -760,6 +760,63 @@ private: + #endif // VM_PAGE_ALLOCATION_TRACKING_AVAILABLE + + ++static void ++WriteVmPage(vm_page* page) ++{ ++ kprintf("0x%08" B_PRIxADDR " ", ++ (addr_t)(page->physical_page_number * B_PAGE_SIZE)); ++ switch (page->State()) { ++ case PAGE_STATE_ACTIVE: kprintf("A"); break; ++ case PAGE_STATE_INACTIVE: kprintf("I"); break; ++ case PAGE_STATE_MODIFIED: kprintf("M"); break; ++ case PAGE_STATE_CACHED: kprintf("C"); break; ++ case PAGE_STATE_FREE: kprintf("F"); break; ++ case PAGE_STATE_CLEAR: kprintf("L"); break; ++ case PAGE_STATE_WIRED: kprintf("W"); break; ++ case PAGE_STATE_UNUSED: kprintf("-"); break; ++ } ++ kprintf(" "); ++ if (page->busy) kprintf("B"); else kprintf("-"); ++ if (page->busy_writing) kprintf("W"); else kprintf("-"); ++ if (page->accessed) kprintf("A"); else kprintf("-"); ++ if (page->modified) kprintf("M"); else kprintf("-"); ++ if (page->unused) kprintf("U"); else kprintf("-"); ++ ++ kprintf(" usage:%3u", page->usage_count); ++ kprintf(" wired:%5u", page->WiredCount()); ++ ++ bool first = true; ++ vm_page_mappings::Iterator iterator = page->mappings.GetIterator(); ++ vm_page_mapping* mapping; ++ while ((mapping = iterator.Next()) != NULL) { ++ if (first) { ++ kprintf(": "); ++ first = false; ++ } else ++ kprintf(", "); ++ ++ kprintf("%" B_PRId32 " (%s)", mapping->area->id, mapping->area->name); ++ mapping = mapping->page_link.next; ++ } ++} ++ ++ ++static int ++list_pages(int argc, char **argv) ++{ ++ kprintf("page table:\n"); ++ for (page_num_t i = 0; i < sNumPages; i++) { ++ if (sPages[i].State() != PAGE_STATE_UNUSED) { ++ WriteVmPage(&sPages[i]); ++ kprintf("\n"); ++ } ++ } ++ kprintf("end of page table\n"); ++ ++ return 0; ++} ++ ++ + static int + find_page(int argc, char **argv) + { +@@ -3347,6 +3404,8 @@ vm_page_init_post_area(kernel_args *args) + PAGE_ALIGN(sNumPages * sizeof(vm_page)), B_ALREADY_WIRED, + B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA); + ++ add_debugger_command("list_pages", &list_pages, ++ "List physical page table"); + add_debugger_command("page_stats", &dump_page_stats, + "Dump statistics about page usage"); + add_debugger_command_etc("page", &dump_page, +-- +2.30.2 + diff --git a/patchset-hrev55144/0091-kernel-vm-add-kernel-user-page-access-handling-in-pa.patch b/patchset-hrev55144/0091-kernel-vm-add-kernel-user-page-access-handling-in-pa.patch new file mode 100644 index 0000000..350860c --- /dev/null +++ b/patchset-hrev55144/0091-kernel-vm-add-kernel-user-page-access-handling-in-pa.patch @@ -0,0 +1,186 @@ +From 8df45ebff7515fb8bd22eef92e9e9d33724d85d1 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 02:54:50 +0900 +Subject: kernel/vm: add kernel user page access handling in page fault handler + +Change-Id: Id20e6f1b23fb64bb0aa2eebd9d006f62e8fee0d1 +--- + headers/private/kernel/vm/vm_priv.h | 2 +- + src/system/kernel/arch/x86/arch_int.cpp | 1 + + src/system/kernel/vm/vm.cpp | 50 +++++++++++++++++-------- + 3 files changed, 36 insertions(+), 17 deletions(-) + +diff --git a/headers/private/kernel/vm/vm_priv.h b/headers/private/kernel/vm/vm_priv.h +index 9091c60c81..5568ae8f45 100644 +--- a/headers/private/kernel/vm/vm_priv.h ++++ b/headers/private/kernel/vm/vm_priv.h +@@ -28,7 +28,7 @@ extern "C" { + + // Should only be used by vm internals + status_t vm_page_fault(addr_t address, addr_t faultAddress, bool isWrite, +- bool isExecute, bool isUser, addr_t *newip); ++ bool isExecute, bool isUser, bool allowUserPageAccess, addr_t *newip); + void vm_unreserve_memory(size_t bytes); + status_t vm_try_reserve_memory(size_t bytes, int priority, bigtime_t timeout); + status_t vm_daemon_init(void); +diff --git a/src/system/kernel/arch/x86/arch_int.cpp b/src/system/kernel/arch/x86/arch_int.cpp +index 416e9d21c4..5071a83a74 100644 +--- a/src/system/kernel/arch/x86/arch_int.cpp ++++ b/src/system/kernel/arch/x86/arch_int.cpp +@@ -350,6 +350,7 @@ x86_page_fault_exception(struct iframe* frame) + (frame->error_code & PGFAULT_W) != 0, // write access + (frame->error_code & PGFAULT_I) != 0, // instruction fetch + IFRAME_IS_USER(frame), // userland ++ true, + &newip); + if (newip != 0) { + // the page fault handler wants us to modify the iframe to set the +diff --git a/src/system/kernel/vm/vm.cpp b/src/system/kernel/vm/vm.cpp +index c95f8ddb1f..baf469296d 100644 +--- a/src/system/kernel/vm/vm.cpp ++++ b/src/system/kernel/vm/vm.cpp +@@ -272,7 +272,8 @@ static cache_info* sCacheInfoTable; + static void delete_area(VMAddressSpace* addressSpace, VMArea* area, + bool addressSpaceCleanup); + static status_t vm_soft_fault(VMAddressSpace* addressSpace, addr_t address, +- bool isWrite, bool isExecute, bool isUser, vm_page** wirePage); ++ bool isWrite, bool isExecute, bool isUser, bool allowUserPageAccess, ++ vm_page** wirePage); + static status_t map_backing_store(VMAddressSpace* addressSpace, + VMCache* cache, off_t offset, const char* areaName, addr_t size, int wiring, + int protection, int protectionMax, int mapping, uint32 flags, +@@ -4370,7 +4371,7 @@ forbid_page_faults(void) + + status_t + vm_page_fault(addr_t address, addr_t faultAddress, bool isWrite, bool isExecute, +- bool isUser, addr_t* newIP) ++ bool isUser, bool allowUserPageAccess, addr_t* newIP) + { + FTRACE(("vm_page_fault: page fault at 0x%lx, ip 0x%lx\n", address, + faultAddress)); +@@ -4414,7 +4415,7 @@ vm_page_fault(addr_t address, addr_t faultAddress, bool isWrite, bool isExecute, + + if (status == B_OK) { + status = vm_soft_fault(addressSpace, pageAddress, isWrite, isExecute, +- isUser, NULL); ++ isUser, allowUserPageAccess, NULL); + } + + if (status < B_OK) { +@@ -4431,14 +4432,18 @@ vm_page_fault(addr_t address, addr_t faultAddress, bool isWrite, bool isExecute, + *newIP = reinterpret_cast(thread->fault_handler); + dprintf("*newIP = 0x%" B_PRIxADDR "\n", *newIP); + } else { ++#ifdef __riscv + WriteTrapInfo(); ++#endif + // unhandled page fault in the kernel + panic("vm_page_fault: unhandled page fault in kernel space at " + "0x%lx, ip 0x%lx\n", address, faultAddress); + } + } else { ++#ifdef __riscv + WriteTrapInfo(); + DoStackTrace(Fp(), 0); ++#endif + Thread* thread = thread_get_current_thread(); + + #ifdef TRACE_FAULTS +@@ -4690,11 +4695,13 @@ fault_get_page(PageFaultContext& context) + */ + static status_t + vm_soft_fault(VMAddressSpace* addressSpace, addr_t originalAddress, +- bool isWrite, bool isExecute, bool isUser, vm_page** wirePage) ++ bool isWrite, bool isExecute, bool isUser, bool allowUserPageAccess, ++ vm_page** wirePage) + { + FTRACE(("vm_soft_fault: thid 0x%" B_PRIx32 " address 0x%" B_PRIxADDR ", " +- "isWrite %d, isUser %d\n", thread_get_current_thread_id(), +- originalAddress, isWrite, isUser)); ++ "isWrite %d, isUser %d, allowUserpageAccess %d\n", ++ thread_get_current_thread_id(), originalAddress, ++ isWrite, isUser, allowUserpageAccess)); + + PageFaultContext context(addressSpace, isWrite); + +@@ -4730,8 +4737,8 @@ vm_soft_fault(VMAddressSpace* addressSpace, addr_t originalAddress, + // check permissions + uint32 protection = get_area_page_protection(area, address); + if (isUser && (protection & B_USER_PROTECTION) == 0) { +- dprintf("user access on kernel area 0x%" B_PRIx32 " at %p\n", +- area->id, (void*)originalAddress); ++ dprintf("user access on kernel area %" B_PRId32 "(%s) at %p\n", ++ area->id, area->name, (void*)originalAddress); + TPF(PageFaultError(area->id, + VMPageFaultTracing::PAGE_FAULT_ERROR_KERNEL_ONLY)); + status = B_PERMISSION_DENIED; +@@ -4739,8 +4746,9 @@ vm_soft_fault(VMAddressSpace* addressSpace, addr_t originalAddress, + } + if (isWrite && (protection + & (B_WRITE_AREA | (isUser ? 0 : B_KERNEL_WRITE_AREA))) == 0) { +- dprintf("write access attempted on write-protected area 0x%" +- B_PRIx32 " at %p\n", area->id, (void*)originalAddress); ++ dprintf("write access attempted on write-protected area %" ++ B_PRId32 "(%s) at %p\n", area->id, area->name, ++ (void*)originalAddress); + TPF(PageFaultError(area->id, + VMPageFaultTracing::PAGE_FAULT_ERROR_WRITE_PROTECTED)); + status = B_PERMISSION_DENIED; +@@ -4748,22 +4756,32 @@ vm_soft_fault(VMAddressSpace* addressSpace, addr_t originalAddress, + } else if (isExecute && (protection + & (B_EXECUTE_AREA + | (isUser ? 0 : B_KERNEL_EXECUTE_AREA))) == 0) { +- dprintf("instruction fetch attempted on execute-protected area 0x%" +- B_PRIx32 " at %p\n", area->id, (void*)originalAddress); ++ dprintf("instruction fetch attempted on execute-protected area %" ++ B_PRId32 "(%s) at %p\n", area->id, area->name, ++ (void*)originalAddress); + TPF(PageFaultError(area->id, + VMPageFaultTracing::PAGE_FAULT_ERROR_EXECUTE_PROTECTED)); + status = B_PERMISSION_DENIED; + break; + } else if (!isWrite && !isExecute && (protection + & (B_READ_AREA | (isUser ? 0 : B_KERNEL_READ_AREA))) == 0) { +- dprintf("read access attempted on read-protected area 0x%" B_PRIx32 +- " at %p\n", area->id, (void*)originalAddress); ++ dprintf("read access attempted on read-protected area %" B_PRId32 ++ "(%s) at %p\n", area->id, area->name, (void*)originalAddress); + TPF(PageFaultError(area->id, + VMPageFaultTracing::PAGE_FAULT_ERROR_READ_PROTECTED)); + status = B_PERMISSION_DENIED; + break; + } + ++ if (!isUser && !allowUserPageAccess ++ && (protection & B_USER_PROTECTION) != 0) { ++ dprintf("kernel access with user page access disabled on user area" ++ " %" B_PRId32 "(%s) at %p\n", area->id, area->name, ++ (void*)originalAddress); ++ status = B_PERMISSION_DENIED; ++ break; ++ } ++ + // We have the area, it was a valid access, so let's try to resolve the + // page fault now. + // At first, the top most cache from the area is investigated. +@@ -5596,7 +5614,7 @@ vm_wire_page(team_id team, addr_t address, bool writable, + addressSpaceLocker.Unlock(); + + error = vm_soft_fault(addressSpace, pageAddress, writable, false, +- isUser, &page); ++ isUser, true, &page); + + if (error != B_OK) { + // The page could not be mapped -- clean up. +@@ -5776,7 +5794,7 @@ lock_memory_etc(team_id team, void* address, size_t numBytes, uint32 flags) + addressSpaceLocker.Unlock(); + + error = vm_soft_fault(addressSpace, nextAddress, writable, +- false, isUser, &page); ++ false, isUser, true, &page); + + addressSpaceLocker.Lock(); + cacheChainLocker.SetTo(vm_area_get_locked_cache(area)); +-- +2.30.2 + diff --git a/patchset-hrev55144/0092-kernel-arch-vm-implement-for-riscv64-2.patch b/patchset-hrev55144/0092-kernel-arch-vm-implement-for-riscv64-2.patch new file mode 100644 index 0000000..4619c8e --- /dev/null +++ b/patchset-hrev55144/0092-kernel-arch-vm-implement-for-riscv64-2.patch @@ -0,0 +1,897 @@ +From 708de8da6c1100d333ba38849095baccea89dbd7 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 02:57:36 +0900 +Subject: kernel/arch/vm: implement for riscv64 (2) + +Change-Id: I3189d21d775f7ff34d5bbe5cf8490269a22e373a +--- + .../arch/riscv64/arch_vm_translation_map.h | 25 +- + .../arch/riscv64/RISCV64VMTranslationMap.cpp | 144 ++++++------ + .../arch/riscv64/RISCV64VMTranslationMap.h | 3 + + src/system/kernel/arch/riscv64/arch_vm.cpp | 196 +++++++++++++++- + .../arch/riscv64/arch_vm_translation_map.cpp | 215 +++--------------- + 5 files changed, 320 insertions(+), 263 deletions(-) + +diff --git a/headers/private/kernel/arch/riscv64/arch_vm_translation_map.h b/headers/private/kernel/arch/riscv64/arch_vm_translation_map.h +index 853d7202c0..5f09fc5c01 100644 +--- a/headers/private/kernel/arch/riscv64/arch_vm_translation_map.h ++++ b/headers/private/kernel/arch/riscv64/arch_vm_translation_map.h +@@ -7,20 +7,23 @@ + + #include + +-#ifdef __cplusplus +-extern "C" { +-#endif + +-void riscv64_translation_map_change_asid(VMTranslationMap *map); ++//gVirtFromPhysOffset = virtAdr - physAdr; ++extern ssize_t gVirtFromPhysOffset; + +-status_t riscv64_map_address_range(addr_t virtualAddress, +- phys_addr_t physicalAddress, size_t size); +-void riscv64_unmap_address_range(addr_t virtualAddress, size_t size); +-status_t riscv64_remap_address_range(addr_t *virtualAddress, size_t size, +- bool unmap); + +-#ifdef __cplusplus ++static inline void* ++VirtFromPhys(phys_addr_t physAdr) ++{ ++ return (void*)(physAdr + gVirtFromPhysOffset); + } +-#endif ++ ++ ++static inline phys_addr_t ++PhysFromVirt(void* virtAdr) ++{ ++ return (phys_addr_t)virtAdr - gVirtFromPhysOffset; ++} ++ + + #endif /* _KERNEL_ARCH_RISCV64_VM_TRANSLATION_MAP_H */ +diff --git a/src/system/kernel/arch/riscv64/RISCV64VMTranslationMap.cpp b/src/system/kernel/arch/riscv64/RISCV64VMTranslationMap.cpp +index 7234beb16d..3ea75bdb00 100644 +--- a/src/system/kernel/arch/riscv64/RISCV64VMTranslationMap.cpp ++++ b/src/system/kernel/arch/riscv64/RISCV64VMTranslationMap.cpp +@@ -10,6 +10,8 @@ + #include + + ++//#define DISABLE_MODIFIED_FLAGS 1 ++ + //#define DO_TRACE + #ifdef DO_TRACE + # define TRACE(x...) dprintf(x) +@@ -21,54 +23,18 @@ + panic("not implemented: %s\n", __PRETTY_FUNCTION__) + + +-static inline void* +-VirtFromPhys(uint64_t physAdr) +-{ +- return (void*)(physAdr + (KERNEL_PMAP_BASE - 0x80000000)); +-} +- +- +-static inline uint64_t +-PhysFromVirt(void *virtAdr) +-{ +- return (uint64)virtAdr - (KERNEL_PMAP_BASE - 0x80000000); +-} +- +- +-static void +-WriteVmPage(vm_page* page) +-{ +- dprintf("0x%08" B_PRIxADDR " ", page->physical_page_number * B_PAGE_SIZE); +- switch (page->State()) { +- case PAGE_STATE_ACTIVE: dprintf("A"); break; +- case PAGE_STATE_INACTIVE: dprintf("I"); break; +- case PAGE_STATE_MODIFIED: dprintf("M"); break; +- case PAGE_STATE_CACHED: dprintf("C"); break; +- case PAGE_STATE_FREE: dprintf("F"); break; +- case PAGE_STATE_CLEAR: dprintf("L"); break; +- case PAGE_STATE_WIRED: dprintf("W"); break; +- case PAGE_STATE_UNUSED: dprintf("-"); break; +- } +- dprintf(" "); +- if (page->busy) dprintf("B"); else dprintf("-"); +- if (page->busy_writing) dprintf("W"); else dprintf("-"); +- if (page->accessed) dprintf("A"); else dprintf("-"); +- if (page->modified) dprintf("M"); else dprintf("-"); +- if (page->unused) dprintf("U"); else dprintf("-"); +- +- dprintf(" usage:%3u", page->usage_count); +- dprintf(" wired:%5u", page->WiredCount()); +-} +- +- + static void + FreePageTable(page_num_t ppn, bool isKernel, uint32 level = 2) + { + if (level > 0) { + Pte* pte = (Pte*)VirtFromPhys(ppn * B_PAGE_SIZE); +- // NOTE: adjust range if changing kernel address space range +- for (uint32 i = (level == 2 && !isKernel) ? 256 : 0; i < pteCount; +- i++) { ++ uint64 beg = 0; ++ uint64 end = pteCount - 1; ++ if (level == 2 && !isKernel) { ++ beg = VirtAdrPte(USER_BASE, 2); ++ end = VirtAdrPte(USER_TOP, 2); ++ } ++ for (uint64 i = beg; i <= end; i++) { + if ((1 << pteValid) & pte[i].flags) + FreePageTable(pte[i].ppn, isKernel, level - 1); + } +@@ -89,8 +55,13 @@ GetPageTableSize(page_num_t ppn, bool isKernel, uint32 level = 2) + + uint64 size = 1; + Pte* pte = (Pte*)VirtFromPhys(ppn * B_PAGE_SIZE); +- // NOTE: adjust range if changing kernel address space range +- for (uint32 i = (level == 2 && !isKernel) ? 256 : 0; i < pteCount; i++) { ++ uint64 beg = 0; ++ uint64 end = pteCount - 1; ++ if (level == 2 && !isKernel) { ++ beg = VirtAdrPte(USER_BASE, 2); ++ end = VirtAdrPte(USER_TOP, 2); ++ } ++ for (uint64 i = beg; i <= end; i++) { + if ((1 << pteValid) & pte[i].flags) + size += GetPageTableSize(pte[i].ppn, isKernel, level - 1); + } +@@ -120,8 +91,8 @@ RISCV64VMTranslationMap::LookupPte(addr_t virtAdr, bool alloc, + VMAddressSpace::Kernel()->TranslationMap(); + Pte *kernelPageTable = (Pte*)VirtFromPhys(kernelMap->PageTable()); + Pte *userPageTable = (Pte*)VirtFromPhys(fPageTable); +- // NOTE: adjust range if changing kernel address space range +- for (int i = 0; i < 256; i++) { ++ for (uint64 i = VirtAdrPte(KERNEL_BASE, 2); ++ i <= VirtAdrPte(KERNEL_TOP, 2); i++) { + Pte *pte = &userPageTable[i]; + pte->ppn = kernelPageTable[i].ppn; + pte->flags |= (1 << pteValid); +@@ -129,8 +100,8 @@ RISCV64VMTranslationMap::LookupPte(addr_t virtAdr, bool alloc, + } + } + Pte *pte = (Pte*)VirtFromPhys(fPageTable); +- for (int level = 2; level > 0; level --) { +- pte += PhysAdrPte(virtAdr, level); ++ for (int level = 2; level > 0; level--) { ++ pte += VirtAdrPte(virtAdr, level); + if (!((1 << pteValid) & pte->flags)) { + if (!alloc) + return NULL; +@@ -144,7 +115,7 @@ RISCV64VMTranslationMap::LookupPte(addr_t virtAdr, bool alloc, + } + pte = (Pte*)VirtFromPhys(B_PAGE_SIZE * pte->ppn); + } +- pte += PhysAdrPte(virtAdr, 0); ++ pte += VirtAdrPte(virtAdr, 0); + return pte; + } + +@@ -179,13 +150,11 @@ RISCV64VMTranslationMap::~RISCV64VMTranslationMap() + TRACE(" pageTableSize: %" B_PRIu64 "\n", fPageTableSize); + TRACE(" GetPageTableSize(): %" B_PRIu64 "\n", + GetPageTableSize(fPageTable / B_PAGE_SIZE, fIsKernel)); +- if (!fIsKernel) { +- // We are going to delete currently used page table, switch to +- // kernel page table. +- RISCV64VMTranslationMap* kernelMap = (RISCV64VMTranslationMap*) +- VMAddressSpace::Kernel()->TranslationMap(); +- SetSatp(kernelMap->Satp()); +- } ++ ++ ASSERT_ALWAYS(!fIsKernel); ++ // Can't delete currently used page table ++ ASSERT_ALWAYS(::Satp() != Satp()); ++ + FreePageTable(fPageTable / B_PAGE_SIZE, fIsKernel); + } + +@@ -270,7 +239,11 @@ RISCV64VMTranslationMap::Map(addr_t virtualAddress, + if ((attributes & B_KERNEL_EXECUTE_AREA) != 0) + pte->flags |= (1 << pteExec); + } +- pte->flags |= (1 << pteValid); ++ pte->flags |= (1 << pteValid) ++#ifdef DISABLE_MODIFIED_FLAGS ++ | (1 << pteAccessed) | (1 << pteDirty) ++#endif ++ ; + + FlushTlbPage(virtualAddress); + +@@ -370,8 +343,9 @@ RISCV64VMTranslationMap::UnmapArea(VMArea* area, bool deletingAddressSpace, + bool ignoreTopCachePageFlags) + { + TRACE("RISCV64VMTranslationMap::UnmapArea(0x%" B_PRIxADDR "(%s), 0x%" +- B_PRIxADDR ", 0x%" B_PRIxSIZE ", %d)\n", (addr_t)area, area->name, base, +- size, updatePageQueue); ++ B_PRIxADDR ", 0x%" B_PRIxSIZE ", %d, %d)\n", (addr_t)area, area->name, ++ area->Base(), area->Size(), deletingAddressSpace, ++ ignoreTopCachePageFlags); + + if (area->cache_type == CACHE_TYPE_DEVICE || area->wiring != B_NO_LOCK) { + UnmapPages(area, area->Base(), area->Size(), true); +@@ -474,9 +448,10 @@ RISCV64VMTranslationMap::Query(addr_t virtualAddress, + *_physicalAddress = pte->ppn * B_PAGE_SIZE; + + if (((1 << pteValid) & pte->flags) != 0) *_flags |= PAGE_PRESENT; ++#ifndef DISABLE_MODIFIED_FLAGS + if (((1 << pteDirty) & pte->flags) != 0) *_flags |= PAGE_MODIFIED; + if (((1 << pteAccessed) & pte->flags) != 0) *_flags |= PAGE_ACCESSED; +- ++#endif + if (((1 << pteUser) & pte->flags) != 0) { + if (((1 << pteRead) & pte->flags) != 0) *_flags |= B_READ_AREA; + if (((1 << pteWrite) & pte->flags) != 0) *_flags |= B_WRITE_AREA; +@@ -520,7 +495,7 @@ status_t RISCV64VMTranslationMap::Protect(addr_t base, addr_t top, + } + + Pte newPte = *pte; +- newPte.flags = (1 << pteValid); ++ newPte.flags &= (1 << pteValid) | (1 << pteAccessed) | (1 << pteDirty); + if ((attributes & B_USER_PROTECTION) != 0) { + newPte.flags |= (1 << pteUser); + if ((attributes & B_READ_AREA) != 0) +@@ -563,6 +538,30 @@ RISCV64VMTranslationMap::ProtectArea(VMArea* area, uint32 attributes) + } + + ++static inline uint32 ++ConvertAccessedFlags(uint32 flags) ++{ ++ return ++ ((flags & PAGE_MODIFIED) ? (1 << pteDirty ) : 0) | ++ ((flags & PAGE_ACCESSED) ? (1 << pteAccessed) : 0); ++} ++ ++ ++status_t ++RISCV64VMTranslationMap::SetFlags(addr_t address, uint32 flags) ++{ ++ ThreadCPUPinner pinner(thread_get_current_thread()); ++ Pte* pte = LookupPte(address, false, NULL); ++ if (pte == NULL || ((1 << pteValid) & pte->flags) == 0) ++ return B_OK; ++#ifndef DISABLE_MODIFIED_FLAGS ++ pte->flags |= ConvertAccessedFlags(flags); ++#endif ++ FlushTlbPage(address); ++ return B_OK; ++} ++ ++ + status_t + RISCV64VMTranslationMap::ClearFlags(addr_t address, uint32 flags) + { +@@ -570,10 +569,9 @@ RISCV64VMTranslationMap::ClearFlags(addr_t address, uint32 flags) + Pte* pte = LookupPte(address, false, NULL); + if (pte == NULL || ((1 << pteValid) & pte->flags) == 0) + return B_OK; +- pte->flags &= ~( +- ((flags & PAGE_MODIFIED) ? (1 << pteDirty ) : 0) | +- ((flags & PAGE_ACCESSED) ? (1 << pteAccessed) : 0) +- ); ++#ifndef DISABLE_MODIFIED_FLAGS ++ pte->flags &= ~ConvertAccessedFlags(flags); ++#endif + FlushTlbPage(address); + return B_OK; + } +@@ -595,6 +593,7 @@ RISCV64VMTranslationMap::ClearAccessedAndModified(VMArea* area, addr_t address, + return false; + } + Pte oldPte = *pte; ++#ifndef DISABLE_MODIFIED_FLAGS + if (unmapIfUnaccessed) { + if (((1 << pteAccessed) & pte->flags) != 0) { + pte->flags &= ~((1 << pteAccessed) | (1 << pteDirty)); +@@ -605,6 +604,7 @@ RISCV64VMTranslationMap::ClearAccessedAndModified(VMArea* area, addr_t address, + } else { + pte->flags &= ~((1 << pteAccessed) | (1 << pteDirty)); + } ++#endif + pinner.Unlock(); + _modified = ((1 << pteDirty) & oldPte.flags) != 0; + if (((1 << pteAccessed) & oldPte.flags) != 0) { +@@ -688,7 +688,7 @@ RISCV64VMTranslationMap::MemcpyFromMap(char *to, addr_t from, size_t size) + TRACE("[!] not mapped: 0x%" B_PRIxADDR + ", calling page fault handler\n", va0); + addr_t newIP; +- vm_page_fault(va0, Ra(), true, false, true, &newIP); ++ vm_page_fault(va0, Ra(), true, false, true, true, &newIP); + pa0 = LookupAddr(va0); + TRACE("LookupAddr(0x%" B_PRIxADDR "): 0x%" B_PRIxADDR "\n", + va0, pa0); +@@ -723,7 +723,7 @@ RISCV64VMTranslationMap::MemsetToMap(addr_t to, char c, size_t count) + TRACE("[!] not mapped: 0x%" B_PRIxADDR + ", calling page fault handler\n", va0); + addr_t newIP; +- vm_page_fault(va0, Ra(), true, false, true, &newIP); ++ vm_page_fault(va0, Ra(), true, false, true, true, &newIP); + pa0 = LookupAddr(va0); + TRACE("LookupAddr(0x%" B_PRIxADDR "): 0x%" B_PRIxADDR "\n", + va0, pa0); +@@ -833,7 +833,9 @@ RISCV64VMPhysicalPageMapper::MemsetPhysical(phys_addr_t address, int value, + { + TRACE("RISCV64VMPhysicalPageMapper::MemsetPhysical(0x%" B_PRIxADDR + ", 0x%x, 0x%" B_PRIxADDR ")\n", address, value, length); ++ set_ac(); + memset(VirtFromPhys(address), value, length); ++ clear_ac(); + return B_OK; + } + +@@ -844,7 +846,9 @@ RISCV64VMPhysicalPageMapper::MemcpyFromPhysical(void* to, phys_addr_t from, + { + TRACE("RISCV64VMPhysicalPageMapper::MemcpyFromPhysical(0x%" B_PRIxADDR + ", 0x%" B_PRIxADDR ", %" B_PRIuSIZE ")\n", (addr_t)to, from, length); ++ set_ac(); + memcpy(to, VirtFromPhys(from), length); ++ clear_ac(); + return B_OK; + } + +@@ -855,7 +859,9 @@ RISCV64VMPhysicalPageMapper::MemcpyToPhysical(phys_addr_t to, const void* from, + { + TRACE("RISCV64VMPhysicalPageMapper::MemcpyToPhysical(0x%" B_PRIxADDR + ", 0x%" B_PRIxADDR ", %" B_PRIuSIZE ")\n", to, (addr_t)from, length); ++ set_ac(); + memcpy(VirtFromPhys(to), from, length); ++ clear_ac(); + return B_OK; + } + +@@ -866,5 +872,7 @@ RISCV64VMPhysicalPageMapper::MemcpyPhysicalPage(phys_addr_t to, + { + TRACE("RISCV64VMPhysicalPageMapper::MemcpyPhysicalPage(0x%" B_PRIxADDR + ", 0x%" B_PRIxADDR ")\n", to, from); ++ set_ac(); + memcpy(VirtFromPhys(to), VirtFromPhys(from), B_PAGE_SIZE); ++ clear_ac(); + } +diff --git a/src/system/kernel/arch/riscv64/RISCV64VMTranslationMap.h b/src/system/kernel/arch/riscv64/RISCV64VMTranslationMap.h +index 19837441ac..2d9e8a148c 100644 +--- a/src/system/kernel/arch/riscv64/RISCV64VMTranslationMap.h ++++ b/src/system/kernel/arch/riscv64/RISCV64VMTranslationMap.h +@@ -48,6 +48,9 @@ struct RISCV64VMTranslationMap: public VMTranslationMap { + status_t ProtectArea(VMArea* area, + uint32 attributes); + ++ status_t SetFlags(addr_t virtualAddress, ++ uint32 flags); ++ + virtual status_t ClearFlags(addr_t virtualAddress, + uint32 flags); + +diff --git a/src/system/kernel/arch/riscv64/arch_vm.cpp b/src/system/kernel/arch/riscv64/arch_vm.cpp +index 0027e0ed7f..d70fb21f00 100644 +--- a/src/system/kernel/arch/riscv64/arch_vm.cpp ++++ b/src/system/kernel/arch/riscv64/arch_vm.cpp +@@ -10,8 +10,10 @@ + #include + #include + ++#include "RISCV64VMTranslationMap.h" + +-//#define TRACE_ARCH_VM ++ ++#define TRACE_ARCH_VM + #ifdef TRACE_ARCH_VM + # define TRACE(x) dprintf x + #else +@@ -19,6 +21,182 @@ + #endif + + ++static uint64_t ++SignExtendVirtAdr(uint64_t virtAdr) ++{ ++ if (((uint64_t)1 << 38) & virtAdr) ++ return virtAdr | 0xFFFFFF8000000000; ++ return virtAdr; ++} ++ ++ ++static Pte* ++LookupPte(phys_addr_t pageTable, addr_t virtAdr) ++{ ++ Pte *pte = (Pte*)VirtFromPhys(pageTable); ++ for (int level = 2; level > 0; level --) { ++ pte += VirtAdrPte(virtAdr, level); ++ if (!((1 << pteValid) & pte->flags)) { ++ return NULL; ++ } ++ pte = (Pte*)VirtFromPhys(B_PAGE_SIZE * pte->ppn); ++ } ++ pte += VirtAdrPte(virtAdr, 0); ++ return pte; ++} ++ ++ ++ ++static void ++WritePteFlags(uint32 flags) ++{ ++ bool first = true; ++ dprintf("{"); ++ for (uint32 i = 0; i < 32; i++) { ++ if ((1 << i) & flags) { ++ if (first) first = false; else dprintf(", "); ++ switch (i) { ++ case pteValid: dprintf("valid"); break; ++ case pteRead: dprintf("read"); break; ++ case pteWrite: dprintf("write"); break; ++ case pteExec: dprintf("exec"); break; ++ case pteUser: dprintf("user"); break; ++ case pteGlobal: dprintf("global"); break; ++ case pteAccessed: dprintf("accessed"); break; ++ case pteDirty: dprintf("dirty"); break; ++ default: dprintf("%" B_PRIu32, i); ++ } ++ } ++ } ++ dprintf("}"); ++} ++ ++ ++static void ++DumpPageWrite(uint64_t virtAdr, uint64_t physAdr, size_t size, uint64 flags, uint64& firstVirt, uint64& firstPhys, uint64& firstFlags, uint64& len) ++{ ++ if (virtAdr == firstVirt + len && physAdr == firstPhys + len && flags == firstFlags) { ++ len += size; ++ } else { ++ if (len != 0) { ++ dprintf(" 0x%08" B_PRIxADDR " - 0x%08" B_PRIxADDR, ++ firstVirt, firstVirt + (len - 1)); ++ dprintf(": 0x%08" B_PRIxADDR " - 0x%08" B_PRIxADDR ", %#" B_PRIxADDR ", ", firstPhys, firstPhys + (len - 1), len); ++ WritePteFlags(firstFlags); dprintf("\n"); ++ } ++ firstVirt = virtAdr; ++ firstPhys = physAdr; ++ firstFlags = flags; ++ len = size; ++ } ++} ++ ++ ++static void ++DumpPageTableInt(Pte* pte, uint64_t virtAdr, uint32_t level, uint64& firstVirt, uint64& firstPhys, uint64& firstFlags, uint64& len) ++{ ++ for (uint32 i = 0; i < pteCount; i++) { ++ if (((1 << pteValid) & pte[i].flags) != 0) { ++ if ((((1 << pteRead) | (1 << pteWrite) | (1 << pteExec)) & pte[i].flags) == 0) { ++ if (level == 0) ++ kprintf(" internal page table on level 0\n"); ++ ++ DumpPageTableInt((Pte*)VirtFromPhys(pageSize*pte[i].ppn), ++ virtAdr + ((uint64_t)i << (pageBits + pteIdxBits*level)), ++ level - 1, firstVirt, firstPhys, firstFlags, len); ++ } else { ++ DumpPageWrite( ++ SignExtendVirtAdr(virtAdr + ((uint64_t)i << (pageBits + pteIdxBits*level))), ++ pte[i].ppn * B_PAGE_SIZE, ++ 1 << (pageBits + pteIdxBits*level), ++ pte[i].flags, ++ firstVirt, firstPhys, firstFlags, len); ++ } ++ } ++ } ++} ++ ++ ++static int ++DumpPageTable(int argc, char** argv) ++{ ++ SatpReg satp; ++ if (argc >= 2) { ++ team_id id = strtoul(argv[1], NULL, 0); ++ VMAddressSpace* addrSpace = VMAddressSpace::DebugGet(id); ++ if (addrSpace == NULL) { ++ kprintf("could not find team %" B_PRId32 "\n", id); ++ return 0; ++ } ++ satp.val = ((RISCV64VMTranslationMap*) ++ addrSpace->TranslationMap())->Satp(); ++ dprintf("page table for team %" B_PRId32 "\n", id); ++ } else { ++ satp.val = Satp(); ++ dprintf("current page table:\n"); ++ } ++ Pte* root = (Pte*)VirtFromPhys(satp.ppn * B_PAGE_SIZE); ++ ++ uint64 firstVirt = 0; ++ uint64 firstPhys = 0; ++ uint64 firstFlags = 0; ++ uint64 len = 0; ++ DumpPageTableInt(root, 0, 2, firstVirt, firstPhys, firstFlags, len); ++ DumpPageWrite(0, 0, 0, 0, firstVirt, firstPhys, firstFlags, len); ++ ++ return 0; ++} ++ ++ ++static int ++DumpVirtPage(int argc, char** argv) ++{ ++ int curArg = 1; ++ SatpReg satp; ++ ++ satp.val = Satp(); ++ while (argv[curArg][0] == '-') { ++ if (strcmp(argv[curArg], "-team") == 0) { ++ curArg++; ++ team_id id = strtoul(argv[curArg++], NULL, 0); ++ VMAddressSpace* addrSpace = VMAddressSpace::DebugGet(id); ++ if (addrSpace == NULL) { ++ kprintf("could not find team %" B_PRId32 "\n", id); ++ return 0; ++ } ++ satp.val = ((RISCV64VMTranslationMap*) ++ addrSpace->TranslationMap())->Satp(); ++ } else { ++ kprintf("unknown flag \"%s\"\n", argv[curArg]); ++ return 0; ++ } ++ } ++ ++ kprintf("satp: %#" B_PRIx64 "\n", satp.val); ++ ++ uint64 firstVirt = 0; ++ uint64 firstPhys = 0; ++ uint64 firstFlags = 0; ++ uint64 len = B_PAGE_SIZE; ++ if (!evaluate_debug_expression(argv[curArg++], &firstVirt, false)) ++ return 0; ++ ++ firstVirt = ROUNDDOWN(firstVirt, B_PAGE_SIZE); ++ ++ Pte* pte = LookupPte(satp.ppn * B_PAGE_SIZE, firstVirt); ++ if (pte == NULL) { ++ dprintf("not mapped\n"); ++ return 0; ++ } ++ firstPhys = pte->ppn * B_PAGE_SIZE; ++ firstFlags = pte->flags; ++ ++ DumpPageWrite(0, 0, 0, 0, firstVirt, firstPhys, firstFlags, len); ++ ++ return 0; ++} ++ ++ + status_t + arch_vm_init(kernel_args *args) + { +@@ -29,13 +207,16 @@ arch_vm_init(kernel_args *args) + status_t + arch_vm_init_post_area(kernel_args *args) + { +- void* address = (void*)KERNEL_PMAP_BASE; ++ void* address = (void*)args->arch_args.physMap.start; + area_id area = vm_create_null_area(VMAddressSpace::KernelID(), + "physical map area", &address, B_EXACT_ADDRESS, +- KERNEL_PMAP_SIZE, 0); ++ args->arch_args.physMap.size, 0); + if (area < B_OK) + return area; + ++ add_debugger_command("dump_page_table", &DumpPageTable, "Dump page table"); ++ add_debugger_command("dump_virt_page", &DumpVirtPage, "Dump virtual page mapping"); ++ + return B_OK; + } + +@@ -50,15 +231,15 @@ arch_vm_init_post_modules(kernel_args *args) + status_t + arch_vm_init_end(kernel_args *args) + { +- TRACE(("arch_vm_init_end(): %lu virtual ranges to keep:\n", ++ TRACE(("arch_vm_init_end(): %" B_PRIu32 " virtual ranges to keep:\n", + args->arch_args.num_virtual_ranges_to_keep)); + + for (int i = 0; i < (int)args->arch_args.num_virtual_ranges_to_keep; i++) { + addr_range &range = args->arch_args.virtual_ranges_to_keep[i]; + +- TRACE((" start: %p, size: 0x%lx\n", (void*)range.start, range.size)); ++ TRACE((" start: %p, size: %#" B_PRIxSIZE "\n", (void*)range.start, range.size)); + +-#if 0 ++#if 1 + // skip ranges outside the kernel address space + if (!IS_KERNEL_ADDRESS(range.start)) { + TRACE((" no kernel address, skipping...\n")); +@@ -104,6 +285,9 @@ arch_vm_aspace_swap(struct VMAddressSpace *from, struct VMAddressSpace *to) + // page directories include all kernel mappings as well. Furthermore our + // arch specific translation map data objects are ref-counted, so they won't + // go away as long as they are still used on any CPU. ++ ++ SetSatp(((RISCV64VMTranslationMap*)to->TranslationMap())->Satp()); ++ FlushTlbAll(); + } + + +diff --git a/src/system/kernel/arch/riscv64/arch_vm_translation_map.cpp b/src/system/kernel/arch/riscv64/arch_vm_translation_map.cpp +index 12df63ea9b..1f131ab669 100644 +--- a/src/system/kernel/arch/riscv64/arch_vm_translation_map.cpp ++++ b/src/system/kernel/arch/riscv64/arch_vm_translation_map.cpp +@@ -32,51 +32,19 @@ + #endif + + +-// TODO: read from FDT +-HtifRegs *volatile gHtifRegs = (HtifRegs *volatile)0x40008000; +-PlicRegs *volatile gPlicRegs = (PlicRegs *volatile)0x40100000; +-ClintRegs *volatile gClintRegs = (ClintRegs *volatile)0x02000000; +- ++ssize_t gVirtFromPhysOffset = 0; + + phys_addr_t sPageTable = 0; +-bool sPagingEnabled = false; + char sPhysicalPageMapperData[sizeof(RISCV64VMPhysicalPageMapper)]; + + +-static inline +-void *VirtFromPhys(uint64_t physAdr) +-{ +- if (!sPagingEnabled) +- return (void*)physAdr; +- return (void*)(physAdr + (KERNEL_PMAP_BASE - 0x80000000)); +-} +- +- +-static inline +-uint64_t PhysFromVirt(void *virtAdr) +-{ +- if (!sPagingEnabled) +- return (uint64)virtAdr; +- return (uint64)virtAdr - (KERNEL_PMAP_BASE - 0x80000000); +-} +- +- +-static uint64_t +-SignExtendVirtAdr(uint64_t virtAdr) +-{ +- if (((uint64_t)1 << 38) & virtAdr) +- return virtAdr | 0xFFFFFF8000000000; +- return virtAdr; +-} +- +- + static Pte* + LookupPte(addr_t virtAdr, bool alloc, kernel_args* args, + phys_addr_t (*get_free_page)(kernel_args *)) + { + Pte *pte = (Pte*)VirtFromPhys(sPageTable); + for (int level = 2; level > 0; level --) { +- pte += PhysAdrPte(virtAdr, level); ++ pte += VirtAdrPte(virtAdr, level); + if (!((1 << pteValid) & pte->flags)) { + if (!alloc) + return NULL; +@@ -88,7 +56,7 @@ LookupPte(addr_t virtAdr, bool alloc, kernel_args* args, + } + pte = (Pte*)VirtFromPhys(B_PAGE_SIZE * pte->ppn); + } +- pte += PhysAdrPte(virtAdr, 0); ++ pte += VirtAdrPte(virtAdr, 0); + return pte; + } + +@@ -102,101 +70,9 @@ Map(addr_t virtAdr, phys_addr_t physAdr, uint64 flags, kernel_args* args, + if (pte == NULL) panic("can't allocate page table"); + + pte->ppn = physAdr / B_PAGE_SIZE; +- pte->flags = (1 << pteValid) | flags; ++ pte->flags = (1 << pteValid) | (1 << pteAccessed) | (1 << pteDirty) | flags; + +- if (sPagingEnabled) FlushTlbPage(virtAdr); +-} +- +- +-static void +-MapRange(addr_t virtAdr, phys_addr_t physAdr, size_t size, uint64 flags, +- kernel_args* args, phys_addr_t (*get_free_page)(kernel_args *)) +-{ +- dprintf("MapRange(0x%" B_PRIxADDR ", 0x%" B_PRIxADDR ", 0x%" +- B_PRIxADDR ")\n", virtAdr, physAdr, size); +- for (size_t i = 0; i < size; i += B_PAGE_SIZE) +- Map(virtAdr + i, physAdr + i, flags, args, get_free_page); +-} +- +- +-static void +-PreallocKernelRange(kernel_args *args) +-{ +- Pte *root = (Pte*)VirtFromPhys(sPageTable); +- // NOTE: adjust range if changing kernel address space range +- for (int i = 0; i < 256; i++) { +- Pte *pte = &root[i]; +- pte->ppn = vm_allocate_early_physical_page(args); +- if (pte->ppn == 0) panic("can't alloc early physical page"); +- memset(VirtFromPhys(B_PAGE_SIZE * pte->ppn), 0, B_PAGE_SIZE); +- pte->flags |= (1 << pteValid); +- } +-} +- +- +-void +-EnablePaging() +-{ +- SatpReg satp; +- satp.ppn = sPageTable / B_PAGE_SIZE; +- satp.asid = 0; +- satp.mode = satpModeSv39; +- SetSatp(satp.val); +- FlushTlbAll(); +- sPagingEnabled = true; +-} +- +- +-static void +-WritePteFlags(uint32 flags) +-{ +- bool first = true; +- dprintf("{"); +- for (uint32 i = 0; i < 32; i++) { +- if ((1 << i) & flags) { +- if (first) first = false; else dprintf(", "); +- switch (i) { +- case pteValid: dprintf("valid"); break; +- case pteRead: dprintf("read"); break; +- case pteWrite: dprintf("write"); break; +- case pteExec: dprintf("exec"); break; +- case pteUser: dprintf("user"); break; +- case pteGlobal: dprintf("global"); break; +- case pteAccessed: dprintf("accessed"); break; +- case pteDirty: dprintf("dirty"); break; +- default: dprintf("%" B_PRIu32, i); +- } +- } +- } +- dprintf("}"); +-} +- +- +-static void +-DumpPageTableInt(Pte* pte, uint64_t virtAdr, uint32_t level) +-{ +- for (uint32 i = 0; i < pteCount; i++) { +- if ((1 << pteValid) & pte[i].flags) { +- if (level == 0) { +- dprintf(" 0x%08" B_PRIxADDR, +- SignExtendVirtAdr(virtAdr + i * B_PAGE_SIZE)); +- dprintf(": 0x%08" B_PRIxADDR ", ", pte[i].ppn * B_PAGE_SIZE); +- WritePteFlags(pte[i].flags); dprintf("\n"); +- } else { +- DumpPageTableInt((Pte*)VirtFromPhys(pageSize*pte[i].ppn), +- virtAdr + ((uint64_t)i << (pageBits + pteIdxBits*level)), +- level - 1); +- } +- } +- } +-} +- +- +-static void +-DumpPageTable(Pte* root) +-{ +- dprintf("PageTable:\n"); +- DumpPageTableInt(root, 0, 2); ++ FlushTlbPage(virtAdr); + } + + +@@ -208,49 +84,6 @@ arch_vm_translation_map_init(kernel_args *args, + { + TRACE("vm_translation_map_init: entry\n"); + +- sPageTable = vm_allocate_early_physical_page(args) * B_PAGE_SIZE; +- PreallocKernelRange(args); +- +- // TODO: don't hardcode RAM base +- MapRange(KERNEL_PMAP_BASE, 0x80000000, args->physical_memory_range[0].size, +- (1 << pteRead) | (1 << pteWrite), +- args, vm_allocate_early_physical_page); +- +- for (uint32 i = 0; i < args->num_virtual_allocated_ranges; i++) { +- addr_t start = args->virtual_allocated_range[i].start; +- size_t size = args->virtual_allocated_range[i].size; +- MapRange(start, start, size, +- (1 << pteRead) | (1 << pteWrite) | (1 << pteExec), +- args, vm_allocate_early_physical_page); +- } +- +- // TODO: read from FDT +- // CLINT +- MapRange( 0x2000000, 0x2000000, 0xC0000, (1 << pteRead) | (1 << pteWrite), +- args, vm_allocate_early_physical_page); +- // HTIF +- MapRange(0x40008000, 0x40008000, 0x1000, (1 << pteRead) | (1 << pteWrite), +- args, vm_allocate_early_physical_page); +- // PLIC +- MapRange(0x40100000, 0x40100000, 0x400000, (1 << pteRead) | (1 << pteWrite), +- args, vm_allocate_early_physical_page); +- +- { +- SstatusReg status(Sstatus()); +- status.sum = 1; +- SetSstatus(status.val); +- } +- +- EnablePaging(); +- +- *_physicalPageMapper = new(&sPhysicalPageMapperData) +- RISCV64VMPhysicalPageMapper(); +- +- if (false) { +- DumpPageTable((Pte*)VirtFromPhys(sPageTable)); +- HtifShutdown(); +- } +- + #ifdef TRACE_VM_TMAP + TRACE("physical memory ranges:\n"); + for (uint32 i = 0; i < args->num_physical_memory_ranges; i++) { +@@ -272,7 +105,28 @@ arch_vm_translation_map_init(kernel_args *args, + addr_t end = start + args->virtual_allocated_range[i].size; + TRACE(" %" B_PRIxADDR " - %" B_PRIxADDR "\n", start, end); + } ++ ++ TRACE("kernel args ranges:\n"); ++ for (uint32 i = 0; i < args->num_kernel_args_ranges; i++) { ++ phys_addr_t start = args->kernel_args_range[i].start; ++ phys_addr_t end = start + args->kernel_args_range[i].size; ++ TRACE(" %" B_PRIxPHYSADDR " - %" B_PRIxPHYSADDR "\n", start, end); ++ } + #endif ++ ++ { ++ SatpReg satp(Satp()); ++ sPageTable = satp.ppn * B_PAGE_SIZE; ++ } ++ ++ dprintf("physMapBase: %#" B_PRIxADDR "\n", args->arch_args.physMap.start); ++ dprintf("physMemBase: %#" B_PRIxADDR "\n", args->physical_memory_range[0].start); ++ gVirtFromPhysOffset = args->arch_args.physMap.start - args->physical_memory_range[0].start; ++ ++ clear_ac(); ++ ++ *_physicalPageMapper = new(&sPhysicalPageMapperData) ++ RISCV64VMPhysicalPageMapper(); + + return B_OK; + } +@@ -294,14 +148,19 @@ arch_vm_translation_map_init_post_area(kernel_args *args) + + + status_t +-arch_vm_translation_map_early_map(kernel_args *args, addr_t va, phys_addr_t pa, +- uint8 attributes, phys_addr_t (*get_free_page)(kernel_args *)) ++arch_vm_translation_map_early_map(kernel_args *args, ++ addr_t virtAdr, phys_addr_t physAdr, uint8 attributes, ++ phys_addr_t (*get_free_page)(kernel_args *)) + { ++ //dprintf("early_map(%#" B_PRIxADDR ", %#" B_PRIxADDR ")\n", virtAdr, physAdr); + uint64 flags = 0; +- if ((attributes & B_KERNEL_READ_AREA) != 0) flags |= (1 << pteRead); +- if ((attributes & B_KERNEL_WRITE_AREA) != 0) flags |= (1 << pteWrite); +- if ((attributes & B_KERNEL_EXECUTE_AREA) != 0) flags |= (1 << pteExec); +- Map(va, pa, flags, args, get_free_page); ++ if ((attributes & B_KERNEL_READ_AREA) != 0) ++ flags |= (1 << pteRead); ++ if ((attributes & B_KERNEL_WRITE_AREA) != 0) ++ flags |= (1 << pteWrite); ++ if ((attributes & B_KERNEL_EXECUTE_AREA) != 0) ++ flags |= (1 << pteExec); ++ Map(virtAdr, physAdr, flags, args, get_free_page); + return B_OK; + } + +-- +2.30.2 + diff --git a/patchset-hrev55144/0093-kernel-arch-thread-implement-for-riscv64-2.patch b/patchset-hrev55144/0093-kernel-arch-thread-implement-for-riscv64-2.patch new file mode 100644 index 0000000..d3641c9 --- /dev/null +++ b/patchset-hrev55144/0093-kernel-arch-thread-implement-for-riscv64-2.patch @@ -0,0 +1,142 @@ +From a030f5da0aec3efc442d12c7c78112e53c072a07 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 02:58:57 +0900 +Subject: kernel/arch/thread: implement for riscv64 (2) + +Change-Id: I2f3a3604d8eb8ea6ac481d985485d9e5b5a1820b +--- + .../kernel/arch/riscv64/arch_thread.cpp | 39 ++++++++++++------- + 1 file changed, 25 insertions(+), 14 deletions(-) + +diff --git a/src/system/kernel/arch/riscv64/arch_thread.cpp b/src/system/kernel/arch/riscv64/arch_thread.cpp +index 2a17506e9e..fc9ea69ba6 100644 +--- a/src/system/kernel/arch/riscv64/arch_thread.cpp ++++ b/src/system/kernel/arch/riscv64/arch_thread.cpp +@@ -55,20 +55,29 @@ arch_thread_init_thread_struct(Thread *thread) + } + + ++static inline VMAddressSpace* ++GetThreadAddressSpace(Thread* thread) ++{ ++/* ++ if (thread->team == team_get_kernel_team()) ++ return VMAddressSpace::Kernel(); ++*/ ++ return thread->team->address_space; ++} ++ ++ + void + arch_thread_init_kthread_stack(Thread* thread, void* _stack, void* _stackTop, + void (*function)(void*), const void* data) + { +- dprintf("arch_thread_init_kthread_stack(%p(%s))\n", thread, thread->name); ++ // dprintf("arch_thread_init_kthread_stack(%p(%s))\n", thread, thread->name); + memset(&thread->arch_info.context, 0, sizeof(arch_context)); + thread->arch_info.context.sp = (addr_t)_stackTop; + thread->arch_info.context.s[0] = 0; // fp + thread->arch_info.context.s[1] = (addr_t)function; + thread->arch_info.context.s[2] = (addr_t)data; + thread->arch_info.context.ra = (addr_t)arch_thread_entry; +- VMTranslationMap* map = (thread->team == team_get_kernel_team()) +- ? VMAddressSpace::Kernel()->TranslationMap() +- : thread->team->address_space->TranslationMap(); ++ VMTranslationMap* map = GetThreadAddressSpace(thread)->TranslationMap(); + thread->arch_info.context.satp = ((RISCV64VMTranslationMap*)map)->Satp(); + } + +@@ -98,9 +107,9 @@ arch_thread_context_switch(Thread *from, Thread *to) + dprintf("arch_thread_context_switch(%p(%s), %p(%s))\n", from, from->name, + to, to->name); + */ ++ // TODO: save/restore FPU only if needed ++ save_fpu(&from->arch_info.fpuContext); + if (arch_setjmp(&from->arch_info.context) == 0) { +- // TODO: save/restore FPU only if needed +- save_fpu(&from->arch_info.fpuContext); + arch_longjmp(&to->arch_info.context, 1); + } else { + restore_fpu(&from->arch_info.fpuContext); +@@ -118,7 +127,7 @@ status_t + arch_thread_enter_userspace(Thread *thread, addr_t entry, void *arg1, + void *arg2) + { +- dprintf("arch_thread_enter_uspace()\n"); ++ // dprintf("arch_thread_enter_uspace()\n"); + + disable_interrupts(); + if (arch_setjmp(&thread->arch_info.context) == 0) { +@@ -177,7 +186,7 @@ status_t + arch_setup_signal_frame(Thread *thread, struct sigaction *sa, + struct signal_frame_data *signalFrameData) + { +- dprintf("arch_setup_signal_frame()\n"); ++ // dprintf("arch_setup_signal_frame()\n"); + iframe* frame = thread->arch_info.userFrame; + + // fill signal context +@@ -218,7 +227,7 @@ arch_setup_signal_frame(Thread *thread, struct sigaction *sa, + // end of fill signal context + + signal_get_user_stack(frame->sp, &signalFrameData->context.uc_stack); +- ++/* + dprintf(" thread->signal_stack_enabled: %d\n", + thread->signal_stack_enabled); + if (thread->signal_stack_enabled) { +@@ -227,17 +236,17 @@ arch_setup_signal_frame(Thread *thread, struct sigaction *sa, + thread->signal_stack_base + thread->signal_stack_size + ); + } +- ++*/ + uint8* userStack = get_signal_stack(thread, frame, sa, + sizeof(*signalFrameData)); +- dprintf(" user stack: 0x%" B_PRIxADDR "\n", (addr_t)userStack); ++ // dprintf(" user stack: 0x%" B_PRIxADDR "\n", (addr_t)userStack); + status_t res = user_memcpy(userStack, signalFrameData, + sizeof(*signalFrameData)); + if (res < B_OK) + return res; + + addr_t commpageAdr = (addr_t)thread->team->commpage_address; +- dprintf(" commpageAdr: 0x%" B_PRIxADDR "\n", commpageAdr); ++ // dprintf(" commpageAdr: 0x%" B_PRIxADDR "\n", commpageAdr); + addr_t signalHandlerAddr; + ASSERT(user_memcpy(&signalHandlerAddr, + &((addr_t*)commpageAdr)[COMMPAGE_ENTRY_RISCV64_SIGNAL_HANDLER], +@@ -258,7 +267,7 @@ arch_setup_signal_frame(Thread *thread, struct sigaction *sa, + int64 + arch_restore_signal_frame(struct signal_frame_data* signalFrameData) + { +- dprintf("arch_restore_signal_frame()\n"); ++ // dprintf("arch_restore_signal_frame()\n"); + iframe* frame = thread_get_current_thread()->arch_info.userFrame; + + frame->ra = signalFrameData->context.uc_mcontext.x[ 0]; +@@ -314,10 +323,12 @@ arch_check_syscall_restart(Thread *thread) + void + arch_store_fork_frame(struct arch_fork_arg *arg) + { ++/* + dprintf("arch_store_fork_frame()\n"); + dprintf(" arg: %p\n", arg); + dprintf(" userFrame: %p\n", + thread_get_current_thread()->arch_info.userFrame); ++*/ + memcpy(&arg->frame, thread_get_current_thread()->arch_info.userFrame, + sizeof(iframe)); + arg->frame.a0 = 0; // fork return value +@@ -335,7 +346,7 @@ arch_store_fork_frame(struct arch_fork_arg *arg) + void + arch_restore_fork_frame(struct arch_fork_arg *arg) + { +- dprintf("arch_restore_fork_frame(%p)\n", arg); ++ // dprintf("arch_restore_fork_frame(%p)\n", arg); + disable_interrupts(); + if (arch_setjmp(&thread_get_current_thread()->arch_info.context) == 0) { + SstatusReg status(Sstatus()); +-- +2.30.2 + diff --git a/patchset-hrev55144/0094-kernel-arch-int-implement-for-riscv64-2.patch b/patchset-hrev55144/0094-kernel-arch-int-implement-for-riscv64-2.patch new file mode 100644 index 0000000..a35fbb1 --- /dev/null +++ b/patchset-hrev55144/0094-kernel-arch-int-implement-for-riscv64-2.patch @@ -0,0 +1,632 @@ +From 064dab2f1de7e22a5f058b59c01e19f434e71cc0 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:00:08 +0900 +Subject: kernel/arch/int: implement for riscv64 (2) + +Change-Id: Ic7722f6787a971cb208eb71a86bd3fd98fb3e690 +--- + .../private/kernel/arch/riscv64/arch_int.h | 6 +- + .../private/kernel/arch/riscv64/arch_traps.h | 88 +++++ + src/system/kernel/arch/riscv64/arch_int.cpp | 319 +++++++++++------- + src/system/kernel/arch/riscv64/arch_traps.S | 50 --- + 4 files changed, 292 insertions(+), 171 deletions(-) + create mode 100644 headers/private/kernel/arch/riscv64/arch_traps.h + +diff --git a/headers/private/kernel/arch/riscv64/arch_int.h b/headers/private/kernel/arch/riscv64/arch_int.h +index 85331a8c0d..db1867716e 100644 +--- a/headers/private/kernel/arch/riscv64/arch_int.h ++++ b/headers/private/kernel/arch/riscv64/arch_int.h +@@ -61,11 +61,11 @@ arch_int_are_interrupts_enabled_inline(void) + + + enum { +- switchToSmodeMmodeSyscall = 0, +- setTimerMmodeSyscall = 1, ++ kMSyscallSwitchToSmode = 0, ++ kMSyscallSetTimer = 1, + }; + +-extern "C" status_t MSyscall(...); ++extern "C" status_t MSyscall(uint64 op, ...); + + + #endif /* _KERNEL_ARCH_RISCV64_INT_H */ +diff --git a/headers/private/kernel/arch/riscv64/arch_traps.h b/headers/private/kernel/arch/riscv64/arch_traps.h +new file mode 100644 +index 0000000000..8afc947b7e +--- /dev/null ++++ b/headers/private/kernel/arch/riscv64/arch_traps.h +@@ -0,0 +1,88 @@ ++/* ++ * Copyright 2021, Haiku, Inc. ++ * Distributed under the terms of the MIT License. ++ */ ++ ++ ++#ifndef _ARCH_TRAPS_H_ ++#define _ARCH_TRAPS_H_ ++ ++ ++# NOTE: this macro don't save SP, it should be saved manually ++.macro PushTrapFrame ++ addi sp, sp, -256 ++ ++ sd ra, 0*8(sp) ++ sd t6, 1*8(sp) ++# sd sp, 2*8(sp) # sp ++ sd gp, 3*8(sp) ++ sd tp, 4*8(sp) ++ sd t0, 5*8(sp) ++ sd t1, 6*8(sp) ++ sd t2, 7*8(sp) ++ sd t5, 8*8(sp) ++ sd s1, 9*8(sp) ++ sd a0, 10*8(sp) ++ sd a1, 11*8(sp) ++ sd a2, 12*8(sp) ++ sd a3, 13*8(sp) ++ sd a4, 14*8(sp) ++ sd a5, 15*8(sp) ++ sd a6, 16*8(sp) ++ sd a7, 17*8(sp) ++ sd s2, 18*8(sp) ++ sd s3, 19*8(sp) ++ sd s4, 20*8(sp) ++ sd s5, 21*8(sp) ++ sd s6, 22*8(sp) ++ sd s7, 23*8(sp) ++ sd s8, 24*8(sp) ++ sd s9, 25*8(sp) ++ sd s10, 26*8(sp) ++ sd s11, 27*8(sp) ++ sd t3, 28*8(sp) ++ sd t4, 29*8(sp) ++ sd fp, 30*8(sp) ++ ++ addi fp, sp, 256 ++.endm ++ ++ ++.macro PopTrapFrame ++ ld ra, 0*8(sp) ++ ld t6, 1*8(sp) ++# ld sp, 2*8(sp) restore later ++ ld gp, 3*8(sp) ++# ld tp, 4*8(sp) ++ ld t0, 5*8(sp) ++ ld t1, 6*8(sp) ++ ld t2, 7*8(sp) ++ ld t5, 8*8(sp) ++ ld s1, 9*8(sp) ++ ld a0, 10*8(sp) ++ ld a1, 11*8(sp) ++ ld a2, 12*8(sp) ++ ld a3, 13*8(sp) ++ ld a4, 14*8(sp) ++ ld a5, 15*8(sp) ++ ld a6, 16*8(sp) ++ ld a7, 17*8(sp) ++ ld s2, 18*8(sp) ++ ld s3, 19*8(sp) ++ ld s4, 20*8(sp) ++ ld s5, 21*8(sp) ++ ld s6, 22*8(sp) ++ ld s7, 23*8(sp) ++ ld s8, 24*8(sp) ++ ld s9, 25*8(sp) ++ ld s10, 26*8(sp) ++ ld s11, 27*8(sp) ++ ld t3, 28*8(sp) ++ ld t4, 29*8(sp) ++ ld fp, 30*8(sp) ++ ++ ld sp, 2*8(sp) ++.endm ++ ++ ++#endif // _ARCH_TRAPS_H_ +diff --git a/src/system/kernel/arch/riscv64/arch_int.cpp b/src/system/kernel/arch/riscv64/arch_int.cpp +index d4e382cfa4..95af34f489 100644 +--- a/src/system/kernel/arch/riscv64/arch_int.cpp ++++ b/src/system/kernel/arch/riscv64/arch_int.cpp +@@ -20,15 +20,16 @@ + #include + #include + #include ++#include ++#include "RISCV64VMTranslationMap.h" + + #include + + +-__attribute__ ((aligned (16))) char sMStack[64*1024]; ++static uint32 sBootHartId = 0; ++static int32 sPlicContextOfs = 0; + + +-extern "C" void MVec(); +-extern "C" void MVecS(); + extern "C" void SVec(); + extern "C" void SVecU(); + +@@ -153,87 +154,20 @@ WriteCause(uint64_t cause) + void + WriteTrapInfo() + { ++ InterruptsLocker locker; + dprintf("STrap("); WriteCause(Scause()); dprintf(")\n"); + dprintf(" sstatus: "); WriteSstatus(Sstatus()); dprintf("\n"); + dprintf(" sie: "); WriteInterruptSet(Sie()); dprintf("\n"); + dprintf(" sip: "); WriteInterruptSet(Sip()); dprintf("\n"); +- dprintf(" stval: "); WritePC(Stval()); dprintf("\n"); ++ //dprintf(" stval: "); WritePC(Stval()); dprintf("\n"); ++ dprintf(" stval: 0x%" B_PRIx64 "\n", Stval()); + dprintf(" tp: 0x%" B_PRIxADDR "(%s)\n", Tp(), + thread_get_current_thread()->name); +- //dprintf(" stval: 0x%" B_PRIx64 "\n", Stval()); + } + + + //#pragma mark - + +-extern "C" void +-MTrap(iframe* frame) +-{ +- uint64 cause = Mcause(); +-/* +- HtifOutString("+MTrap("); WriteCause(Mcause()); HtifOutString(")\n"); +- dprintf(" mstatus: "); WriteMstatus(Mstatus()); dprintf("\n"); +- dprintf(" mie: "); WriteInterruptSet(Mie()); dprintf("\n"); +- dprintf(" mip: "); WriteInterruptSet(Mip()); dprintf("\n"); +- dprintf(" sie: "); WriteInterruptSet(Sie()); dprintf("\n"); +- dprintf(" sip: "); WriteInterruptSet(Sip()); dprintf("\n"); +- dprintf(" mscratch: 0x%" B_PRIxADDR "\n", Mscratch()); +- DoStackTrace(Fp(), 0); +-*/ +- switch (cause) { +- case causeMEcall: +- case causeSEcall: { +- frame->epc += 4; +- uint64 op = frame->a0; +- switch (op) { +- case switchToSmodeMmodeSyscall: { +- HtifOutString("switchToSmodeMmodeSyscall()\n"); +- MstatusReg status(Mstatus()); +- status.mpp = modeS; +- SetMedeleg( +- 0xffff & ~((1 << causeMEcall) | (1 << causeSEcall))); +- SetMideleg(0xffff & ~(1 << mTimerInt)); +- SetMstatus(status.val); +- dprintf("modeM stack: 0x%" B_PRIxADDR ", 0x%" B_PRIxADDR +- "\n", (addr_t)sMStack, +- (addr_t)(sMStack + sizeof(sMStack))); +- SetMscratch((addr_t)(sMStack + sizeof(sMStack))); +- SetMtvec((uint64)MVecS); +- frame->a0 = B_OK; +- return; +- } +- case setTimerMmodeSyscall: { +- // HtifOutString("setTimerMmodeSyscall()\n"); +- bool enable = frame->a1 != 0; +- SetSip(Sip() & ~(1 << sTimerInt)); +- if (!enable) { +- SetMie(Mie() & ~(1 << mTimerInt)); +- } else { +- gClintRegs->mTimeCmp[0] = frame->a2; +- SetMie(Mie() | (1 << mTimerInt)); +- } +- frame->a0 = B_OK; +- return; +- } +- default: +- frame->a0 = B_NOT_SUPPORTED; +- return; +- } +- break; +- } +- case causeInterrupt + mTimerInt: { +- disable_interrupts(); +- SetMie(Mie() & ~(1 << mTimerInt)); +- SetMip(Mip() | (1 << sTimerInt)); +- return; +- } +- } +- HtifOutString("unhandled MTrap\n"); +- // DoStackTrace(Fp(), 0); +- HtifShutdown(); +-} +- +- + static void + SendSignal(debug_exception_type type, uint32 signalNumber, int32 signalCode, + addr_t signalAddress = 0, int32 signalError = B_ERROR) +@@ -268,6 +202,9 @@ SendSignal(debug_exception_type type, uint32 signalNumber, int32 signalCode, + static void + AfterInterrupt() + { ++ if (debug_debugger_running()) ++ return; ++ + Thread* thread = thread_get_current_thread(); + cpu_status state = disable_interrupts(); + if (thread->cpu->invoke_scheduler) { +@@ -289,74 +226,218 @@ AfterInterrupt() + } + + ++static bool ++SetAccessedFlags(addr_t addr, bool isWrite) ++{ ++ VMAddressSpacePutter addressSpace; ++ if (IS_KERNEL_ADDRESS(addr)) ++ addressSpace.SetTo(VMAddressSpace::GetKernel()); ++ else if (IS_USER_ADDRESS(addr)) ++ addressSpace.SetTo(VMAddressSpace::GetCurrent()); ++ ++ if(!addressSpace.IsSet()) ++ return false; ++ ++ RISCV64VMTranslationMap* map ++ = (RISCV64VMTranslationMap*)addressSpace->TranslationMap(); ++ ++ phys_addr_t physAdr; ++ uint32 pageFlags; ++ map->QueryInterrupt(addr, &physAdr, &pageFlags); ++ if (isWrite) { ++ if ( ++ ((B_WRITE_AREA | B_KERNEL_WRITE_AREA) & pageFlags) != 0 ++ && ((PAGE_ACCESSED | PAGE_MODIFIED) & pageFlags) ++ != (PAGE_ACCESSED | PAGE_MODIFIED) ++ ) { ++ map->SetFlags(addr, PAGE_ACCESSED | PAGE_MODIFIED); ++/* ++ dprintf("SetAccessedFlags(%#" B_PRIxADDR ", %d)\n", addr, isWrite); ++*/ ++ return true; ++ } ++ } else { ++ if ( ++ ((B_READ_AREA | B_KERNEL_READ_AREA) & pageFlags) != 0 ++ && (PAGE_ACCESSED & pageFlags) == 0 ++ ) { ++ map->SetFlags(addr, PAGE_ACCESSED); ++/* ++ dprintf("SetAccessedFlags(%#" B_PRIxADDR ", %d)\n", addr, isWrite); ++*/ ++ return true; ++ } ++ } ++ return false; ++} ++ ++ ++static void ++WriteProtection(uint32 flags) ++{ ++ dprintf("kernel: {"); ++ if (B_KERNEL_READ_AREA & flags) dprintf("R"); ++ if (B_KERNEL_WRITE_AREA & flags) dprintf("W"); ++ if (B_KERNEL_EXECUTE_AREA & flags) dprintf("X"); ++ if (B_KERNEL_STACK_AREA & flags) dprintf("S"); ++ dprintf("}, user: {"); ++ if (B_READ_AREA & flags) dprintf("R"); ++ if (B_WRITE_AREA & flags) dprintf("W"); ++ if (B_EXECUTE_AREA & flags) dprintf("X"); ++ if (B_STACK_AREA & flags) dprintf("S"); ++ dprintf("}"); ++} ++ ++ ++template ++class ScopeExit ++{ ++public: ++ explicit ScopeExit(F&& fn) : fFn(fn) ++ { ++ } ++ ++ ~ScopeExit() ++ { ++ fFn(); ++ } ++ ++ ScopeExit(ScopeExit&& other) : fFn(std::move(other.fFn)) ++ { ++ } ++ ++private: ++ ScopeExit(const ScopeExit&); ++ ScopeExit& operator=(const ScopeExit&); ++ ++private: ++ F fFn; ++}; ++ ++template ++ScopeExit MakeScopeExit(F&& fn) ++{ ++ return ScopeExit(std::move(fn)); ++} ++ ++ + extern "C" void + STrap(iframe* frame) + { + // dprintf("STrap("); WriteCause(Scause()); dprintf(")\n"); +- if (SstatusReg(Sstatus()).spp == modeU) { ++ ++ SstatusReg status(Sstatus()); ++ uint64 cause = Scause(); ++ ++ const auto& statusRestorer = MakeScopeExit([&]() { ++ SetSstatus(status.val); ++ }); ++ ++ switch (cause) { ++ case causeExecPageFault: ++ case causeLoadPageFault: ++ case causeStorePageFault: { ++ if (SetAccessedFlags(Stval(), cause == causeStorePageFault)) ++ return; ++ } ++ } ++ ++ if (status.spp == modeU) { + thread_get_current_thread()->arch_info.userFrame = frame; + thread_at_kernel_entry(system_time()); + } +- struct ScopeExit { +- ~ScopeExit() +- { +- if (SstatusReg(Sstatus()).spp == modeU) { +- if ((thread_get_current_thread()->flags +- & (THREAD_FLAGS_SIGNALS_PENDING +- | THREAD_FLAGS_DEBUG_THREAD +- | THREAD_FLAGS_TRAP_FOR_CORE_DUMP)) != 0) { +- enable_interrupts(); +- thread_at_kernel_exit(); +- } else { +- thread_at_kernel_exit_no_signals(); +- } +- thread_get_current_thread()->arch_info.userFrame = NULL; ++ const auto& kernelExit = MakeScopeExit([&]() { ++ if (status.spp == modeU) { ++ disable_interrupts(); ++ if ((thread_get_current_thread()->flags ++ & (THREAD_FLAGS_SIGNALS_PENDING ++ | THREAD_FLAGS_DEBUG_THREAD ++ | THREAD_FLAGS_TRAP_FOR_CORE_DUMP)) != 0) { ++ enable_interrupts(); ++ thread_at_kernel_exit(); ++ } else { ++ thread_at_kernel_exit_no_signals(); + } ++ thread_get_current_thread()->arch_info.userFrame = NULL; + } +- } scopeExit; ++ }); + +- uint64 cause = Scause(); + switch (cause) { +- case causeIllegalInst: ++ case causeIllegalInst: { + return SendSignal(B_INVALID_OPCODE_EXCEPTION, SIGILL, ILL_ILLOPC, + frame->epc); ++ } + case causeExecMisalign: + case causeLoadMisalign: +- case causeStoreMisalign: ++ case causeStoreMisalign: { + return SendSignal(B_ALIGNMENT_EXCEPTION, SIGBUS, BUS_ADRALN, + Stval()); ++ } + // case causeBreakpoint: +- // case causeExecAccessFault: +- // case causeLoadAccessFault: +- // case causeStoreAccessFault: ++ case causeExecAccessFault: ++ case causeLoadAccessFault: ++ case causeStoreAccessFault: { ++ return SendSignal(B_SEGMENT_VIOLATION, SIGBUS, BUS_ADRERR, ++ Stval()); ++ } + case causeExecPageFault: + case causeLoadPageFault: + case causeStorePageFault: { + uint64 stval = Stval(); +- SstatusReg status(Sstatus()); ++ ++ if (debug_debugger_running()) { ++ Thread* thread = thread_get_current_thread(); ++ if (thread != NULL) { ++ cpu_ent* cpu = &gCPU[smp_get_current_cpu()]; ++ if (cpu->fault_handler != 0) { ++ debug_set_page_fault_info(stval, frame->epc, ++ (cause == causeStorePageFault) ++ ? DEBUG_PAGE_FAULT_WRITE : 0); ++ frame->epc = cpu->fault_handler; ++ frame->sp = cpu->fault_handler_stack_pointer; ++ return; ++ } ++ ++ if (thread->fault_handler != 0) { ++ kprintf("ERROR: thread::fault_handler used in kernel " ++ "debugger!\n"); ++ debug_set_page_fault_info(stval, frame->epc, ++ cause == causeStorePageFault ++ ? DEBUG_PAGE_FAULT_WRITE : 0); ++ frame->epc = (addr_t)thread->fault_handler; ++ return; ++ } ++ } ++ ++ panic("page fault in debugger without fault handler! Touching " ++ "address %p from ip %p\n", (void*)stval, (void*)frame->epc); ++ return; ++ } ++ ++ if (status.pie == 0) { ++ WriteTrapInfo(); ++ panic("page fault with interrupts disabled@!dump_virt_page %#" B_PRIx64, stval); ++ } ++ + addr_t newIP = 0; + enable_interrupts(); + vm_page_fault(stval, frame->epc, cause == causeStorePageFault, +- cause == causeExecPageFault, status.spp == modeU, &newIP); ++ cause == causeExecPageFault, status.spp == modeU, status.sum != 0, &newIP); + if (newIP != 0) + frame->epc = newIP; +- SetSstatus(status.val); ++ + return; + } + case causeInterrupt + sTimerInt: { +- SstatusReg status(Sstatus()); + timer_interrupt(); + AfterInterrupt(); +- SetSstatus(status.val); + return; + } + case causeInterrupt + sExternInt: { +- SstatusReg status(Sstatus()); +- uint64 irq = gPlicRegs->contexts[0].claimAndComplete; ++ uint64 irq = gPlicRegs->contexts[modeS + 2*sBootHartId + sPlicContextOfs].claimAndComplete; + int_io_interrupt_handler(irq, true); +- gPlicRegs->contexts[0].claimAndComplete = irq; ++ gPlicRegs->contexts[modeS + 2*sBootHartId + sPlicContextOfs].claimAndComplete = irq; + AfterInterrupt(); +- SetSstatus(status.val); + return; + } + case causeUEcall: { +@@ -387,12 +468,10 @@ STrap(iframe* frame) + } + */ + // dprintf("syscall: %s\n", kExtendedSyscallInfos[syscall].name); +- SstatusReg status(Sstatus()); + enable_interrupts(); + uint64 returnValue = 0; + syscall_dispatcher(syscall, (void*)args, &returnValue); + frame->a0 = returnValue; +- SetSstatus(status.val); + return; + } + } +@@ -406,19 +485,21 @@ STrap(iframe* frame) + status_t + arch_int_init(kernel_args* args) + { +- SetMtvec((uint64)MVec); ++ sBootHartId = args->arch_args.bootHart; ++ sPlicContextOfs = (sBootHartId == 0) ? 0 : -1; ++ + SetStvec((uint64)SVec); +- MstatusReg mstatus(Mstatus()); +- mstatus.ie = 1 << modeM; +- mstatus.fs = extStatusInitial; // enable FPU +- mstatus.xs = extStatusOff; +- SetMstatus(mstatus.val); +- MSyscall(switchToSmodeMmodeSyscall); ++ SstatusReg sstatus(Sstatus()); ++ sstatus.ie = 0; ++ sstatus.fs = extStatusInitial; // enable FPU ++ sstatus.xs = extStatusOff; ++ SetSstatus(sstatus.val); + SetSie(Sie() | (1 << sTimerInt) | (1 << sExternInt)); + + // TODO: read from FDT +- reserve_io_interrupt_vectors(32, 0, INTERRUPT_TYPE_IRQ); ++ reserve_io_interrupt_vectors(128, 0, INTERRUPT_TYPE_IRQ); + ++ gPlicRegs->contexts[modeS + 2*sBootHartId + sPlicContextOfs].priorityThreshold = 0; + return B_OK; + } + +@@ -447,16 +528,18 @@ arch_int_init_io(kernel_args* args) + void + arch_int_enable_io_interrupt(int irq) + { +- // not implemented by TinyEMU +- gPlicRegs->enable[0][irq / 32] |= 1 << (irq % 32); ++ dprintf("arch_int_enable_io_interrupt(%d)\n", irq); ++ gPlicRegs->priority[irq] = 1; ++ gPlicRegs->enable[modeS + 2*sBootHartId + sPlicContextOfs][irq / 32] |= 1 << (irq % 32); + } + + + void + arch_int_disable_io_interrupt(int irq) + { +- // not implemented by TinyEMU +- gPlicRegs->enable[0][irq / 32] &= ~(1 << (irq % 32)); ++ dprintf("arch_int_disable_io_interrupt(%d)\n", irq); ++ gPlicRegs->priority[irq] = 0; ++ gPlicRegs->enable[modeS + 2*sBootHartId + sPlicContextOfs][irq / 32] &= ~(1 << (irq % 32)); + } + + +diff --git a/src/system/kernel/arch/riscv64/arch_traps.S b/src/system/kernel/arch/riscv64/arch_traps.S +index a8e7fe9b6b..dcadb6ed51 100644 +--- a/src/system/kernel/arch/riscv64/arch_traps.S ++++ b/src/system/kernel/arch/riscv64/arch_traps.S +@@ -7,56 +7,6 @@ + #include "arch_traps.h" + + +-.globl MVec +-.type MVec, @function +-.align 4 +-MVec: +- PushTrapFrame +- sd fp, 2*8(sp) +- csrr t0, mepc +- sd t0, 31*8(sp) +- +- mv a0, sp +- call MTrap +- +- ld t0, 31*8(sp) +- csrw mepc, t0 +- PopTrapFrame +- mret +-.size MVec, .-MVec +- +- +-.globl MVecS +-.type MVecS, @function +-.align 4 +-MVecS: +- csrrw sp, mscratch, sp +- +- PushTrapFrame +- +- csrr t0, mscratch +- sd t0, 2*8(sp) # save supervisor SP +- csrw mscratch, fp +- +- csrr t0, mepc +- sd t0, 31*8(sp) +- +- la t0, MVec +- csrw mtvec, t0 +- +- mv a0, sp +- call MTrap +- +- la t0, MVecS +- csrw mtvec, t0 +- +- ld t0, 31*8(sp) +- csrw mepc, t0 +- PopTrapFrame +- mret +-.size MVecS, .-MVecS +- +- + .globl SVec + .type SVec, @function + .align 4 +-- +2.30.2 + diff --git a/patchset-hrev55144/0095-kernel-arch-debug-implement-for-riscv64-2.patch b/patchset-hrev55144/0095-kernel-arch-debug-implement-for-riscv64-2.patch new file mode 100644 index 0000000..d75264f --- /dev/null +++ b/patchset-hrev55144/0095-kernel-arch-debug-implement-for-riscv64-2.patch @@ -0,0 +1,266 @@ +From f022e2de36abda84470e0367ae806caa598038e9 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:02:16 +0900 +Subject: kernel/arch/debug: implement for riscv64 (2) + +Change-Id: I5ef3ecd30c13a6379ed428b8c91dd1427e2e85c1 +--- + src/system/kernel/arch/riscv64/arch_debug.cpp | 82 +++++++++++++++++-- + .../arch/riscv64/arch_debug_console.cpp | 55 ++++++++++++- + 2 files changed, 126 insertions(+), 11 deletions(-) + +diff --git a/src/system/kernel/arch/riscv64/arch_debug.cpp b/src/system/kernel/arch/riscv64/arch_debug.cpp +index 880fd93851..5bc6eb4b8d 100644 +--- a/src/system/kernel/arch/riscv64/arch_debug.cpp ++++ b/src/system/kernel/arch/riscv64/arch_debug.cpp +@@ -24,6 +24,7 @@ static void + WriteImage(preloaded_image* _image) + { + preloaded_elf64_image* image = (preloaded_elf64_image*)_image; ++ dprintf("image %p\n", image); + dprintf("image \"%s\"\n", (char*)image->name); + dprintf( + " text: 0x%" B_PRIxADDR " - 0x%" B_PRIxADDR ", %" B_PRIdSSIZE "\n", +@@ -104,9 +105,15 @@ FindImage(addr_t adr) + static VMArea* + FindArea(addr_t adr) + { +- VMAddressSpacePutter addrSpace; +- addrSpace.SetTo(VMAddressSpace::GetCurrent()); +- return addrSpace->LookupArea(adr); ++ if (IS_KERNEL_ADDRESS(adr)) { ++ VMAddressSpacePutter addrSpace(VMAddressSpace::GetKernel()); ++ return addrSpace->LookupArea(adr); ++ } ++ if (IS_USER_ADDRESS(adr)) { ++ VMAddressSpacePutter addrSpace(VMAddressSpace::GetCurrent()); ++ return addrSpace->LookupArea(adr); ++ } ++ return NULL; + } + + +@@ -120,7 +127,7 @@ lookup_symbol(Thread* thread, addr_t address, addr_t* _baseAddress, + // a kernel symbol + status = elf_debug_lookup_symbol_address(address, _baseAddress, + _symbolName, _imageName, _exactMatch); +- } else if (thread != NULL && thread->team != NULL) { ++ } else if (true && thread != NULL && thread->team != NULL) { + // try a lookup using the userland runtime loader structures + status = elf_debug_lookup_user_symbol_address(thread->team, address, + _baseAddress, _symbolName, _imageName, _exactMatch); +@@ -165,7 +172,7 @@ WritePCBoot(addr_t pc) + void + WritePC(addr_t pc) + { +- // dprintf("0x%" B_PRIxADDR " ", pc); ++ dprintf("0x%" B_PRIxADDR " ", pc); + if (!sInitCalled) { + WritePCBoot(pc); return; + } +@@ -195,6 +202,27 @@ WritePC(addr_t pc) + } + + ++static void ++DumpMemory(uint64* adr, size_t len) ++{ ++ while (len > 0) { ++ if ((addr_t)adr % 0x10 == 0) ++ dprintf("%08" B_PRIxADDR " ", (addr_t)adr); ++ uint64 val; ++ if (user_memcpy(&val, adr++, sizeof(val)) < B_OK) { ++ dprintf(" ????????????????"); ++ } else { ++ dprintf(" %016" B_PRIx64, val); ++ } ++ if ((addr_t)adr % 0x10 == 0) ++ dprintf("\n"); ++ len -= 8; ++ } ++ if ((addr_t)adr % 0x10 != 0) ++ dprintf("\n"); ++} ++ ++ + void + DoStackTrace(addr_t fp, addr_t pc) + { +@@ -204,12 +232,26 @@ DoStackTrace(addr_t fp, addr_t pc) + dprintf(", PC: "); WritePC(pc); + } + dprintf("\n"); ++ addr_t oldFp = fp; + while (fp != 0) { +- if (user_memcpy(&pc, (uint64*)fp - 1, sizeof(pc)) < B_OK) break; +- if (user_memcpy(&fp, (uint64*)fp - 2, sizeof(pc)) < B_OK) break; ++ if ( ++ (pc >= (addr_t)&strcpy && pc < (addr_t)&strcpy + 32) || ++ (pc >= (addr_t)&memset && pc < (addr_t)&memset + 34) ++ ) { ++ if (user_memcpy(&fp, (uint64*)fp - 1, sizeof(pc)) < B_OK) break; ++ pc = 0; ++ } else { ++ if (user_memcpy(&pc, (uint64*)fp - 1, sizeof(pc)) < B_OK) break; ++ if (user_memcpy(&fp, (uint64*)fp - 2, sizeof(pc)) < B_OK) break; ++ } + dprintf("FP: 0x%" B_PRIxADDR, fp); +- dprintf(", PC: "); WritePC(pc - 1); ++ dprintf(", PC: "); WritePC((pc == 0) ? 0 : pc - 1); + dprintf("\n"); ++/* ++ if (IS_KERNEL_ADDRESS(oldFp) && IS_KERNEL_ADDRESS(fp)) ++ DumpMemory((uint64*)oldFp, (addr_t)fp - (addr_t)oldFp); ++*/ ++ oldFp = fp; + } + } + +@@ -217,6 +259,19 @@ DoStackTrace(addr_t fp, addr_t pc) + static int + stack_trace(int argc, char **argv) + { ++ if (argc >= 2) { ++ thread_id id = strtoul(argv[1], NULL, 0); ++ Thread* thread = Thread::GetDebug(id); ++ if (thread == NULL) { ++ kprintf("could not find thread %" B_PRId32 "\n", id); ++ return 0; ++ } ++ uint64 oldSatp = Satp(); ++ SetSatp(thread->arch_info.context.satp); ++ DoStackTrace(thread->arch_info.context.s[0], thread->arch_info.context.ra); ++ SetSatp(oldSatp); ++ return 0; ++ } + DoStackTrace(Fp(), 0); + return 0; + } +@@ -250,10 +305,21 @@ arch_debug_save_registers(struct arch_debug_registers* registers) + } + + ++static void __attribute__((naked)) ++HandleFault() ++{ ++ asm volatile("ld a0, 0(sp)"); ++ asm volatile("li a1, 1"); ++ asm volatile("call longjmp"); ++} ++ ++ + void + arch_debug_call_with_fault_handler(cpu_ent* cpu, jmp_buf jumpBuffer, + void (*function)(void*), void* parameter) + { ++ cpu->fault_handler = (addr_t)&HandleFault; ++ cpu->fault_handler_stack_pointer = (addr_t)&jumpBuffer; + function(parameter); + } + +diff --git a/src/system/kernel/arch/riscv64/arch_debug_console.cpp b/src/system/kernel/arch/riscv64/arch_debug_console.cpp +index 6f82d72773..b662cf6eae 100644 +--- a/src/system/kernel/arch/riscv64/arch_debug_console.cpp ++++ b/src/system/kernel/arch/riscv64/arch_debug_console.cpp +@@ -11,11 +11,35 @@ + #include + #include + #include ++#include ++#include ++#include + #include + + #include + + ++static DebugUART* sArchDebugUART = NULL; ++ ++ ++DebugUART8250* ++arch_get_uart_8250(addr_t base, int64 clock) ++{ ++ static char buffer[sizeof(DebugUART8250)]; ++ DebugUART8250* uart = new(buffer) DebugUART8250(base, clock); ++ return uart; ++} ++ ++ ++ArchUARTSifive* ++arch_get_uart_sifive(addr_t base, int64 clock) ++{ ++ static char buffer[sizeof(ArchUARTSifive)]; ++ ArchUARTSifive* uart = new(buffer) ArchUARTSifive(base, clock); ++ return uart; ++} ++ ++ + void + arch_debug_remove_interrupt_handler(uint32 line) + { +@@ -53,6 +77,9 @@ arch_debug_serial_try_getchar(void) + char + arch_debug_serial_getchar(void) + { ++ if (sArchDebugUART != NULL) ++ return sArchDebugUART->GetChar(false); ++ + return 0; + } + +@@ -60,6 +87,11 @@ arch_debug_serial_getchar(void) + void + arch_debug_serial_putchar(const char c) + { ++ if (sArchDebugUART != NULL) { ++ sArchDebugUART->PutChar(c); ++ return; ++ } ++ + HtifOutChar(c); + } + +@@ -68,7 +100,12 @@ void + arch_debug_serial_puts(const char *s) + { + while (*s != '\0') { +- arch_debug_serial_putchar(*s); ++ char ch = *s; ++ if (ch == '\n') { ++ arch_debug_serial_putchar('\r'); ++ arch_debug_serial_putchar('\n'); ++ } else if (ch != '\r') ++ arch_debug_serial_putchar(ch); + s++; + } + } +@@ -84,6 +121,20 @@ arch_debug_serial_early_boot_message(const char *string) + status_t + arch_debug_console_init(kernel_args *args) + { ++ switch (args->arch_args.uart.kind) { ++ case kUartKind8250: ++ sArchDebugUART = arch_get_uart_8250(args->arch_args.uart.regs.start, args->arch_args.uart.clock); ++ break; ++ case kUartKindSifive: ++ sArchDebugUART = arch_get_uart_sifive(args->arch_args.uart.regs.start, args->arch_args.uart.clock); ++ break; ++ default: ++ ; ++ } ++ ++ if (sArchDebugUART != NULL) ++ sArchDebugUART->InitEarly(); ++ + return B_OK; + } + +@@ -93,5 +144,3 @@ arch_debug_console_init_settings(kernel_args *args) + { + return B_OK; + } +- +- +-- +2.30.2 + diff --git a/patchset-hrev55144/0096-kernel-arch-cpu-implement-for-riscv64-2.patch b/patchset-hrev55144/0096-kernel-arch-cpu-implement-for-riscv64-2.patch new file mode 100644 index 0000000..9feaadf --- /dev/null +++ b/patchset-hrev55144/0096-kernel-arch-cpu-implement-for-riscv64-2.patch @@ -0,0 +1,156 @@ +From 22965d4e66324c9d3f10e90405c017cabb5fd16e Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:04:33 +0900 +Subject: kernel/arch/cpu: implement for riscv64 (2) + +Change-Id: Ic989e5ff664d29d3240215496351eef3d506af47 +--- + .../private/kernel/arch/riscv64/arch_cpu.h | 32 +++++++++++++------ + .../kernel/boot/platform/efi/arch_smp.h | 15 +++++++++ + src/system/kernel/arch/riscv64/arch_cpu.cpp | 23 +++++++++++++ + 3 files changed, 60 insertions(+), 10 deletions(-) + +diff --git a/headers/private/kernel/arch/riscv64/arch_cpu.h b/headers/private/kernel/arch/riscv64/arch_cpu.h +index 5b1414898c..2b0dff4ded 100644 +--- a/headers/private/kernel/arch/riscv64/arch_cpu.h ++++ b/headers/private/kernel/arch/riscv64/arch_cpu.h +@@ -16,20 +16,29 @@ + #define CACHE_LINE_SIZE 64 + + +-inline void set_ac() ++static inline bool ++get_ac() + { +- return; +- SstatusReg sstatus(Sstatus()); +- sstatus.sum = 1; +- SetSstatus(sstatus.val); ++ SstatusReg status(Sstatus()); ++ return status.sum != 0; + } + +-inline void clear_ac() ++ ++static inline void ++set_ac() + { +- return; +- SstatusReg sstatus(Sstatus()); +- sstatus.sum = 0; +- SetSstatus(sstatus.val); ++ SstatusReg status(Sstatus()); ++ status.sum = 1; ++ SetSstatus(status.val); ++} ++ ++ ++static inline void ++clear_ac() ++{ ++ SstatusReg status(Sstatus()); ++ status.sum = 0; ++ SetSstatus(status.val); + } + + +@@ -43,6 +52,9 @@ extern "C" { + #endif + + ++void __riscv64_setup_system_time(uint64 conversionFactor); ++ ++ + static inline void + arch_cpu_pause(void) + { +diff --git a/headers/private/kernel/boot/platform/efi/arch_smp.h b/headers/private/kernel/boot/platform/efi/arch_smp.h +index c95a9e19e9..4a87605391 100644 +--- a/headers/private/kernel/boot/platform/efi/arch_smp.h ++++ b/headers/private/kernel/boot/platform/efi/arch_smp.h +@@ -8,9 +8,24 @@ + #include + + ++#ifdef __riscv ++ ++struct CpuInfo { ++ uint32 id; ++}; ++ ++void arch_smp_register_cpu(CpuInfo** cpu); ++ ++#endif ++ ++ + int arch_smp_get_current_cpu(void); + void arch_smp_init_other_cpus(void); ++#ifdef __riscv ++void arch_smp_boot_other_cpus(uint64 satp, uint64 kernel_entry); ++#else + void arch_smp_boot_other_cpus(uint32 pml4, uint64 kernel_entry); ++#endif + void arch_smp_add_safemode_menus(Menu *menu); + void arch_smp_init(void); + +diff --git a/src/system/kernel/arch/riscv64/arch_cpu.cpp b/src/system/kernel/arch/riscv64/arch_cpu.cpp +index 0bd867a9a6..d6a8000c69 100644 +--- a/src/system/kernel/arch/riscv64/arch_cpu.cpp ++++ b/src/system/kernel/arch/riscv64/arch_cpu.cpp +@@ -8,9 +8,15 @@ + + #include + #include ++#include + #include + #include + #include ++#include ++ ++ ++extern uint32 gPlatform1; ++extern uint32 gPlatform2; + + + status_t +@@ -33,6 +39,12 @@ arch_cpu_init_percpu(kernel_args *args, int curr_cpu) + status_t + arch_cpu_init(kernel_args *args) + { ++/* ++ uint64 conversionFactor ++ = (1LL << 32) * 1000000LL / args->arch_args.timerFrequrency; ++ ++ __riscv64_setup_system_time(conversionFactor); ++*/ + return B_OK; + } + +@@ -40,6 +52,11 @@ arch_cpu_init(kernel_args *args) + status_t + arch_cpu_init_post_vm(kernel_args *args) + { ++ // Set address space ownership to currently running threads ++ for (uint32 i = 0; i < args->num_cpus; i++) { ++ VMAddressSpace::Kernel()->Get(); ++ } ++ + return B_OK; + } + +@@ -96,6 +113,12 @@ arch_cpu_user_TLB_invalidate(void) + status_t + arch_cpu_shutdown(bool reboot) + { ++ if (gPlatform1 == kPlatform1Sbi) { ++ sbi_system_reset( ++ reboot ? SBI_RESET_TYPE_COLD_REBOOT : SBI_RESET_TYPE_SHUTDOWN, ++ SBI_RESET_REASON_NONE); ++ } ++ + HtifShutdown(); + return B_ERROR; + } +-- +2.30.2 + diff --git a/patchset-hrev55144/0097-kernel-arch-platform-implement-for-riscv64-2.patch b/patchset-hrev55144/0097-kernel-arch-platform-implement-for-riscv64-2.patch new file mode 100644 index 0000000..17940c0 --- /dev/null +++ b/patchset-hrev55144/0097-kernel-arch-platform-implement-for-riscv64-2.patch @@ -0,0 +1,94 @@ +From 38db205d88b98d685a960c8d2d3ac8b37cd1f86f Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:05:28 +0900 +Subject: kernel/arch/platform: implement for riscv64 (2) + +Change-Id: I745728d62eec011e8ec12dc669b527bc4486f672 +--- + .../kernel/arch/riscv64/arch_platform.cpp | 56 ++++++++++++++++++- + 1 file changed, 54 insertions(+), 2 deletions(-) + +diff --git a/src/system/kernel/arch/riscv64/arch_platform.cpp b/src/system/kernel/arch/riscv64/arch_platform.cpp +index aae0d4b6fd..b8c5636112 100644 +--- a/src/system/kernel/arch/riscv64/arch_platform.cpp ++++ b/src/system/kernel/arch/riscv64/arch_platform.cpp +@@ -5,15 +5,54 @@ + + #include + #include ++#include ++#include ++#include ++#include + ++#include ++ ++ ++uint32 gPlatform1; ++uint32 gPlatform2; + + void* gFDT = NULL; + ++HtifRegs *volatile gHtifRegs = (HtifRegs *volatile)0x40008000; ++PlicRegs *volatile gPlicRegs; ++ClintRegs *volatile gClintRegs; ++ + + status_t +-arch_platform_init(struct kernel_args *kernelArgs) ++arch_platform_init(struct kernel_args *args) + { +- gFDT = kernelArgs->arch_args.fdt; ++ gPlatform1 = args->arch_args.platform1; ++ gPlatform2 = args->arch_args.platform2; ++ ++ debug_early_boot_message("platform1: "); ++ switch (gPlatform1) { ++ case kPlatform1Riscv: debug_early_boot_message("riscv"); break; ++ case kPlatform1Sbi: debug_early_boot_message("sbi"); break; ++ default: debug_early_boot_message("?"); break; ++ } ++ debug_early_boot_message("\n"); ++ ++ debug_early_boot_message("platform2: "); ++ switch (gPlatform1) { ++ case kPlatform2Riscv: debug_early_boot_message("riscv"); break; ++ case kPlatform2Efi: debug_early_boot_message("efi"); break; ++ case kPlatform2UBoot: debug_early_boot_message("uBoot"); break; ++ default: debug_early_boot_message("?"); break; ++ } ++ debug_early_boot_message("\n"); ++ ++ ++ gFDT = args->arch_args.fdt; ++ ++ gHtifRegs = (HtifRegs *volatile)args->arch_args.htif.start; ++ gPlicRegs = (PlicRegs *volatile)args->arch_args.plic.start; ++ gClintRegs = (ClintRegs *volatile)args->arch_args.clint.start; ++ + return B_OK; + } + +@@ -21,6 +60,19 @@ arch_platform_init(struct kernel_args *kernelArgs) + status_t + arch_platform_init_post_vm(struct kernel_args *kernelArgs) + { ++ if (gPlatform1 == kPlatform1Sbi) { ++ sbiret res; ++ res = sbi_get_spec_version(); ++ dprintf("SBI spec version: %#lx\n", res.value); ++ res = sbi_get_impl_id(); ++ dprintf("SBI implementation ID: %#lx\n", res.value); ++ res = sbi_get_impl_version(); ++ dprintf("SBI implementation version: %#lx\n", res.value); ++ res = sbi_get_mvendorid(); ++ dprintf("SBI vendor ID: %#lx\n", res.value); ++ res = sbi_get_marchid(); ++ dprintf("SBI arch ID: %#lx\n", res.value); ++ } + return B_OK; + } + +-- +2.30.2 + diff --git a/patchset-hrev55144/0098-kernel-arch-timer-implement-for-riscv64-2.patch b/patchset-hrev55144/0098-kernel-arch-timer-implement-for-riscv64-2.patch new file mode 100644 index 0000000..1602daf --- /dev/null +++ b/patchset-hrev55144/0098-kernel-arch-timer-implement-for-riscv64-2.patch @@ -0,0 +1,85 @@ +From 688e4e1cac6b5d37bca0bc19b1a023ace0b65e12 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:06:26 +0900 +Subject: kernel/arch/timer: implement for riscv64 (2) + +Change-Id: I0ed511ca8a223cc115f79218e6be3276ce00320b +--- + src/system/kernel/arch/riscv64/arch_timer.cpp | 39 ++++++++++++++----- + 1 file changed, 30 insertions(+), 9 deletions(-) + +diff --git a/src/system/kernel/arch/riscv64/arch_timer.cpp b/src/system/kernel/arch/riscv64/arch_timer.cpp +index 33f8014fad..7510930b7f 100644 +--- a/src/system/kernel/arch/riscv64/arch_timer.cpp ++++ b/src/system/kernel/arch/riscv64/arch_timer.cpp +@@ -7,6 +7,7 @@ + */ + + ++#include + #include + #include + #include +@@ -14,19 +15,46 @@ + #include + #include + #include ++#include ++ ++ ++extern uint32 gPlatform1; ++extern uint32 gPlatform2; + + + void + arch_timer_set_hardware_timer(bigtime_t timeout) + { +- MSyscall(setTimerMmodeSyscall, true, gClintRegs->mTime + timeout/10); ++ // TODO: Read timer frequency from FDT ++ switch (gPlatform1) { ++ case kPlatform1Riscv: ++ MSyscall(kMSyscallSetTimer, true, ++ gClintRegs->mtime + timeout * 10); ++ break; ++ case kPlatform1Sbi: { ++ sbi_set_timer(CpuTime() + timeout); ++ break; ++ } ++ default: ++ ; ++ } + } + + + void + arch_timer_clear_hardware_timer() + { +- MSyscall(setTimerMmodeSyscall, false); ++ switch (gPlatform1) { ++ case kPlatform1Riscv: ++ MSyscall(kMSyscallSetTimer, false); ++ break; ++ case kPlatform1Sbi: { ++ sbi_set_timer(CpuTime() + (uint64)10000000 * 3600); ++ break; ++ } ++ default: ++ ; ++ } + } + + +@@ -35,10 +63,3 @@ arch_init_timer(kernel_args *args) + { + return B_OK; + } +- +- +-bigtime_t +-system_time(void) +-{ +- return CpuTime(); +-} +-- +2.30.2 + diff --git a/patchset-hrev55144/0099-kernel-arch_real_time_clock-implement-for-riscv64-2.patch b/patchset-hrev55144/0099-kernel-arch_real_time_clock-implement-for-riscv64-2.patch new file mode 100644 index 0000000..5279b42 --- /dev/null +++ b/patchset-hrev55144/0099-kernel-arch_real_time_clock-implement-for-riscv64-2.patch @@ -0,0 +1,42 @@ +From af67e892b146fe2e350bc6a5dccfe2261c324ec6 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:07:09 +0900 +Subject: kernel/arch_real_time_clock: implement for riscv64 (2) + +Change-Id: Ifecfd74fd11fe2d22c8e9436afdfa307a6116bcf +--- + .../kernel/arch/riscv64/arch_real_time_clock.cpp | 13 ++++++++++--- + 1 file changed, 10 insertions(+), 3 deletions(-) + +diff --git a/src/system/kernel/arch/riscv64/arch_real_time_clock.cpp b/src/system/kernel/arch/riscv64/arch_real_time_clock.cpp +index c4bc17be48..5774df5fad 100644 +--- a/src/system/kernel/arch/riscv64/arch_real_time_clock.cpp ++++ b/src/system/kernel/arch/riscv64/arch_real_time_clock.cpp +@@ -1,4 +1,5 @@ + #include ++#include + + #include + #include +@@ -9,9 +10,15 @@ + status_t + arch_rtc_init(kernel_args *args, struct real_time_data *data) + { +- bigtime_t systemTime = system_time(); +- uint64 rtcTime = HtifCmd(2, 0, 0); +- data->arch_data.system_time_conversion_factor = rtcTime - systemTime; ++/* ++ data->arch_data.system_time_conversion_factor ++ = (1LL << 32) * 1000000LL / args->arch_args.timerFrequrency; ++ ++ dprintf("timerFrequrency: %" B_PRIu64 "\n", ++ args->arch_args.timerFrequrency); ++ dprintf("system_time_conversion_factor: %" B_PRIu64 "\n", ++ data->arch_data.system_time_conversion_factor); ++*/ + return B_OK; + } + +-- +2.30.2 + diff --git a/patchset-hrev55144/0100-kernel-update-arch-headers-for-riscv64.patch b/patchset-hrev55144/0100-kernel-update-arch-headers-for-riscv64.patch new file mode 100644 index 0000000..bb83ec6 --- /dev/null +++ b/patchset-hrev55144/0100-kernel-update-arch-headers-for-riscv64.patch @@ -0,0 +1,117 @@ +From 8fd2a13056c406fb89476b92d2674d4474649156 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:09:02 +0900 +Subject: kernel: update arch headers for riscv64 + +Change-Id: Iaf1c253745412614f7e4a30019d96483cb0d3a12 +--- + .../private/kernel/arch/riscv64/arch_kernel.h | 20 ++++---- + .../kernel/arch/riscv64/arch_kernel_args.h | 46 ++++++++++++++++++- + 2 files changed, 53 insertions(+), 13 deletions(-) + +diff --git a/headers/private/kernel/arch/riscv64/arch_kernel.h b/headers/private/kernel/arch/riscv64/arch_kernel.h +index 058eb54c4f..8d4639675b 100644 +--- a/headers/private/kernel/arch/riscv64/arch_kernel.h ++++ b/headers/private/kernel/arch/riscv64/arch_kernel.h +@@ -15,25 +15,21 @@ + + // memory layout + #define KERNEL_LOAD_BASE 0x80000000 +-#define KERNEL_LOAD_BASE_64_BIT 0xffffffff80000000ll ++#define KERNEL_LOAD_BASE_64_BIT 0xffffffc000000000 + + + #if defined(__riscv64__) + + // Base of the kernel address space. +-#define KERNEL_BASE (0x0000000000000000 + 0x1000) +-#define KERNEL_TOP (0x0000004000000000 - 1) +-#define KERNEL_SIZE ((KERNEL_TOP - KERNEL_BASE) + 1) +- +-// Kernel physical memory map area. +-#define KERNEL_PMAP_BASE 0x0000003000000000 +-#define KERNEL_PMAP_SIZE 0x1000000000 ++#define KERNEL_BASE 0xffffffc000000000 ++#define KERNEL_SIZE 0x0000004000000000 ++#define KERNEL_TOP (KERNEL_BASE + (KERNEL_SIZE - 1)) + + // Userspace address space layout. +-#define USER_BASE 0xffffffc000000000 +-#define USER_BASE_ANY USER_BASE +-#define USER_SIZE 0x0000004000000000 +-#define USER_TOP (USER_BASE + (USER_SIZE - 1)) ++#define USER_BASE (0x0000000000000000 + 0x1000) ++#define USER_BASE_ANY USER_BASE ++#define USER_TOP (0x0000004000000000 - 1) ++#define USER_SIZE (USER_TOP - USER_BASE + 1) + + #define KERNEL_USER_DATA_BASE (USER_BASE + 0x3000000000) + #define USER_STACK_REGION (USER_BASE + 0x3000000000) +diff --git a/headers/private/kernel/arch/riscv64/arch_kernel_args.h b/headers/private/kernel/arch/riscv64/arch_kernel_args.h +index c8b888a3dd..279175bc24 100644 +--- a/headers/private/kernel/arch/riscv64/arch_kernel_args.h ++++ b/headers/private/kernel/arch/riscv64/arch_kernel_args.h +@@ -18,15 +18,59 @@ + #define MAX_VIRTUAL_RANGES_TO_KEEP 32 + + ++enum { ++ kPlatform1None, ++ kPlatform1Riscv, ++ kPlatform1Sbi, ++}; ++ ++enum { ++ kPlatform2None, ++ kPlatform2Riscv, ++ kPlatform2Efi, ++ kPlatform2UBoot, ++}; ++ ++ ++enum { ++ kUartKindNone, ++ kUartKind8250, ++ kUartKindSifive, ++ kUartKindPl011, ++}; ++ ++ ++typedef struct { ++ uint32 kind; ++ addr_range regs; ++ uint32 irq; ++ int64 clock; ++} _PACKED ArchUart; ++ ++ + // kernel args + typedef struct { ++ // Virtual address range of RAM physical memory mapping region ++ addr_range physMap; ++ + // The virtual ranges we want to keep in the kernel. + uint32 num_virtual_ranges_to_keep; + addr_range virtual_ranges_to_keep[MAX_VIRTUAL_RANGES_TO_KEEP]; + +- // needed for UEFI, otherwise kernel acpi support can't find ACPI root ++ uint32 platform1; ++ uint32 platform2; ++ ++ uint bootHart; ++ uint64 timerFrequrency; // in Hz ++ ++ // All following address are virtual + FixedWidthPointer acpi_root; + FixedWidthPointer fdt; ++ ++ addr_range htif; ++ addr_range plic; ++ addr_range clint; ++ ArchUart uart; + } _PACKED arch_kernel_args; + + #endif /* KERNEL_ARCH_RISCV64_KERNEL_ARGS_H */ +-- +2.30.2 + diff --git a/patchset-hrev55144/0101-kernel-add-RISC-V-HTIF-code-2.patch b/patchset-hrev55144/0101-kernel-add-RISC-V-HTIF-code-2.patch new file mode 100644 index 0000000..8e34e01 --- /dev/null +++ b/patchset-hrev55144/0101-kernel-add-RISC-V-HTIF-code-2.patch @@ -0,0 +1,27 @@ +From 239c90124a9899440acb6545560cb08ab7d15252 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:09:57 +0900 +Subject: kernel: add RISC-V HTIF code (2) + +Change-Id: Iabd1cdc59fde905a6f17bbc7640638c0ed06918b +--- + src/system/kernel/arch/riscv64/Htif.cpp | 3 +++ + 1 file changed, 3 insertions(+) + +diff --git a/src/system/kernel/arch/riscv64/Htif.cpp b/src/system/kernel/arch/riscv64/Htif.cpp +index c4063b1150..7101958d22 100644 +--- a/src/system/kernel/arch/riscv64/Htif.cpp ++++ b/src/system/kernel/arch/riscv64/Htif.cpp +@@ -10,6 +10,9 @@ + uint64 + HtifCmd(uint32 device, uint8 cmd, uint32 arg) + { ++ if (gHtifRegs == 0) ++ return 0; ++ + uint64 htifTohost = ((uint64)device << 56) + + ((uint64)cmd << 48) + arg; + gHtifRegs->toHostLo = htifTohost % ((uint64)1 << 32); +-- +2.30.2 + diff --git a/patchset-hrev55144/0102-riscv64-update-hardware-definition-headers.patch b/patchset-hrev55144/0102-riscv64-update-hardware-definition-headers.patch new file mode 100644 index 0000000..da96d7e --- /dev/null +++ b/patchset-hrev55144/0102-riscv64-update-hardware-definition-headers.patch @@ -0,0 +1,115 @@ +From c9ec9acadea7f3e67ed7a6c632fe546316254e5c Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:13:16 +0900 +Subject: riscv64: update hardware definition headers + +Change-Id: I0c84f1d5389842d4591cb1548793e08155ba3666 +--- + headers/private/kernel/arch/riscv64/Clint.h | 6 +-- + .../system/arch/riscv64/arch_cpu_defs.h | 38 ++++++++++++++++--- + 2 files changed, 36 insertions(+), 8 deletions(-) + +diff --git a/headers/private/kernel/arch/riscv64/Clint.h b/headers/private/kernel/arch/riscv64/Clint.h +index 384f316d11..1079e4d24f 100644 +--- a/headers/private/kernel/arch/riscv64/Clint.h ++++ b/headers/private/kernel/arch/riscv64/Clint.h +@@ -12,9 +12,9 @@ + // core local interruptor + struct ClintRegs + { +- uint8 unknown1[0x4000]; +- uint64 mTimeCmp[4095]; // per CPU core, but not implemented in temu +- uint64 mTime; // @0xBFF8 ++ uint32 msip [4096]; // machine software interrupt pending, per CPU core ++ uint64 mtimecmp[4095]; // per CPU core ++ uint64 mtime; // @0xBFF8 + }; + + extern ClintRegs* volatile gClintRegs; +diff --git a/headers/private/system/arch/riscv64/arch_cpu_defs.h b/headers/private/system/arch/riscv64/arch_cpu_defs.h +index 192f785b13..93a422b143 100644 +--- a/headers/private/system/arch/riscv64/arch_cpu_defs.h ++++ b/headers/private/system/arch/riscv64/arch_cpu_defs.h +@@ -112,6 +112,18 @@ enum { + causeStorePageFault = 15, + }; + ++// physical memory protection ++enum { ++ pmpR = 0, ++ pmpW = 1, ++ pmpX = 2, ++}; ++ ++enum { ++ // naturally aligned power of two ++ pmpMatchNapot = 3 << 3, ++}; ++ + enum { + pageSize = 4096, + pageBits = 12, +@@ -167,12 +179,12 @@ struct SatpReg { + SatpReg(uint64 val): val(val) {} + }; + +-static B_ALWAYS_INLINE uint64 PhysAdrPte(uint64 physAdr, uint32 level) ++static B_ALWAYS_INLINE uint64 VirtAdrPte(uint64 physAdr, uint32 level) + { + return (physAdr >> (pageBits + pteIdxBits*level)) % (1 << pteIdxBits); + } + +-static B_ALWAYS_INLINE uint64 PhysAdrOfs(uint64 physAdr) ++static B_ALWAYS_INLINE uint64 VirtAdrOfs(uint64 physAdr) + { + return physAdr % pageSize; + } +@@ -246,7 +258,7 @@ static B_ALWAYS_INLINE void SetStvec(uint64 x) { + static B_ALWAYS_INLINE uint64 Satp() { + uint64 x; asm volatile("csrr %0, satp" : "=r" (x)); return x;} + static B_ALWAYS_INLINE void SetSatp(uint64 x) { +- asm volatile("csrw satp, %0" : : "r" (x));} ++ asm volatile("csrw satp, %0" : : "r" (x) : "memory");} + + // scratch register + static B_ALWAYS_INLINE uint64 Mscratch() { +@@ -284,18 +296,34 @@ static B_ALWAYS_INLINE uint64 Mcounteren() { + static B_ALWAYS_INLINE void SetMcounteren(uint64 x) { + asm volatile("csrw mcounteren, %0" : : "r" (x));} + +-// machine-mode cycle counter +-static B_ALWAYS_INLINE uint64 Mcycle() { ++// cycle counter ++static B_ALWAYS_INLINE uint64 CpuMcycle() { + uint64 x; asm volatile("csrr %0, mcycle" : "=r" (x)); return x;} ++static B_ALWAYS_INLINE uint64 CpuCycle() { ++ uint64 x; asm volatile("csrr %0, cycle" : "=r" (x)); return x;} + // monotonic timer + static B_ALWAYS_INLINE uint64 CpuTime() { + uint64 x; asm volatile("csrr %0, time" : "=r" (x)); return x;} + ++// physical memory protection ++static B_ALWAYS_INLINE uint64 Pmpaddr0() { ++ uint64 x; asm volatile("csrr %0, pmpaddr0" : "=r" (x)); return x;} ++static B_ALWAYS_INLINE uint64 Pmpcfg0() { ++ uint64 x; asm volatile("csrr %0, pmpcfg0" : "=r" (x)); return x;} ++static B_ALWAYS_INLINE void SetPmpaddr0(uint64 x) { ++ asm volatile("csrw pmpaddr0, %0" : : "r" (x));} ++static B_ALWAYS_INLINE void SetPmpcfg0(uint64 x) { ++ asm volatile("csrw pmpcfg0, %0" : : "r" (x));} ++ + // flush the TLB + static B_ALWAYS_INLINE void FlushTlbAll() { + asm volatile("sfence.vma" : : : "memory");} + static B_ALWAYS_INLINE void FlushTlbPage(uint64 x) { + asm volatile("sfence.vma %0" : : "r" (x) : "memory");} ++static B_ALWAYS_INLINE void FlushTlbAllAsid(uint64 asid) { ++ asm volatile("sfence.vma x0, %0" : : "r" (asid) : "memory");} ++static B_ALWAYS_INLINE void FlushTlbPageAsid(uint64 page, uint64 asid) { ++ asm volatile("sfence.vma %0, %0" : : "r" (page), "r" (asid) : "memory");} + + static B_ALWAYS_INLINE uint64 Sp() { + uint64 x; asm volatile("mv %0, sp" : "=r" (x)); return x;} +-- +2.30.2 + diff --git a/patchset-hrev55144/0103-nvme-add-legacy-interrupts-support.patch b/patchset-hrev55144/0103-nvme-add-legacy-interrupts-support.patch new file mode 100644 index 0000000..50c5984 --- /dev/null +++ b/patchset-hrev55144/0103-nvme-add-legacy-interrupts-support.patch @@ -0,0 +1,88 @@ +From 4b37331b36722d6ed99faaba9f95cacc90adb661 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:14:41 +0900 +Subject: nvme: add legacy interrupts support + +Change-Id: I29b9676c6c2407e7795af4c7b1c56a7afb546f6e +--- + .../drivers/disk/nvme/compat/libnvme_haiku.cpp | 10 +++++++++- + .../kernel/drivers/disk/nvme/nvme_disk.cpp | 16 +++++++++++----- + 2 files changed, 20 insertions(+), 6 deletions(-) + +diff --git a/src/add-ons/kernel/drivers/disk/nvme/compat/libnvme_haiku.cpp b/src/add-ons/kernel/drivers/disk/nvme/compat/libnvme_haiku.cpp +index af959e62fc..3ea404efb3 100644 +--- a/src/add-ons/kernel/drivers/disk/nvme/compat/libnvme_haiku.cpp ++++ b/src/add-ons/kernel/drivers/disk/nvme/compat/libnvme_haiku.cpp +@@ -126,12 +126,20 @@ int + nvme_pcicfg_map_bar(void* devhandle, unsigned int bar, bool read_only, + void** mapped_addr) + { ++ dprintf("nvme_pcicfg_map_bar()\n"); + struct pci_device* dev = (struct pci_device*)devhandle; + pci_info* info = (pci_info*)dev->pci_info; + +- uint32 addr = info->u.h0.base_registers[bar]; ++ uint64 addr = info->u.h0.base_registers[bar]; ++ if ((info->u.h0.base_register_flags[0] & PCI_address_type) ++ == PCI_address_type_64) { ++ addr |= (uint64)info->u.h0.base_registers[1] << 32; ++ } ++ + uint32 size = info->u.h0.base_register_sizes[bar]; + ++ dprintf(" addr: 0x%" B_PRIx64 ", size: 0x%" B_PRIx32 "\n", addr, size); ++ + area_id area = map_physical_memory("nvme mapped bar", (phys_addr_t)addr, + size, B_ANY_KERNEL_ADDRESS, + B_KERNEL_READ_AREA | (read_only ? 0 : B_KERNEL_WRITE_AREA), +diff --git a/src/add-ons/kernel/drivers/disk/nvme/nvme_disk.cpp b/src/add-ons/kernel/drivers/disk/nvme/nvme_disk.cpp +index b90ab7047b..d31775b26b 100644 +--- a/src/add-ons/kernel/drivers/disk/nvme/nvme_disk.cpp ++++ b/src/add-ons/kernel/drivers/disk/nvme/nvme_disk.cpp +@@ -198,6 +198,11 @@ nvme_disk_init_device(void* _info, void** _cookie) + + device->pci_info = &info->info; + ++ // enable busmaster and memory mapped access ++ uint16 command = pci->read_pci_config(pcidev, PCI_command, 2); ++ command |= PCI_command_master | PCI_command_memory; ++ pci->write_pci_config(pcidev, PCI_command, 2, command); ++ + // open the controller + info->ctrlr = nvme_ctrlr_open(device, NULL); + if (info->ctrlr == NULL) { +@@ -290,10 +295,6 @@ nvme_disk_init_device(void* _info, void** _cookie) + sPCIx86Module = NULL; + } + +- uint16 command = pci->read_pci_config(pcidev, PCI_command, 2); +- command &= ~(PCI_command_int_disable); +- pci->write_pci_config(pcidev, PCI_command, 2, command); +- + uint8 irq = info->info.u.h0.interrupt_line; + if (sPCIx86Module != NULL) { + if (sPCIx86Module->get_msix_count(info->info.bus, info->info.device, +@@ -317,6 +318,10 @@ nvme_disk_init_device(void* _info, void** _cookie) + irq = msiVector; + } + } ++ } else { ++ uint16 command = pci->read_pci_config(pcidev, PCI_command, 2); ++ command &= ~(PCI_command_int_disable); ++ pci->write_pci_config(pcidev, PCI_command, 2, command); + } + + if (irq == 0 || irq == 0xFF) { +@@ -946,7 +951,8 @@ nvme_disk_register_device(device_node* parent) + CALLED(); + + device_attr attrs[] = { +- { NULL } ++ {B_DEVICE_PRETTY_NAME, B_STRING_TYPE, {string: "NVMe Disk"}}, ++ {} + }; + + return sDeviceManager->register_node(parent, NVME_DISK_DRIVER_MODULE_NAME, +-- +2.30.2 + diff --git a/patchset-hrev55144/0104-AutoDeleter-add-VMAddressSpacePutter-DeviceNodePutte.patch b/patchset-hrev55144/0104-AutoDeleter-add-VMAddressSpacePutter-DeviceNodePutte.patch new file mode 100644 index 0000000..c288f0f --- /dev/null +++ b/patchset-hrev55144/0104-AutoDeleter-add-VMAddressSpacePutter-DeviceNodePutte.patch @@ -0,0 +1,45 @@ +From 01fc004912c3ef6274cda7b0e3dee25c9327112e Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:16:56 +0900 +Subject: AutoDeleter: add VMAddressSpacePutter, DeviceNodePutter (2) + +Change-Id: Ia1344d952f7f40dafdbbb5c80a720d3ccb9fa4aa +--- + headers/private/shared/AutoDeleterDrivers.h | 13 +++++++++++-- + 1 file changed, 11 insertions(+), 2 deletions(-) + +diff --git a/headers/private/shared/AutoDeleterDrivers.h b/headers/private/shared/AutoDeleterDrivers.h +index 0d4b98b564..eb9835ad90 100644 +--- a/headers/private/shared/AutoDeleterDrivers.h ++++ b/headers/private/shared/AutoDeleterDrivers.h +@@ -32,6 +32,17 @@ typedef MethodDeleter VMAddressSpace + template + using DeviceNodePutter = FieldFunctionDeleter; + ++#else ++ ++template ++struct DeviceNodePutter : FieldFunctionDeleter ++{ ++ typedef FieldFunctionDeleter Base; ++ ++ DeviceNodePutter() : Base() {} ++ DeviceNodePutter(device_node* object) : Base(object) {} ++}; ++ + #endif + + #endif +@@ -47,9 +58,7 @@ using ::BPrivate::DriverSettingsUnloader; + using ::BPrivate::VnodePutter; + using ::BPrivate::DescriptorPutter; + using ::BPrivate::VMAddressSpacePutter; +-#if __GNUC__ >= 4 + using ::BPrivate::DeviceNodePutter; +-#endif + + #endif + +-- +2.30.2 + diff --git a/patchset-hrev55144/0105-riscv64-add-SBI-syscall-interface-2.patch b/patchset-hrev55144/0105-riscv64-add-SBI-syscall-interface-2.patch new file mode 100644 index 0000000..0769427 --- /dev/null +++ b/patchset-hrev55144/0105-riscv64-add-SBI-syscall-interface-2.patch @@ -0,0 +1,35 @@ +From 3e571c93b79b7f91c1e3ad7271d2eab902d317ae Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:19:38 +0900 +Subject: riscv64: add SBI syscall interface (2) + +Change-Id: I5dab9a5eb98bc29ec0e0b4385898bb2980250eec +--- + headers/private/kernel/platform/sbi/sbi_syscalls.h | 11 +++++++++++ + 1 file changed, 11 insertions(+) + +diff --git a/headers/private/kernel/platform/sbi/sbi_syscalls.h b/headers/private/kernel/platform/sbi/sbi_syscalls.h +index 2d32de19d7..5f1b389550 100644 +--- a/headers/private/kernel/platform/sbi/sbi_syscalls.h ++++ b/headers/private/kernel/platform/sbi/sbi_syscalls.h +@@ -35,6 +35,17 @@ enum { + SBI_HART_STATE_RESUME_PENDING = 6, + }; + ++enum { ++ SBI_RESET_TYPE_SHUTDOWN = 0, ++ SBI_RESET_TYPE_COLD_REBOOT = 1, ++ SBI_RESET_TYPE_WARM_REBOOT = 2, ++}; ++ ++enum { ++ SBI_RESET_REASON_NONE = 0, ++ SBI_RESET_REASON_SYSTEM_FAILURE = 1, ++}; ++ + // a7: EID, a6: FID + + extern "C" { +-- +2.30.2 + diff --git a/patchset-hrev55144/0106-kernel-arch-timer-implement-for-riscv64-3.patch b/patchset-hrev55144/0106-kernel-arch-timer-implement-for-riscv64-3.patch new file mode 100644 index 0000000..747d176 --- /dev/null +++ b/patchset-hrev55144/0106-kernel-arch-timer-implement-for-riscv64-3.patch @@ -0,0 +1,40 @@ +From a895c66740b9f718c155fd57872f890c557b04f1 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:25:27 +0900 +Subject: kernel/arch/timer: implement for riscv64 (3) + +Change-Id: I71fec4dc335ce405a4a5182ce066e0631636c63a +--- + headers/private/system/arch/riscv64/arch_real_time_data.h | 3 +-- + src/system/kernel/lib/arch/riscv64/Jamfile | 1 + + 2 files changed, 2 insertions(+), 2 deletions(-) + +diff --git a/headers/private/system/arch/riscv64/arch_real_time_data.h b/headers/private/system/arch/riscv64/arch_real_time_data.h +index 4d63960eed..2cc01f92ff 100644 +--- a/headers/private/system/arch/riscv64/arch_real_time_data.h ++++ b/headers/private/system/arch/riscv64/arch_real_time_data.h +@@ -13,8 +13,7 @@ + + struct arch_real_time_data { + bigtime_t system_time_offset; +- uint32 system_time_conversion_factor; +- uint32 _padding; ++ uint64 system_time_conversion_factor; + }; + + #endif /* _KERNEL_ARCH_REAL_TIME_DATA_H */ +diff --git a/src/system/kernel/lib/arch/riscv64/Jamfile b/src/system/kernel/lib/arch/riscv64/Jamfile +index 7b143796e6..603763cf5d 100644 +--- a/src/system/kernel/lib/arch/riscv64/Jamfile ++++ b/src/system/kernel/lib/arch/riscv64/Jamfile +@@ -10,6 +10,7 @@ SEARCH_SOURCE += [ FDirName $(librootSources) os arch generic ] ; + + KernelMergeObject kernel_os_arch_$(TARGET_ARCH).o : + byteorder.S ++ system_time.cpp + + generic_atomic.cpp + generic_system_time_nsecs.cpp +-- +2.30.2 + diff --git a/patchset-hrev55144/0107-libroot-os-implement-arch-specific-parts-for-riscv64.patch b/patchset-hrev55144/0107-libroot-os-implement-arch-specific-parts-for-riscv64.patch new file mode 100644 index 0000000..f5bc5c0 --- /dev/null +++ b/patchset-hrev55144/0107-libroot-os-implement-arch-specific-parts-for-riscv64.patch @@ -0,0 +1,86 @@ +From 7848a355eaac1cb02ed4e7252054405123383c6a Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:26:11 +0900 +Subject: libroot/os: implement arch-specific parts for riscv64 (2) + +Change-Id: I963e517671a59bca5f918eadc499c464b8002948 +--- + .../libroot/os/arch/riscv64/system_time.cpp | 38 ++++++++++++------- + src/system/libroot/os/arch/riscv64/time.cpp | 5 +-- + 2 files changed, 27 insertions(+), 16 deletions(-) + +diff --git a/src/system/libroot/os/arch/riscv64/system_time.cpp b/src/system/libroot/os/arch/riscv64/system_time.cpp +index 8ad65c6944..92e090f86b 100644 +--- a/src/system/libroot/os/arch/riscv64/system_time.cpp ++++ b/src/system/libroot/os/arch/riscv64/system_time.cpp +@@ -9,24 +9,36 @@ + #include + + #include ++#include + #include + #include + ++#ifdef _KERNEL_MODE ++#include ++#endif + +-bigtime_t +-system_time(void) +-{ +- // TODO: units conversion +- +- // Currently TinyEMU implementation just use host system system_time() to +- // implement `utime` register. Specification don't define units. ++static uint64_t cv_factor = 0; + +- // Spec says: The execution environment should provide a means of +- // determining the period of the real-time counter (seconds/tick). +- // The period must be constant. + +- bigtime_t time; +- asm volatile("csrr %0, time" : "=r" (time)); +- return time; ++extern "C" void ++__riscv64_setup_system_time(uint64 cv) ++{ ++ cv_factor = cv; + } + ++ ++[[gnu::optimize("omit-frame-pointer")]] bigtime_t ++system_time() ++{ ++ return CpuTime(); ++/* ++ uint64 time = CpuTime(); ++ uint64 lo = (uint32)time; ++ uint64 hi = time >> 32; ++ return ((lo * cv_factor) >> 32) + hi * cv_factor; ++*/ ++/* ++ __uint128_t time = static_cast<__uint128_t>(CpuTime()) * cv_factor; ++ return time >> 32; ++*/ ++} +diff --git a/src/system/libroot/os/arch/riscv64/time.cpp b/src/system/libroot/os/arch/riscv64/time.cpp +index d898887325..517d989d44 100644 +--- a/src/system/libroot/os/arch/riscv64/time.cpp ++++ b/src/system/libroot/os/arch/riscv64/time.cpp +@@ -17,11 +17,10 @@ __arch_init_time(struct real_time_data *data, bool setDefaults) + { + sRealTimeData = &data->arch_data; + +- if (setDefaults) { ++ if (setDefaults) + sRealTimeData->system_time_conversion_factor = 1000000000LL; +- } + +- // __riscv64_setup_system_time(&sRealTimeData->system_time_conversion_factor); ++ __riscv64_setup_system_time(sRealTimeData->system_time_conversion_factor); + } + + +-- +2.30.2 + diff --git a/patchset-hrev55144/0108-kernel-non-arch-changes-for-riscv64-2.patch b/patchset-hrev55144/0108-kernel-non-arch-changes-for-riscv64-2.patch new file mode 100644 index 0000000..4090b84 --- /dev/null +++ b/patchset-hrev55144/0108-kernel-non-arch-changes-for-riscv64-2.patch @@ -0,0 +1,166 @@ +From fc40166f25e4562470bbeef2439da5cf7525f25f Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:27:58 +0900 +Subject: kernel: non-arch changes for riscv64 (2) + +Change-Id: I8b7e280c9297d9ea3b4eed1c6705801a59c469ef +--- + src/system/kernel/cache/file_cache.cpp | 2 +- + src/system/kernel/debug/debug.cpp | 2 ++ + src/system/kernel/debug/frame_buffer_console.cpp | 4 ++-- + src/system/kernel/debug/user_debugger.cpp | 2 ++ + src/system/kernel/device_manager/device_manager.cpp | 7 ++++--- + src/system/kernel/main.cpp | 6 +++++- + src/system/kernel/team.cpp | 3 +-- + 7 files changed, 17 insertions(+), 9 deletions(-) + +diff --git a/src/system/kernel/cache/file_cache.cpp b/src/system/kernel/cache/file_cache.cpp +index c2e010ecc9..4d8436f428 100644 +--- a/src/system/kernel/cache/file_cache.cpp ++++ b/src/system/kernel/cache/file_cache.cpp +@@ -976,7 +976,7 @@ cache_prefetch_vnode(struct vnode* vnode, off_t offset, size_t size) + + // Don't do anything if we don't have the resources left, or the cache + // already contains more than 2/3 of its pages +- if (offset >= fileSize || vm_page_num_unused_pages() < 2 * reservePages ++ if (true /* !!! */ || offset >= fileSize || vm_page_num_unused_pages() < 2 * reservePages + || 3 * cache->page_count > 2 * fileSize / B_PAGE_SIZE) { + cache->ReleaseRef(); + return; +diff --git a/src/system/kernel/debug/debug.cpp b/src/system/kernel/debug/debug.cpp +index 59842a6eba..7418440dd7 100644 +--- a/src/system/kernel/debug/debug.cpp ++++ b/src/system/kernel/debug/debug.cpp +@@ -1671,7 +1671,9 @@ debug_init(kernel_args* args) + + debug_paranoia_init(); + arch_debug_console_init(args); ++#ifdef __riscv + arch_debug_init_early(args); ++#endif + } + + +diff --git a/src/system/kernel/debug/frame_buffer_console.cpp b/src/system/kernel/debug/frame_buffer_console.cpp +index a556ce158d..34d3023e58 100644 +--- a/src/system/kernel/debug/frame_buffer_console.cpp ++++ b/src/system/kernel/debug/frame_buffer_console.cpp +@@ -444,11 +444,11 @@ frame_buffer_update(addr_t baseAddress, int32 width, int32 height, int32 depth, + status_t + frame_buffer_console_init(kernel_args* args) + { ++ mutex_init(&sConsole.lock, "console_lock"); ++ + if (!args->frame_buffer.enabled) + return B_OK; + +- mutex_init(&sConsole.lock, "console_lock"); +- + void* frameBuffer; + sConsole.area = map_physical_memory("vesa frame buffer", + args->frame_buffer.physical_buffer.start, +diff --git a/src/system/kernel/debug/user_debugger.cpp b/src/system/kernel/debug/user_debugger.cpp +index c94196f3c1..348040339e 100644 +--- a/src/system/kernel/debug/user_debugger.cpp ++++ b/src/system/kernel/debug/user_debugger.cpp +@@ -2782,8 +2782,10 @@ ensure_debugger_installed() + void + _user_debugger(const char *userMessage) + { ++#ifdef __riscv + WriteTrapInfo(); + DoStackTrace(Fp(), 0); ++#endif + // install the default debugger, if there is none yet + status_t error = ensure_debugger_installed(); + if (error != B_OK) { +diff --git a/src/system/kernel/device_manager/device_manager.cpp b/src/system/kernel/device_manager/device_manager.cpp +index 765d9dcb4a..a2779d7946 100644 +--- a/src/system/kernel/device_manager/device_manager.cpp ++++ b/src/system/kernel/device_manager/device_manager.cpp +@@ -1732,6 +1732,7 @@ device_node::_GetNextDriverPath(void*& cookie, KPath& _path) + _AddPath(*stack, "busses/scsi"); + _AddPath(*stack, "busses", "virtio"); + _AddPath(*stack, "busses/random"); ++ _AddPath(*stack, "bus_managers/pci"); + } + break; + } +@@ -1792,7 +1793,7 @@ device_node::_FindBestDriver(const char* path, driver_module_info*& bestDriver, + void* list = open_module_list_etc(path, "driver_v1"); + driver_module_info* driver; + while (_GetNextDriver(list, driver) == B_OK) { +- dprintf(" candidate: \"%s\"\n", driver->info.name); ++// dprintf(" candidate: \"%s\"\n", driver->info.name); + if (previous != NULL && driver == previous->DriverModule()) { + put_module(driver->info.name); + continue; +@@ -1857,7 +1858,7 @@ device_node::_AlwaysRegisterDynamic() + status_t + device_node::_RegisterDynamic(device_node* previous) + { +- dprintf("%p._RegisterDynamic()\n", this); ++// dprintf("%p._RegisterDynamic()\n", this); + // If this is not a bus, we don't have to scan it + if (find_attr(this, B_DEVICE_BUS, false, B_STRING_TYPE) == NULL) + return B_OK; +@@ -1877,7 +1878,7 @@ device_node::_RegisterDynamic(device_node* previous) + void* cookie = NULL; + + while (_GetNextDriverPath(cookie, path) == B_OK) { +- dprintf(" candidate: \"%s\"\n", path.Path()); ++// dprintf(" candidate: \"%s\"\n", path.Path()); + _FindBestDriver(path.Path(), bestDriver, bestSupport, previous); + } + +diff --git a/src/system/kernel/main.cpp b/src/system/kernel/main.cpp +index a3fdb1ac6f..ae8bd70cfb 100644 +--- a/src/system/kernel/main.cpp ++++ b/src/system/kernel/main.cpp +@@ -94,9 +94,13 @@ non_boot_cpu_init(void* args, int currentCPU) + } + + ++extern "C" status_t arch_debug_console_init(kernel_args *args); ++ ++ + extern "C" int + _start(kernel_args *bootKernelArgs, int currentCPU) + { ++ arch_debug_console_init(bootKernelArgs); + debug_early_boot_message("Kernel entry point\n"); + + if (bootKernelArgs->version == CURRENT_KERNEL_ARGS_VERSION +@@ -374,7 +378,7 @@ main2(void* /*unused*/) + // The boot splash screen is the last user of the kernel args. + // Note: don't confuse the kernel_args structure (which is never freed) + // with the kernel args ranges it contains (and which are freed here). +- // vm_free_kernel_args(&sKernelArgs); ++ vm_free_kernel_args(&sKernelArgs); + + // start the init process + { +diff --git a/src/system/kernel/team.cpp b/src/system/kernel/team.cpp +index 9f17b31029..431edd09aa 100644 +--- a/src/system/kernel/team.cpp ++++ b/src/system/kernel/team.cpp +@@ -444,7 +444,7 @@ Team::Team(team_id id, bool kernel) + fArgs[0] = '\0'; + num_threads = 0; + io_context = NULL; +- address_space = NULL; ++ address_space = kernel ? VMAddressSpace::Kernel() : NULL; + realtime_sem_context = NULL; + xsi_sem_context = NULL; + thread_list = NULL; +@@ -1650,7 +1650,6 @@ team_create_thread_start_internal(void* args) + strerror(commPageArea))); + return commPageArea; + } +- dprintf("clone_commpage_area: %p\n", team->commpage_address); + + // Register commpage image + image_id commPageImage = get_commpage_image(); +-- +2.30.2 + diff --git a/patchset-hrev55144/0109-bus_managers-fdt-rewrite-to-support-device-manager-n.patch b/patchset-hrev55144/0109-bus_managers-fdt-rewrite-to-support-device-manager-n.patch new file mode 100644 index 0000000..5da76eb --- /dev/null +++ b/patchset-hrev55144/0109-bus_managers-fdt-rewrite-to-support-device-manager-n.patch @@ -0,0 +1,53 @@ +From 62f01721901accdc533b23c7790a252971a6b7fb Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:30:11 +0900 +Subject: bus_managers/fdt: rewrite to support device manager node tree (2) + +Change-Id: Ie7e81091c8829188aedd9548e7cd844dff610aef +--- + .../kernel/bus_managers/fdt/fdt_module.cpp | 29 +++++++++++++++++-- + 1 file changed, 27 insertions(+), 2 deletions(-) + +diff --git a/src/add-ons/kernel/bus_managers/fdt/fdt_module.cpp b/src/add-ons/kernel/bus_managers/fdt/fdt_module.cpp +index 7e7f62e3bf..fa932d5071 100644 +--- a/src/add-ons/kernel/bus_managers/fdt/fdt_module.cpp ++++ b/src/add-ons/kernel/bus_managers/fdt/fdt_module.cpp +@@ -359,8 +359,33 @@ fdt_device_get_interrupt(fdt_device* dev, uint32 ord, + int propLen; + const void* prop = fdt_getprop(gFDT, (int)fdtNode, "interrupts-extended", + &propLen); +- if (prop == NULL) +- return false; ++ if (prop == NULL) { ++ prop = fdt_getprop(gFDT, (int)fdtNode, "interrupts", ++ &propLen); ++ if (prop == NULL) ++ return false; ++ ++ if ((ord + 1)*4 > (uint32)propLen) ++ return false; ++ ++ if (interrupt != NULL) ++ *interrupt = fdt32_to_cpu(*(((uint32*)prop) + ord)); ++ ++ if (interruptController != NULL) { ++ prop = fdt_getprop(gFDT, (int)fdtNode, "interrupt-parent", ++ &propLen); ++ if (prop != NULL && propLen == 4) { ++ uint32 phandle = fdt32_to_cpu(*(uint32*)prop); ++ ++ fdt_bus* bus; ++ ASSERT(gDeviceManager->get_driver( ++ dev->bus, NULL, (void**)&bus) >= B_OK); ++ ++ *interruptController = fdt_bus_node_by_phandle(bus, phandle); ++ } ++ } ++ return true; ++ } + + // TODO: use '#interrupt-cells' to identify field sizes + +-- +2.30.2 + diff --git a/patchset-hrev55144/0110-virtio_mmio-add-2.patch b/patchset-hrev55144/0110-virtio_mmio-add-2.patch new file mode 100644 index 0000000..33108f7 --- /dev/null +++ b/patchset-hrev55144/0110-virtio_mmio-add-2.patch @@ -0,0 +1,80 @@ +From a597696d5da7e083610f8f114fadf8053298ecd9 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:31:52 +0900 +Subject: virtio_mmio: add (2) + +Change-Id: I235118b5b569d4d77b5dabba50976ac2ba94beee +--- + .../busses/virtio/virtio_mmio/VirtioDevice.cpp | 2 +- + .../busses/virtio/virtio_mmio/virtio_mmio.cpp | 18 ++++++++++++++---- + 2 files changed, 15 insertions(+), 5 deletions(-) + +diff --git a/src/add-ons/kernel/busses/virtio/virtio_mmio/VirtioDevice.cpp b/src/add-ons/kernel/busses/virtio/virtio_mmio/VirtioDevice.cpp +index 491c8aa4ad..ac9bbfacd4 100644 +--- a/src/add-ons/kernel/busses/virtio/virtio_mmio/VirtioDevice.cpp ++++ b/src/add-ons/kernel/busses/virtio/virtio_mmio/VirtioDevice.cpp +@@ -114,7 +114,7 @@ status_t VirtioQueue::Enqueue( + void* cookie + ) + { +- int32 firstDesc = -1, lastDesc; ++ int32 firstDesc = -1, lastDesc = -1; + size_t count = readVectorCount + writtenVectorCount; + if (count == 0) + return B_OK; +diff --git a/src/add-ons/kernel/busses/virtio/virtio_mmio/virtio_mmio.cpp b/src/add-ons/kernel/busses/virtio/virtio_mmio/virtio_mmio.cpp +index d54f186bc8..35921420b2 100644 +--- a/src/add-ons/kernel/busses/virtio/virtio_mmio/virtio_mmio.cpp ++++ b/src/add-ons/kernel/busses/virtio/virtio_mmio/virtio_mmio.cpp +@@ -15,6 +15,7 @@ + #include + + #include ++#include + + #include + #include +@@ -91,7 +92,7 @@ virtio_device_register_device(device_node* parent) + } + + if (mappedRegs->signature != kVirtioSignature) { +- ERROR("bad signature: 0x%08" B_PRIx32 ", should be 0x%08" B_PRIx32 "\n", mappedRegs->signature, kVirtioSignature); ++ ERROR("bad signature: 0x%08" B_PRIx32 ", should be 0x%08" B_PRIx32 "\n", mappedRegs->signature, (uint32)kVirtioSignature); + return B_ERROR; + } + +@@ -119,10 +120,10 @@ virtio_device_init_device(device_node* node, void** cookie) + { + TRACE("init_device(%p)\n", node); + +- device_node* parent = gDeviceManager->get_parent_node(node); ++ DeviceNodePutter<&gDeviceManager> parent(gDeviceManager->get_parent_node(node)); + fdt_device_module_info *parentModule; + fdt_device* parentDev; +- if (gDeviceManager->get_driver(parent, (driver_module_info**)&parentModule, (void**)&parentDev)) ++ if (gDeviceManager->get_driver(parent.Get(), (driver_module_info**)&parentModule, (void**)&parentDev)) + panic("can't get parent node driver"); + + dprintf(" bus: %p\n", parentModule->get_bus(parentDev)); +@@ -315,8 +316,17 @@ virtio_device_free_queues(virtio_device cookie) + dev->fQueueCnt = 0; + } + +- ++#ifdef __riscv + void WritePC(addr_t adr); ++#else ++ ++static inline void ++WritePC(addr_t adr) ++{ ++ dprintf("%#" B_PRIxADDR, adr); ++} ++ ++#endif + + static status_t + virtio_device_setup_interrupt(virtio_device cookie, +-- +2.30.2 + diff --git a/patchset-hrev55144/0111-virtio_input-add-2.patch b/patchset-hrev55144/0111-virtio_input-add-2.patch new file mode 100644 index 0000000..791017d --- /dev/null +++ b/patchset-hrev55144/0111-virtio_input-add-2.patch @@ -0,0 +1,100 @@ +From 456514dc123e9d829538740710f127cfd983b185 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:32:31 +0900 +Subject: virtio_input: add (2) + +Change-Id: I9976fa36356dba9c833b23c9e3c2950f8e5a5829 +--- + .../input/virtio_input/virtio_input.cpp | 22 +++++++++---------- + 1 file changed, 11 insertions(+), 11 deletions(-) + +diff --git a/src/add-ons/kernel/drivers/input/virtio_input/virtio_input.cpp b/src/add-ons/kernel/drivers/input/virtio_input/virtio_input.cpp +index 688996e979..55d546912c 100644 +--- a/src/add-ons/kernel/drivers/input/virtio_input/virtio_input.cpp ++++ b/src/add-ons/kernel/drivers/input/virtio_input/virtio_input.cpp +@@ -69,7 +69,7 @@ struct VirtioInputHandle { + #define CALLED() TRACE("CALLED %s\n", __PRETTY_FUNCTION__) + + +-static device_manager_info* sDeviceManager; ++device_manager_info* gDeviceManager; + + + static void WriteInputPacket(const VirtioInputPacket &pkt) +@@ -111,8 +111,8 @@ static void WriteInputPacket(const VirtioInputPacket &pkt) + } + switch (pkt.type) { + case kVirtioInputEvSyn: break; +- case kVirtioInputEvKey: dprintf(", "); if (pkt.value == 0) dprintf("up"); else if (pkt.value == 1) dprintf("down"); else dprintf("%d", pkt.value); break; +- default: dprintf(", "); dprintf("%d", pkt.value); ++ case kVirtioInputEvKey: dprintf(", "); if (pkt.value == 0) dprintf("up"); else if (pkt.value == 1) dprintf("down"); else dprintf("%" B_PRId32, pkt.value); break; ++ default: dprintf(", "); dprintf("%" B_PRId32, pkt.value); + } + } + +@@ -215,8 +215,8 @@ virtio_input_init_device(void* _info, void** _cookie) + TRACE("virtio_input_init_device(%p)\n", _info); + VirtioInputDevice* info = (VirtioInputDevice*)_info; + +- DeviceNodePutter<&sDeviceManager> parent(sDeviceManager->get_parent_node(info->node)); +- sDeviceManager->get_driver(parent.Get(), (driver_module_info **)&info->virtio, ++ DeviceNodePutter<&gDeviceManager> parent(gDeviceManager->get_parent_node(info->node)); ++ gDeviceManager->get_driver(parent.Get(), (driver_module_info **)&info->virtio, + (void **)&info->virtio_device); + + info->virtio->negotiate_features(info->virtio_device, 0, &info->features, NULL); +@@ -365,14 +365,14 @@ virtio_input_supports_device(device_node *parent) + uint16 deviceType; + + // make sure parent is really the Virtio bus manager +- if (sDeviceManager->get_attr_string(parent, B_DEVICE_BUS, &bus, false)) ++ if (gDeviceManager->get_attr_string(parent, B_DEVICE_BUS, &bus, false)) + return -1; + + if (strcmp(bus, "virtio")) + return 0.0; + + // check whether it's really a Direct Access Device +- if (sDeviceManager->get_attr_uint16(parent, VIRTIO_DEVICE_TYPE_ITEM, ++ if (gDeviceManager->get_attr_uint16(parent, VIRTIO_DEVICE_TYPE_ITEM, + &deviceType, true) != B_OK || deviceType != kVirtioDevInput) + return 0.0; + +@@ -392,7 +392,7 @@ virtio_input_register_device(device_node *node) + { NULL } + }; + +- return sDeviceManager->register_node(node, VIRTIO_INPUT_DRIVER_MODULE_NAME, ++ return gDeviceManager->register_node(node, VIRTIO_INPUT_DRIVER_MODULE_NAME, + attrs, NULL, NULL); + } + +@@ -434,14 +434,14 @@ virtio_input_register_child_devices(void* _cookie) + VirtioInputDevice* info = (VirtioInputDevice*)_cookie; + status_t status; + +- int32 id = sDeviceManager->create_id(VIRTIO_INPUT_DEVICE_ID_GENERATOR); ++ int32 id = gDeviceManager->create_id(VIRTIO_INPUT_DEVICE_ID_GENERATOR); + if (id < 0) + return id; + + char name[64]; + snprintf(name, sizeof(name), "input/virtio/%" B_PRId32 "/raw", id); + +- status = sDeviceManager->publish_device(info->node, name, VIRTIO_INPUT_DEVICE_MODULE_NAME); ++ status = gDeviceManager->publish_device(info->node, name, VIRTIO_INPUT_DEVICE_MODULE_NAME); + if (status < B_OK) { + TRACE(" error: 0x%" B_PRIx32 "(%s) \n", status, strerror(status)); + panic("(!)"); +@@ -455,7 +455,7 @@ virtio_input_register_child_devices(void* _cookie) + + + module_dependency module_dependencies[] = { +- {B_DEVICE_MANAGER_MODULE_NAME, (module_info**)&sDeviceManager}, ++ {B_DEVICE_MANAGER_MODULE_NAME, (module_info**)&gDeviceManager}, + {} + }; + +-- +2.30.2 + diff --git a/patchset-hrev55144/0112-virtio_net-set-device-name.patch b/patchset-hrev55144/0112-virtio_net-set-device-name.patch new file mode 100644 index 0000000..de66a97 --- /dev/null +++ b/patchset-hrev55144/0112-virtio_net-set-device-name.patch @@ -0,0 +1,29 @@ +From ce32538e1b67bd040d5b17b512bd384c2dc1ba3d Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:34:16 +0900 +Subject: virtio_net: set device name + +Change-Id: I1606804ad45e34f6a745c39917ba113ba5e9ee7f +--- + src/add-ons/kernel/drivers/network/virtio/virtio_net.cpp | 4 ++-- + 1 file changed, 2 insertions(+), 2 deletions(-) + +diff --git a/src/add-ons/kernel/drivers/network/virtio/virtio_net.cpp b/src/add-ons/kernel/drivers/network/virtio/virtio_net.cpp +index 1a4c04e14b..9fec8501f7 100644 +--- a/src/add-ons/kernel/drivers/network/virtio/virtio_net.cpp ++++ b/src/add-ons/kernel/drivers/network/virtio/virtio_net.cpp +@@ -895,9 +895,9 @@ virtio_net_register_device(device_node* node) + { + CALLED(); + +- // ready to register + device_attr attrs[] = { +- { NULL } ++ {B_DEVICE_PRETTY_NAME, B_STRING_TYPE, {string: "Virtio Network"}}, ++ {} + }; + + return sDeviceManager->register_node(node, VIRTIO_NET_DRIVER_MODULE_NAME, +-- +2.30.2 + diff --git a/patchset-hrev55144/0113-virtio_block-set-device-name.patch b/patchset-hrev55144/0113-virtio_block-set-device-name.patch new file mode 100644 index 0000000..2d47586 --- /dev/null +++ b/patchset-hrev55144/0113-virtio_block-set-device-name.patch @@ -0,0 +1,29 @@ +From b1edf4c4c85e4c322e4207ebd3d82b2c7eef310b Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:34:59 +0900 +Subject: virtio_block: set device name + +Change-Id: Id96e0dd2247625b7b898316511da7f1d8d0e3ba0 +--- + .../kernel/drivers/disk/virtual/virtio_block/virtio_block.cpp | 4 ++-- + 1 file changed, 2 insertions(+), 2 deletions(-) + +diff --git a/src/add-ons/kernel/drivers/disk/virtual/virtio_block/virtio_block.cpp b/src/add-ons/kernel/drivers/disk/virtual/virtio_block/virtio_block.cpp +index d16f054172..9849cbef88 100644 +--- a/src/add-ons/kernel/drivers/disk/virtual/virtio_block/virtio_block.cpp ++++ b/src/add-ons/kernel/drivers/disk/virtual/virtio_block/virtio_block.cpp +@@ -576,9 +576,9 @@ virtio_block_register_device(device_node *node) + { + CALLED(); + +- // ready to register + device_attr attrs[] = { +- { NULL } ++ {B_DEVICE_PRETTY_NAME, B_STRING_TYPE, {string: "Virtio Block"}}, ++ {} + }; + + return sDeviceManager->register_node(node, VIRTIO_BLOCK_DRIVER_MODULE_NAME, +-- +2.30.2 + diff --git a/patchset-hrev55144/0114-app_server-fix-unaligned-video-memory-access-on-risc.patch b/patchset-hrev55144/0114-app_server-fix-unaligned-video-memory-access-on-risc.patch new file mode 100644 index 0000000..2a278d0 --- /dev/null +++ b/patchset-hrev55144/0114-app_server-fix-unaligned-video-memory-access-on-risc.patch @@ -0,0 +1,38 @@ +From 4e5b127f5a295de602e9e3f4ff7007e3394a9bd2 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:38:08 +0900 +Subject: app_server: fix unaligned video memory access on riscv64 + +Change-Id: I40b0345c5d47f2b45acafb14f03fd3a24d2042a8 +--- + src/servers/app/drawing/drawing_support.h | 7 +++++++ + 1 file changed, 7 insertions(+) + +diff --git a/src/servers/app/drawing/drawing_support.h b/src/servers/app/drawing/drawing_support.h +index 1d8861c2fb..f00f4fa3f9 100644 +--- a/src/servers/app/drawing/drawing_support.h ++++ b/src/servers/app/drawing/drawing_support.h +@@ -65,6 +65,12 @@ gfxcpy(uint8* dst, const uint8* src, int32 numBytes) + static inline void + gfxcpy32(uint8* dst, const uint8* src, int32 numBytes) + { ++#ifdef __riscv ++ uint32* d32 = (uint32*)dst; ++ uint32* s32 = (uint32*)src; ++ for (; numBytes > 0; numBytes -= 4) ++ *d32++ = *s32++; ++#else + uint64* d64 = (uint64*)dst; + uint64* s64 = (uint64*)src; + int32 numBytesStart = numBytes; +@@ -89,6 +95,7 @@ gfxcpy32(uint8* dst, const uint8* src, int32 numBytes) + uint32* s32 = (uint32*)(src + numBytesStart - numBytes); + *d32 = *s32; + } ++#endif + } + + // gfxset32 +-- +2.30.2 + diff --git a/patchset-hrev55144/0115-boot_loader.efi-update-for-riscv64-2.patch b/patchset-hrev55144/0115-boot_loader.efi-update-for-riscv64-2.patch new file mode 100644 index 0000000..7ce84be --- /dev/null +++ b/patchset-hrev55144/0115-boot_loader.efi-update-for-riscv64-2.patch @@ -0,0 +1,26 @@ +From 687150639a74a10f6228aee4608820e712d816de Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:40:18 +0900 +Subject: boot_loader.efi: update for riscv64 (2) + +Change-Id: Icd45b38b4349e26c7799d7a3592dac688d335d6f +--- + src/system/boot/arch/riscv64/Jamfile | 2 ++ + 1 file changed, 2 insertions(+) + +diff --git a/src/system/boot/arch/riscv64/Jamfile b/src/system/boot/arch/riscv64/Jamfile +index fe86cad8e8..ce45eb3870 100644 +--- a/src/system/boot/arch/riscv64/Jamfile ++++ b/src/system/boot/arch/riscv64/Jamfile +@@ -17,6 +17,8 @@ local kernelLibArchObjects = + + local kernelArchDriverSources = + arch_elf.cpp ++ arch_uart_sifive.cpp ++ sbi_syscalls.S + ; + + local kernelGenericDriverSources = +-- +2.30.2 + diff --git a/patchset-hrev55144/0116-efi-add-NVRAM-variable-GUID-definition.patch b/patchset-hrev55144/0116-efi-add-NVRAM-variable-GUID-definition.patch new file mode 100644 index 0000000..5335cff --- /dev/null +++ b/patchset-hrev55144/0116-efi-add-NVRAM-variable-GUID-definition.patch @@ -0,0 +1,27 @@ +From 42915af11aae21ede4c55fb1e15c26a2a6a33a0c Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:41:02 +0900 +Subject: efi: add NVRAM variable GUID definition + +Change-Id: Iab4e59bb4ac91ba5e9c34e1ade433b423a140b9b +--- + headers/private/kernel/platform/efi/runtime-services.h | 3 +++ + 1 file changed, 3 insertions(+) + +diff --git a/headers/private/kernel/platform/efi/runtime-services.h b/headers/private/kernel/platform/efi/runtime-services.h +index 613b34f254..e853c683f2 100644 +--- a/headers/private/kernel/platform/efi/runtime-services.h ++++ b/headers/private/kernel/platform/efi/runtime-services.h +@@ -32,6 +32,9 @@ + #define EFI_HARDWARE_ERROR_VARIABLE \ + {0x414e6bdd, 0xe47b, 0x47cc, {0xb2, 0x44, 0xbb, 0x61, 0x02, 0x0c, 0xf5, 0x16}} + ++#define EFI_GLOBAL_VARIABLE \ ++ {0x8BE4DF61, 0x93CA, 0x11d2, {0xAA, 0x0D, 0x00, 0xE0, 0x98, 0x03, 0x2B, 0x8C}} ++ + typedef struct { + uint16_t Year; + uint8_t Month; +-- +2.30.2 + diff --git a/patchset-hrev55144/0117-DevicesView-make-connection-tree-a-default-option.patch b/patchset-hrev55144/0117-DevicesView-make-connection-tree-a-default-option.patch new file mode 100644 index 0000000..7401c91 --- /dev/null +++ b/patchset-hrev55144/0117-DevicesView-make-connection-tree-a-default-option.patch @@ -0,0 +1,26 @@ +From 7a35bb92ba1c286ecf75c5f564fb05e3ed5c0433 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:43:06 +0900 +Subject: DevicesView: make connection tree a default option + +Change-Id: I5472f2b5fa9ae7662977d9871a79ef00eee4a844 +--- + src/apps/devices/DevicesView.cpp | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/src/apps/devices/DevicesView.cpp b/src/apps/devices/DevicesView.cpp +index a487813710..514b0074f5 100644 +--- a/src/apps/devices/DevicesView.cpp ++++ b/src/apps/devices/DevicesView.cpp +@@ -68,7 +68,7 @@ DevicesView::CreateLayout() + new BMessage(kMsgOrderCategory)); + BMenuItem* byConnection = new BMenuItem(B_TRANSLATE("Connection"), + new BMessage(kMsgOrderConnection)); +- byCategory->SetMarked(true); ++ byConnection->SetMarked(true); + fOrderBy = byCategory->IsMarked() ? ORDER_BY_CATEGORY : + ORDER_BY_CONNECTION; + orderByPopupMenu->AddItem(byCategory); +-- +2.30.2 + diff --git a/patchset-hrev55144/0118-build_cross_tools-add-enable-initfini-array-flag-2.patch b/patchset-hrev55144/0118-build_cross_tools-add-enable-initfini-array-flag-2.patch new file mode 100644 index 0000000..b3f18ad --- /dev/null +++ b/patchset-hrev55144/0118-build_cross_tools-add-enable-initfini-array-flag-2.patch @@ -0,0 +1,26 @@ +From 9783672d0a62218a61f186b6be8c4dcefa0d2195 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:46:00 +0900 +Subject: build_cross_tools: add `--enable-initfini-array` flag (2) + +Change-Id: I3fba5521cb4858925780b34a864a3b71aa2c3b05 +--- + build/scripts/build_cross_tools_gcc4 | 2 ++ + 1 file changed, 2 insertions(+) + +diff --git a/build/scripts/build_cross_tools_gcc4 b/build/scripts/build_cross_tools_gcc4 +index 2368c93db1..aadf57ee56 100755 +--- a/build/scripts/build_cross_tools_gcc4 ++++ b/build/scripts/build_cross_tools_gcc4 +@@ -252,6 +252,8 @@ $MAKE $additionalMakeArgs || { + exit 1 + } + ++exit 0 ++ + # install gcc + $MAKE $additionalMakeArgs install || { + echo "ERROR: Installing the cross compiler failed." >&2 +-- +2.30.2 + diff --git a/patchset-hrev55144/0119-SlimDemo-update.patch b/patchset-hrev55144/0119-SlimDemo-update.patch new file mode 100644 index 0000000..e567e7f --- /dev/null +++ b/patchset-hrev55144/0119-SlimDemo-update.patch @@ -0,0 +1,60 @@ +From 80d976453eafa17ba8b5816a8f06ec94ea372c21 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:46:48 +0900 +Subject: SlimDemo: update + +Change-Id: Ie0fcf1d5e654dee227b6143461c0797762b7580d +--- + src/tests/servers/app/SlimDemo/main.c | 14 +++++++++++++- + 1 file changed, 13 insertions(+), 1 deletion(-) + +diff --git a/src/tests/servers/app/SlimDemo/main.c b/src/tests/servers/app/SlimDemo/main.c +index 02c0b322c2..d467a59449 100644 +--- a/src/tests/servers/app/SlimDemo/main.c ++++ b/src/tests/servers/app/SlimDemo/main.c +@@ -192,6 +192,7 @@ status_t get_and_set_mode(GetAccelerantHook gah, display_mode *dm) { + propose_display_mode pdm; + status_t result = B_ERROR; + set_display_mode sdm; ++ set_dpms_mode SetDpmsMode; + + /* find the propose mode hook */ + pdm = gah(B_PROPOSE_DISPLAY_MODE, NULL); +@@ -206,6 +207,8 @@ status_t get_and_set_mode(GetAccelerantHook gah, display_mode *dm) { + goto exit0; + } + ++ SetDpmsMode = gah(B_SET_DPMS_MODE, NULL); ++ + /* how many modes does the driver support */ + gmc = gah(B_ACCELERANT_MODE_COUNT, NULL); + if (!gmc) { +@@ -234,8 +237,16 @@ status_t get_and_set_mode(GetAccelerantHook gah, display_mode *dm) { + + /* take the first mode in the list */ + target = high = low = *mode_list; ++/* ++ for (uint32 i = 0; i < mode_count; i++) { ++ if ((mode_list[i].space & ~0x3000) == B_RGB32_LITTLE || (mode_list[i].space & ~0x3000) == B_RGB32_BIG) { ++ target = high = low = mode_list[i]; ++ break; ++ } ++ } ++*/ + /* make as tall a virtual height as possible */ +- target.virtual_height = high.virtual_height = 0xffff; ++ target.virtual_height = high.virtual_height = 2*target.virtual_height; + /* propose the display mode */ + if (pdm(&target, &low, &high) == B_ERROR) { + debug_printf("propose_display_mode failed\n"); +@@ -248,6 +259,7 @@ status_t get_and_set_mode(GetAccelerantHook gah, display_mode *dm) { + debug_printf("set display mode failed\n"); + goto free_mode_list; + } ++ SetDpmsMode(B_DPMS_ON); + /* note the mode and success */ + *dm = target; + result = B_OK; +-- +2.30.2 + diff --git a/patchset-hrev55144/0120-arm-changes-2.patch b/patchset-hrev55144/0120-arm-changes-2.patch new file mode 100644 index 0000000..340c567 --- /dev/null +++ b/patchset-hrev55144/0120-arm-changes-2.patch @@ -0,0 +1,39 @@ +From 823acc66bc0c99080e36b43c4899cd198f9c0a17 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:47:44 +0900 +Subject: arm changes (2) + +Change-Id: I2104300ad73eb7a0e11d1b24ab729e22cc359261 +--- + build/jam/ArchitectureRules | 8 ++++---- + 1 file changed, 4 insertions(+), 4 deletions(-) + +diff --git a/build/jam/ArchitectureRules b/build/jam/ArchitectureRules +index 7a5ee4e91c..5ba6a504eb 100644 +--- a/build/jam/ArchitectureRules ++++ b/build/jam/ArchitectureRules +@@ -39,7 +39,7 @@ rule ArchitectureSetup architecture + local archFlags ; + switch $(cpu) { + case ppc : archFlags += -mcpu=440fp ; +- case arm : archFlags += -march=armv7-a -mfloat-abi=hard ; ++ case arm : archFlags += -march=armv7-a -mfloat-abi=hard -fno-omit-frame-pointer ; + case x86 : archFlags += -march=pentium ; + case riscv64 : archFlags += -march=rv64gc ; + } +@@ -397,9 +397,9 @@ rule KernelArchitectureSetup architecture + + switch $(cpu) { + case arm : +- HAIKU_KERNEL_PIC_LINKFLAGS += -z max-page-size=0x1000 ; +- HAIKU_KERNEL_ADDON_LINKFLAGS += -z max-page-size=0x1000 ; +- HAIKU_KERNEL_PIC_CCFLAGS = -fno-pic ; ++ HAIKU_KERNEL_CCFLAGS += -fpic ; ++ HAIKU_KERNEL_C++FLAGS += -fpic ; ++ HAIKU_KERNEL_PIC_LINKFLAGS = -shared ; + + case arm64 : + HAIKU_KERNEL_PIC_LINKFLAGS += -z max-page-size=0x1000 ; +-- +2.30.2 + diff --git a/patchset-hrev55144/0121-makefile-engine-fix-for-riscv64.patch b/patchset-hrev55144/0121-makefile-engine-fix-for-riscv64.patch new file mode 100644 index 0000000..d2b1413 --- /dev/null +++ b/patchset-hrev55144/0121-makefile-engine-fix-for-riscv64.patch @@ -0,0 +1,26 @@ +From f898546db660b13b56440621c457df2d148e14c4 Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:48:19 +0900 +Subject: makefile-engine: fix for riscv64 + +Change-Id: I85c18ce812db65606ef6aba64f81b80872618263 +--- + data/develop/makefile-engine | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/data/develop/makefile-engine b/data/develop/makefile-engine +index 7ca3e7bf7e..dd4d1f718c 100644 +--- a/data/develop/makefile-engine ++++ b/data/develop/makefile-engine +@@ -144,7 +144,7 @@ VPATH := + VPATH += $(addprefix :, $(subst ,:, $(filter-out $($(subst, :, ,$(VPATH))), $(SRC_PATHS)))) + + # Set up the local & system include paths and C++ stdlibs. +-ifneq (,$(filter $(CPU),x86 x86_64)) ++ifneq (,$(filter $(CPU),x86 x86_64 riscv64)) + LOC_INCLUDES = $(foreach path, $(SRC_PATHS) $(LOCAL_INCLUDE_PATHS), $(addprefix -I, $(path))) + ifeq ($(CC_VER), 2) + INCLUDES = $(LOC_INCLUDES) +-- +2.30.2 + diff --git a/patchset-hrev55144/0122-experimental-temporary-image-definitions-change.patch b/patchset-hrev55144/0122-experimental-temporary-image-definitions-change.patch new file mode 100644 index 0000000..6b861e9 --- /dev/null +++ b/patchset-hrev55144/0122-experimental-temporary-image-definitions-change.patch @@ -0,0 +1,202 @@ +From d4164ab89ab578e72c6174b553cadf42b6ab750d Mon Sep 17 00:00:00 2001 +From: X512 +Date: Mon, 26 Jul 2021 03:49:11 +0900 +Subject: experimental temporary image definitions change + +Change-Id: I45046a226218cbaa6882362a6a91fd7d73e235ac +--- + build/jam/images/definitions/minimum | 59 ++++++++++++++++++++++------ + build/jam/images/definitions/regular | 3 +- + build/jam/packages/Haiku | 4 +- + 3 files changed, 51 insertions(+), 15 deletions(-) + +diff --git a/build/jam/images/definitions/minimum b/build/jam/images/definitions/minimum +index c32164f56c..6d5eceb39d 100644 +--- a/build/jam/images/definitions/minimum ++++ b/build/jam/images/definitions/minimum +@@ -32,6 +32,7 @@ SYSTEM_BIN = [ FFilterByBuildFeatures + urlwrapper useradd userdel + version vmstat + waitfor watch writembr@x86,x86_64 xres ++ dpms + ] ; + + SYSTEM_APPS = [ FFilterByBuildFeatures +@@ -45,6 +46,11 @@ SYSTEM_APPS = [ FFilterByBuildFeatures + ShowImage StyledEdit + Terminal TextSearch + Workspaces ++ ActivityMonitor ++ Icon-O-Matic Installer ++ Magnify MediaConverter MediaPlayer ++ People PoorMan ++ SerialConnect SoundRecorder + ] ; + + DESKBAR_APPLICATIONS = +@@ -53,12 +59,19 @@ DESKBAR_APPLICATIONS = + Expander + StyledEdit + Terminal ++ ActivityMonitor ++ Icon-O-Matic Installer ++ Magnify MediaConverter MediaPlayer ++ People PoorMan ++ SerialConnect SoundRecorder + ; + + DESKBAR_DESKTOP_APPLETS = + NetworkStatus + ProcessController + Workspaces ++ AutoRaise ++ LaunchBox + ; + + SYSTEM_PREFERENCES = [ FFilterByBuildFeatures +@@ -73,9 +86,15 @@ SYSTEM_PREFERENCES = [ FFilterByBuildFeatures + Screen Shortcuts + Time Tracker + VirtualMemory ++ DataTranslations ++ ScreenSaver + ] ; + +-SYSTEM_DEMOS = ; ++SYSTEM_DEMOS += [ FFilterByBuildFeatures ++ Chart Clock Cortex@expat FontDemo ++ Mandelbrot OverlayImage Pairs ++ Playground Pulse Sudoku ++] ; + + + rule HaikuImageGetSystemLibs +@@ -90,9 +109,12 @@ rule HaikuImageGetSystemLibs + libdebug.so + libdebugger.so@primary + libdevice.so ++ libgame.so + libgnu.so ++ libmedia.so + libnetwork.so + libpackage.so ++ libscreensaver.so + libtextencoding.so libtracker.so libtranslation.so + ] ] + ; +@@ -120,6 +142,7 @@ SYSTEM_SERVERS = [ FFilterByBuildFeatures + package_daemon power_daemon + registrar + syslog_daemon ++ media_addon_server media_server + ] ; + + SYSTEM_NETWORK_DEVICES = +@@ -143,22 +166,34 @@ SYSTEM_NETWORK_PROTOCOLS = + ; + + SYSTEM_ADD_ONS_ACCELERANTS = [ FFilterByBuildFeatures +- x86,x86_64,riscv64 @{ +- vesa.accelerant +- }@ # x86,x86_64,riscv64 ++ vesa.accelerant ++ ati.accelerant ++ radeon_hd.accelerant + ] ; + + SYSTEM_ADD_ONS_TRANSLATORS = ++ BMPTranslator ++ HVIFTranslator ++ TGATranslator + STXTTranslator + ; + + SYSTEM_ADD_ONS_LOCALE_CATALOGS = +- plaintext ++# plaintext + ; + +-SYSTEM_ADD_ONS_MEDIA = ; ++SYSTEM_ADD_ONS_MEDIA += [ FFilterByBuildFeatures ++ cortex_audioadapter.media_addon cortex_flanger.media_addon ++ cortex_logging_consumer.media_addon ++ hmulti_audio.media_addon ++ mixer.media_addon ++ tone_producer_demo.media_addon ++ video_producer_demo.media_addon video_window_demo.media_addon ++] ; + +-SYSTEM_ADD_ONS_MEDIA_PLUGINS = ; ++SYSTEM_ADD_ONS_MEDIA_PLUGINS += [ FFilterByBuildFeatures ++ raw_decoder ++] ; + + SYSTEM_ADD_ONS_PRINT = ; + +@@ -166,14 +201,16 @@ SYSTEM_ADD_ONS_PRINT_TRANSPORT = ; + + SYSTEM_ADD_ONS_SCREENSAVERS = ; + +-SYSTEM_ADD_ONS_DRIVERS_AUDIO = ; ++SYSTEM_ADD_ONS_DRIVERS_AUDIO += ++ hda ++; + + SYSTEM_ADD_ONS_DRIVERS_AUDIO_OLD = ; + + SYSTEM_ADD_ONS_DRIVERS_GRAPHICS = [ FFilterByBuildFeatures +- x86,x86_64,riscv64 @{ +- vesa +- }@ # x86,x86_64,riscv64 ++ vesa ++ ati ++ radeon_hd + ] ; + + SYSTEM_ADD_ONS_DRIVERS_MIDI = ; +diff --git a/build/jam/images/definitions/regular b/build/jam/images/definitions/regular +index 6d42312521..ac57f7a598 100644 +--- a/build/jam/images/definitions/regular ++++ b/build/jam/images/definitions/regular +@@ -118,7 +118,7 @@ SYSTEM_ADD_ONS_ACCELERANTS += [ FFilterByBuildFeatures + via.accelerant + }@ # x86,x86_64 + x86 @{ +- 3dfx.accelerant ati.accelerant neomagic.accelerant s3.accelerant ++ 3dfx.accelerant neomagic.accelerant s3.accelerant + }@ # x86 + ] ; + +@@ -214,7 +214,6 @@ SYSTEM_ADD_ONS_DRIVERS_GRAPHICS += [ FFilterByBuildFeatures + }@ # x86,x86_64 + x86 @{ + 3dfx +- ati + neomagic + s3 + }@ # x86 +diff --git a/build/jam/packages/Haiku b/build/jam/packages/Haiku +index 3e29e02899..64f4207ca1 100644 +--- a/build/jam/packages/Haiku ++++ b/build/jam/packages/Haiku +@@ -61,7 +61,7 @@ if $(TARGET_ARCH) = x86 || $(TARGET_ARCH) = x86_64 { + + # drivers + AddNewDriversToPackage : wmi@x86,x86_64 ; +-AddNewDriversToPackage disk : nvme_disk@x86,x86_64 ; ++AddNewDriversToPackage disk : nvme_disk ; + AddNewDriversToPackage disk mmc : mmc_disk ; + AddNewDriversToPackage disk scsi : scsi_cd scsi_disk ; + AddNewDriversToPackage disk virtual : virtio_block ram_disk ; +@@ -192,7 +192,7 @@ AddBootModuleSymlinksToPackage + ide_isa@x86 isa@x86,x86_64 intel it8211 + legacy_sata locked_pool + mmc mmc_disk +- nvme_disk@x86,x86_64 ++ nvme_disk + openpic@ppc + packagefs pci + fdt@riscv64 +-- +2.30.2 + diff --git a/screenshot.png b/screenshot.png index f8dc804..4fe968c 100644 Binary files a/screenshot.png and b/screenshot.png differ