Compare commits

..

1 commit

Author SHA1 Message Date
644926a361 feat: add SMTP server and mail sender scripts
Implement an SMTP server using aiosmtpd and a mail sender script. The 
server handles incoming messages and prints their content, while the 
mail sender constructs and sends an email message. These changes 
enable local email testing for the CNP assignment, improving 
development efficiency.
2025-03-24 03:41:40 +05:30
57 changed files with 52 additions and 9057 deletions

View file

@ -1,20 +0,0 @@
AREA RESET,DATA,READONLY
EXPORT __Vectors
__Vectors
DCD 0x10001000 ;
DCD Reset_Handler ;
ALIGN
AREA mycode, CODE, READONLY
ENTRY
EXPORT Reset_Handler
Reset_Handler
MOV R0,#10
MOV R1, #0x10
MOV R3, #2_1010
MOV R4, #5_34
MOV R5, #-8
STOP
B STOP
END;

View file

@ -1 +0,0 @@
DATATRANSFER.o: DATATRANSFER.asm

View file

@ -1,86 +0,0 @@
ARM Macro Assembler Page 1
1 00000000 AREA RESET,DATA,READONLY
2 00000000 EXPORT __Vectors
3 00000000 __Vectors
4 00000000 10001000 DCD 0x10001000 ;
5 00000004 00000000 DCD Reset_Handler ;
6 00000008 ALIGN
7 00000008 AREA mycode, CODE, READONLY
8 00000000 ENTRY
9 00000000 EXPORT Reset_Handler
10 00000000 Reset_Handler
11 00000000 F04F 000A MOV R0,#10
12 00000004 F04F 0110 MOV R1, #0x10
13 00000008 F04F 030A MOV R3, #2_1010
14 0000000C F04F 0413 MOV R4, #5_34
15 00000010 F06F 0507 MOV R5, #-8
16 00000014
17 00000014 STOP
18 00000014 E7FE B STOP
19 00000016
20 00000016 END ;
Command Line: --debug --xref --cpu=Cortex-M3 --apcs=interwork --depend=DATATRAN
SFER.d -oDATATRANSFER.o -IC:\Keil\ARM\RV31\INC -IC:\Keil\ARM\CMSIS\Include -IC:
\Keil\ARM\Inc\NXP\LPC17xx --predefine="__EVAL SETA 1" --list=DATATRANSFER.lst D
ATATRANSFER.asm
ARM Macro Assembler Page 1 Alphabetic symbol ordering
Relocatable symbols
RESET 00000000
Symbol: RESET
Definitions
At line 1 in file DATATRANSFER.asm
Uses
None
Comment: RESET unused
__Vectors 00000000
Symbol: __Vectors
Definitions
At line 3 in file DATATRANSFER.asm
Uses
At line 2 in file DATATRANSFER.asm
Comment: __Vectors used once
2 symbols
ARM Macro Assembler Page 1 Alphabetic symbol ordering
Relocatable symbols
Reset_Handler 00000000
Symbol: Reset_Handler
Definitions
At line 10 in file DATATRANSFER.asm
Uses
At line 5 in file DATATRANSFER.asm
At line 9 in file DATATRANSFER.asm
STOP 00000014
Symbol: STOP
Definitions
At line 17 in file DATATRANSFER.asm
Uses
At line 18 in file DATATRANSFER.asm
Comment: STOP used once
mycode 00000000
Symbol: mycode
Definitions
At line 7 in file DATATRANSFER.asm
Uses
None
Comment: mycode unused
3 symbols
336 symbols in table

Binary file not shown.

View file

@ -1 +0,0 @@
Taught MOV, DCD etc.

Binary file not shown.

View file

@ -1,35 +0,0 @@
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html><head>
<title>Static Call Graph - [F:\230953344\ES\Lab1\init\init.axf]</title></head>
<body><HR>
<H1>Static Call Graph for image F:\230953344\ES\Lab1\init\init.axf</H1><HR>
<BR><P>#&#060CALLGRAPH&#062# ARM Linker, 5.03 [Build 24]: Last Updated: Thu Jul 24 12:55:03 2025
<BR><P>
<H3>Maximum Stack Usage = 0 bytes + Unknown(Functions without stacksize, Untraceable Function Pointers)</H3><H3>
Call chain for Maximum Stack Depth:</H3>
<P>
<H3>
Functions with no stack information
</H3><UL>
<LI><a href="#[1]">Reset_Handler</a>
</UL>
</UL>
<P>
<H3>
Function Pointers
</H3><UL>
<LI><a href="#[1]">Reset_Handler</a> from datatransfer.o(mycode) referenced from datatransfer.o(RESET)
</UL>
<P>
<H3>
Global Symbols
</H3>
<P><STRONG><a name="[1]"></a>Reset_Handler</STRONG> (Thumb, 0 bytes, Stack size unknown bytes, datatransfer.o(mycode))
<P>
<H3>
Local Symbols
</H3><P>
<H3>
Undefined Global Symbols
</H3><HR></body></html>

View file

@ -1,4 +0,0 @@
--cpu Cortex-M3 "datatransfer.o"
--ro-base 0x00000000 --entry 0x00000000 --rw-base 0x10000000 --entry Reset_Handler --first __Vectors --strict --summary_stderr --info summarysizes --map --xref --callgraph --symbols
--info sizes --info totals --info unused --info veneers
--list ".\init.map" -o init.axf

View file

@ -1,94 +0,0 @@
ARM Linker, 5.03 [Build 24] [MDK-ARM Lite]
==============================================================================
Section Cross References
datatransfer.o(RESET) refers to datatransfer.o(mycode) for Reset_Handler
==============================================================================
Image Symbol Table
Local Symbols
Symbol Name Value Ov Type Size Object(Section)
RESET 0x00000000 Section 8 datatransfer.o(RESET)
DATATRANSFER.asm 0x00000000 Number 0 datatransfer.o ABSOLUTE
mycode 0x00000008 Section 22 datatransfer.o(mycode)
Global Symbols
Symbol Name Value Ov Type Size Object(Section)
BuildAttributes$$THM_ISAv4$P$D$K$B$S$PE$A:L22UL41UL21$X:L11$S22US41US21$IEEE1$IW$USESV6$~STKCKD$USESV7$~SHL$OSPACE$EBA8$STANDARDLIB$PRES8$EABIv2 0x00000000 Number 0 anon$$obj.o ABSOLUTE
__Vectors 0x00000000 Data 0 datatransfer.o(RESET)
Reset_Handler 0x00000009 Thumb Code 0 datatransfer.o(mycode)
==============================================================================
Memory Map of the image
Image Entry point : 0x00000009
Load Region LR_1 (Base: 0x00000000, Size: 0x00000020, Max: 0xffffffff, ABSOLUTE)
Execution Region ER_RO (Base: 0x00000000, Size: 0x00000020, Max: 0xffffffff, ABSOLUTE)
Base Addr Size Type Attr Idx E Section Name Object
0x00000000 0x00000008 Data RO 1 RESET datatransfer.o
0x00000008 0x00000016 Code RO 2 * mycode datatransfer.o
Execution Region ER_RW (Base: 0x10000000, Size: 0x00000000, Max: 0xffffffff, ABSOLUTE)
**** No section assigned to this execution region ****
Execution Region ER_ZI (Base: 0x10000000, Size: 0x00000000, Max: 0xffffffff, ABSOLUTE)
**** No section assigned to this execution region ****
==============================================================================
Image component sizes
Code (inc. data) RO Data RW Data ZI Data Debug Object Name
22 0 8 0 0 204 datatransfer.o
----------------------------------------------------------------------
24 0 8 0 0 204 Object Totals
0 0 0 0 0 0 (incl. Generated)
2 0 0 0 0 0 (incl. Padding)
----------------------------------------------------------------------
0 0 0 0 0 0 Library Totals
0 0 0 0 0 0 (incl. Padding)
----------------------------------------------------------------------
==============================================================================
Code (inc. data) RO Data RW Data ZI Data Debug
24 0 8 0 0 204 Grand Totals
24 0 8 0 0 204 ELF Image Totals
24 0 8 0 0 0 ROM Totals
==============================================================================
Total RO Size (Code + RO Data) 32 ( 0.03kB)
Total RW Size (RW Data + ZI Data) 0 ( 0.00kB)
Total ROM Size (Code + RO Data + RW Data) 32 ( 0.03kB)
==============================================================================

View file

@ -1,19 +0,0 @@
*** Creating Trace Output File 'init.tra' Ok.
### Preparing for ADS-LD.
### Creating ADS-LD Command Line
### List of Objects: adding '"datatransfer.o"'
### ADS-LD Command completed:
--cpu Cortex-M3 "datatransfer.o"
--ro-base 0x00000000 --entry 0x00000000 --rw-base 0x10000000 --entry Reset_Handler --first __Vectors --strict --summary_stderr --info summarysizes --map --xref --callgraph --symbols
--info sizes --info totals --info unused --info veneers
--list ".\init.map" -o init.axf### Preparing Environment (PrepEnvAds)
### ADS-LD Output File: 'init.axf'
### ADS-LD Command File: 'init.lnp'
### Checking for dirty Components...
### Creating CmdFile 'init.lnp', Handle=0x00000D34
### Writing '.lnp' file
### ADS-LD Command file 'init.lnp' is ready.
### ADS-LD: About to start ADS-LD Thread.
### ADS-LD: executed with 0 errors
### Updating obj list
### LDADS_file() completed.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1,232 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<ProjectOpt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="project_opt.xsd">
<SchemaVersion>1.0</SchemaVersion>
<Header>### uVision Project, (C) Keil Software</Header>
<Extensions>
<cExt>*.c</cExt>
<aExt>*.s*; *.src; *.a*</aExt>
<oExt>*.obj</oExt>
<lExt>*.lib</lExt>
<tExt>*.txt; *.h; *.inc</tExt>
<pExt>*.plm</pExt>
<CppX>*.cpp</CppX>
</Extensions>
<DaveTm>
<dwLowDateTime>0</dwLowDateTime>
<dwHighDateTime>0</dwHighDateTime>
</DaveTm>
<Target>
<TargetName>Target 1</TargetName>
<ToolsetNumber>0x4</ToolsetNumber>
<ToolsetName>ARM-ADS</ToolsetName>
<TargetOption>
<CLKADS>12000000</CLKADS>
<OPTTT>
<gFlags>0</gFlags>
<BeepAtEnd>1</BeepAtEnd>
<RunSim>1</RunSim>
<RunTarget>0</RunTarget>
</OPTTT>
<OPTHX>
<HexSelection>1</HexSelection>
<FlashByte>65535</FlashByte>
<HexRangeLowAddress>0</HexRangeLowAddress>
<HexRangeHighAddress>0</HexRangeHighAddress>
<HexOffset>0</HexOffset>
</OPTHX>
<OPTLEX>
<PageWidth>79</PageWidth>
<PageLength>66</PageLength>
<TabStop>8</TabStop>
<ListingPath>.\</ListingPath>
</OPTLEX>
<ListingPage>
<CreateCListing>1</CreateCListing>
<CreateAListing>1</CreateAListing>
<CreateLListing>1</CreateLListing>
<CreateIListing>0</CreateIListing>
<AsmCond>1</AsmCond>
<AsmSymb>1</AsmSymb>
<AsmXref>0</AsmXref>
<CCond>1</CCond>
<CCode>0</CCode>
<CListInc>0</CListInc>
<CSymb>0</CSymb>
<LinkerCodeListing>0</LinkerCodeListing>
</ListingPage>
<OPTXL>
<LMap>1</LMap>
<LComments>1</LComments>
<LGenerateSymbols>1</LGenerateSymbols>
<LLibSym>1</LLibSym>
<LLines>1</LLines>
<LLocSym>1</LLocSym>
<LPubSym>1</LPubSym>
<LXref>0</LXref>
<LExpSel>0</LExpSel>
</OPTXL>
<OPTFL>
<tvExp>1</tvExp>
<tvExpOptDlg>0</tvExpOptDlg>
<IsCurrentTarget>1</IsCurrentTarget>
</OPTFL>
<CpuCode>8</CpuCode>
<Books>
<Book>
<Number>0</Number>
<Title>Data Sheet</Title>
<Path>DATASHTS\PHILIPS\LPC176x_DS.pdf</Path>
</Book>
<Book>
<Number>1</Number>
<Title>User Manual</Title>
<Path>DATASHTS\PHILIPS\LPC17xx_UM.pdf</Path>
</Book>
<Book>
<Number>2</Number>
<Title>Errata Sheet</Title>
<Path>DATASHTS\PHILIPS\LPC1768_ES.pdf</Path>
</Book>
<Book>
<Number>3</Number>
<Title>Technical Reference Manual</Title>
<Path>datashts\arm\cortex_m3\r2p1\DDI0337I_CORTEXM3_R2P1_TRM.PDF</Path>
</Book>
<Book>
<Number>4</Number>
<Title>Generic User Guide</Title>
<Path>datashts\arm\cortex_m3\r2p1\DUI0552A_CORTEX_M3_DGUG.PDF</Path>
</Book>
</Books>
<DllOpt>
<SimDllName>SARMCM3.DLL</SimDllName>
<SimDllArguments>-MPU</SimDllArguments>
<SimDlgDllName>DARMP1.DLL</SimDlgDllName>
<SimDlgDllArguments>-pLPC1768</SimDlgDllArguments>
<TargetDllName>SARMCM3.DLL</TargetDllName>
<TargetDllArguments>-MPU</TargetDllArguments>
<TargetDlgDllName>TARMP1.DLL</TargetDlgDllName>
<TargetDlgDllArguments>-pLPC1768</TargetDlgDllArguments>
</DllOpt>
<DebugOpt>
<uSim>1</uSim>
<uTrg>0</uTrg>
<sLdApp>1</sLdApp>
<sGomain>1</sGomain>
<sRbreak>1</sRbreak>
<sRwatch>1</sRwatch>
<sRmem>1</sRmem>
<sRfunc>1</sRfunc>
<sRbox>1</sRbox>
<tLdApp>1</tLdApp>
<tGomain>0</tGomain>
<tRbreak>1</tRbreak>
<tRwatch>1</tRwatch>
<tRmem>1</tRmem>
<tRfunc>0</tRfunc>
<tRbox>1</tRbox>
<tRtrace>1</tRtrace>
<sRunDeb>0</sRunDeb>
<sLrtime>0</sLrtime>
<nTsel>1</nTsel>
<sDll></sDll>
<sDllPa></sDllPa>
<sDlgDll></sDlgDll>
<sDlgPa></sDlgPa>
<sIfile></sIfile>
<tDll></tDll>
<tDllPa></tDllPa>
<tDlgDll></tDlgDll>
<tDlgPa></tDlgPa>
<tIfile></tIfile>
<pMon>BIN\UL2CM3.DLL</pMon>
</DebugOpt>
<TargetDriverDllRegistry>
<SetRegEntry>
<Number>0</Number>
<Key>DLGDARM</Key>
<Name>(1010=-1,-1,-1,-1,0)(1007=-1,-1,-1,-1,0)(1008=-1,-1,-1,-1,0)(1009=-1,-1,-1,-1,0)(1012=-1,-1,-1,-1,0)(350=-1,-1,-1,-1,0)(250=-1,-1,-1,-1,0)(270=-1,-1,-1,-1,0)(313=-1,-1,-1,-1,0)(291=-1,-1,-1,-1,0)(302=-1,-1,-1,-1,0)(110=-1,-1,-1,-1,0)(113=-1,-1,-1,-1,0)(320=-1,-1,-1,-1,0)(210=-1,-1,-1,-1,0)(330=-1,-1,-1,-1,0)(332=-1,-1,-1,-1,0)(333=-1,-1,-1,-1,0)(334=-1,-1,-1,-1,0)(335=-1,-1,-1,-1,0)(336=-1,-1,-1,-1,0)(345=-1,-1,-1,-1,0)(346=-1,-1,-1,-1,0)(381=-1,-1,-1,-1,0)(382=-1,-1,-1,-1,0)(383=-1,-1,-1,-1,0)(384=-1,-1,-1,-1,0)(197=-1,-1,-1,-1,0)(198=-1,-1,-1,-1,0)(191=-1,-1,-1,-1,0)(192=-1,-1,-1,-1,0)(199=-1,-1,-1,-1,0)(180=-1,-1,-1,-1,0)(261=-1,-1,-1,-1,0)(262=-1,-1,-1,-1,0)(231=-1,-1,-1,-1,0)(232=-1,-1,-1,-1,0)(233=-1,-1,-1,-1,0)(121=-1,-1,-1,-1,0)(122=-1,-1,-1,-1,0)(123=-1,-1,-1,-1,0)(124=-1,-1,-1,-1,0)(170=-1,-1,-1,-1,0)(142=-1,-1,-1,-1,0)(150=-1,-1,-1,-1,0)(400=-1,-1,-1,-1,0)(370=-1,-1,-1,-1,0)(160=-1,-1,-1,-1,0)(280=-1,-1,-1,-1,0)(240=-1,-1,-1,-1,0)</Name>
</SetRegEntry>
<SetRegEntry>
<Number>0</Number>
<Key>ARMDBGFLAGS</Key>
<Name>-T0</Name>
</SetRegEntry>
<SetRegEntry>
<Number>0</Number>
<Key>UL2CM3</Key>
<Name>-O463 -S0 -C0 -FO7 -FD10000000 -FC800 -FN1 -FF0LPC_IAP_512 -FS00 -FL080000)</Name>
</SetRegEntry>
</TargetDriverDllRegistry>
<Breakpoint/>
<MemoryWindow1>
<Mm>
<WinNumber>1</WinNumber>
<SubType>0</SubType>
<ItemText>0x000000A</ItemText>
</Mm>
</MemoryWindow1>
<DebugFlag>
<trace>0</trace>
<periodic>1</periodic>
<aLwin>1</aLwin>
<aCover>0</aCover>
<aSer1>0</aSer1>
<aSer2>0</aSer2>
<aPa>0</aPa>
<viewmode>1</viewmode>
<vrSel>0</vrSel>
<aSym>0</aSym>
<aTbox>0</aTbox>
<AscS1>0</AscS1>
<AscS2>0</AscS2>
<AscS3>0</AscS3>
<aSer3>0</aSer3>
<eProf>0</eProf>
<aLa>0</aLa>
<aPa1>0</aPa1>
<AscS4>0</AscS4>
<aSer4>0</aSer4>
<StkLoc>0</StkLoc>
<TrcWin>0</TrcWin>
<newCpu>0</newCpu>
<uProt>0</uProt>
</DebugFlag>
<Tracepoint>
<THDelay>0</THDelay>
</Tracepoint>
<LintExecutable></LintExecutable>
<LintConfigFile></LintConfigFile>
</TargetOption>
</Target>
<Group>
<GroupName>Source Group 1</GroupName>
<tvExp>1</tvExp>
<tvExpOptDlg>0</tvExpOptDlg>
<cbSel>0</cbSel>
<RteFlg>0</RteFlg>
<File>
<GroupNumber>1</GroupNumber>
<FileNumber>1</FileNumber>
<FileType>2</FileType>
<tvExp>0</tvExp>
<Focus>0</Focus>
<ColumnNumber>0</ColumnNumber>
<tvExpOptDlg>0</tvExpOptDlg>
<TopLine>1</TopLine>
<CurrentLine>11</CurrentLine>
<bDave2>0</bDave2>
<PathWithFileName>.\DATATRANSFER.asm</PathWithFileName>
<FilenameWithoutPath>DATATRANSFER.asm</FilenameWithoutPath>
<RteFlg>0</RteFlg>
<bShared>0</bShared>
</File>
</Group>
</ProjectOpt>

View file

@ -1,405 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<Project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="project_proj.xsd">
<SchemaVersion>1.1</SchemaVersion>
<Header>### uVision Project, (C) Keil Software</Header>
<Targets>
<Target>
<TargetName>Target 1</TargetName>
<ToolsetNumber>0x4</ToolsetNumber>
<ToolsetName>ARM-ADS</ToolsetName>
<TargetOption>
<TargetCommonOption>
<Device>LPC1768</Device>
<Vendor>NXP (founded by Philips)</Vendor>
<Cpu>IRAM(0x10000000-0x10007FFF) IRAM2(0x2007C000-0x20083FFF) IROM(0-0x7FFFF) CLOCK(12000000) CPUTYPE("Cortex-M3")</Cpu>
<FlashUtilSpec></FlashUtilSpec>
<StartupFile>"STARTUP\NXP\LPC17xx\startup_LPC17xx.s" ("NXP LPC17xx Startup Code")</StartupFile>
<FlashDriverDll>UL2CM3(-O463 -S0 -C0 -FO7 -FD10000000 -FC800 -FN1 -FF0LPC_IAP_512 -FS00 -FL080000)</FlashDriverDll>
<DeviceId>4868</DeviceId>
<RegisterFile>LPC17xx.H</RegisterFile>
<MemoryEnv></MemoryEnv>
<Cmp></Cmp>
<Asm></Asm>
<Linker></Linker>
<OHString></OHString>
<InfinionOptionDll></InfinionOptionDll>
<SLE66CMisc></SLE66CMisc>
<SLE66AMisc></SLE66AMisc>
<SLE66LinkerMisc></SLE66LinkerMisc>
<SFDFile></SFDFile>
<UseEnv>0</UseEnv>
<BinPath></BinPath>
<IncludePath></IncludePath>
<LibPath></LibPath>
<RegisterFilePath>NXP\LPC17xx\</RegisterFilePath>
<DBRegisterFilePath>NXP\LPC17xx\</DBRegisterFilePath>
<TargetStatus>
<Error>0</Error>
<ExitCodeStop>0</ExitCodeStop>
<ButtonStop>0</ButtonStop>
<NotGenerated>0</NotGenerated>
<InvalidFlash>1</InvalidFlash>
</TargetStatus>
<OutputDirectory>.\</OutputDirectory>
<OutputName>init</OutputName>
<CreateExecutable>1</CreateExecutable>
<CreateLib>0</CreateLib>
<CreateHexFile>0</CreateHexFile>
<DebugInformation>1</DebugInformation>
<BrowseInformation>1</BrowseInformation>
<ListingPath>.\</ListingPath>
<HexFormatSelection>1</HexFormatSelection>
<Merge32K>0</Merge32K>
<CreateBatchFile>0</CreateBatchFile>
<BeforeCompile>
<RunUserProg1>0</RunUserProg1>
<RunUserProg2>0</RunUserProg2>
<UserProg1Name></UserProg1Name>
<UserProg2Name></UserProg2Name>
<UserProg1Dos16Mode>0</UserProg1Dos16Mode>
<UserProg2Dos16Mode>0</UserProg2Dos16Mode>
<nStopU1X>0</nStopU1X>
<nStopU2X>0</nStopU2X>
</BeforeCompile>
<BeforeMake>
<RunUserProg1>0</RunUserProg1>
<RunUserProg2>0</RunUserProg2>
<UserProg1Name></UserProg1Name>
<UserProg2Name></UserProg2Name>
<UserProg1Dos16Mode>0</UserProg1Dos16Mode>
<UserProg2Dos16Mode>0</UserProg2Dos16Mode>
</BeforeMake>
<AfterMake>
<RunUserProg1>0</RunUserProg1>
<RunUserProg2>0</RunUserProg2>
<UserProg1Name></UserProg1Name>
<UserProg2Name></UserProg2Name>
<UserProg1Dos16Mode>0</UserProg1Dos16Mode>
<UserProg2Dos16Mode>0</UserProg2Dos16Mode>
</AfterMake>
<SelectedForBatchBuild>0</SelectedForBatchBuild>
<SVCSIdString></SVCSIdString>
</TargetCommonOption>
<CommonProperty>
<UseCPPCompiler>0</UseCPPCompiler>
<RVCTCodeConst>0</RVCTCodeConst>
<RVCTZI>0</RVCTZI>
<RVCTOtherData>0</RVCTOtherData>
<ModuleSelection>0</ModuleSelection>
<IncludeInBuild>1</IncludeInBuild>
<AlwaysBuild>0</AlwaysBuild>
<GenerateAssemblyFile>0</GenerateAssemblyFile>
<AssembleAssemblyFile>0</AssembleAssemblyFile>
<PublicsOnly>0</PublicsOnly>
<StopOnExitCode>3</StopOnExitCode>
<CustomArgument></CustomArgument>
<IncludeLibraryModules></IncludeLibraryModules>
</CommonProperty>
<DllOption>
<SimDllName>SARMCM3.DLL</SimDllName>
<SimDllArguments>-MPU</SimDllArguments>
<SimDlgDll>DARMP1.DLL</SimDlgDll>
<SimDlgDllArguments>-pLPC1768</SimDlgDllArguments>
<TargetDllName>SARMCM3.DLL</TargetDllName>
<TargetDllArguments>-MPU</TargetDllArguments>
<TargetDlgDll>TARMP1.DLL</TargetDlgDll>
<TargetDlgDllArguments>-pLPC1768</TargetDlgDllArguments>
</DllOption>
<DebugOption>
<OPTHX>
<HexSelection>1</HexSelection>
<HexRangeLowAddress>0</HexRangeLowAddress>
<HexRangeHighAddress>0</HexRangeHighAddress>
<HexOffset>0</HexOffset>
<Oh166RecLen>16</Oh166RecLen>
</OPTHX>
<Simulator>
<UseSimulator>1</UseSimulator>
<LoadApplicationAtStartup>1</LoadApplicationAtStartup>
<RunToMain>1</RunToMain>
<RestoreBreakpoints>1</RestoreBreakpoints>
<RestoreWatchpoints>1</RestoreWatchpoints>
<RestoreMemoryDisplay>1</RestoreMemoryDisplay>
<RestoreFunctions>1</RestoreFunctions>
<RestoreToolbox>1</RestoreToolbox>
<LimitSpeedToRealTime>0</LimitSpeedToRealTime>
</Simulator>
<Target>
<UseTarget>0</UseTarget>
<LoadApplicationAtStartup>1</LoadApplicationAtStartup>
<RunToMain>0</RunToMain>
<RestoreBreakpoints>1</RestoreBreakpoints>
<RestoreWatchpoints>1</RestoreWatchpoints>
<RestoreMemoryDisplay>1</RestoreMemoryDisplay>
<RestoreFunctions>0</RestoreFunctions>
<RestoreToolbox>1</RestoreToolbox>
<RestoreTracepoints>1</RestoreTracepoints>
</Target>
<RunDebugAfterBuild>0</RunDebugAfterBuild>
<TargetSelection>1</TargetSelection>
<SimDlls>
<CpuDll></CpuDll>
<CpuDllArguments></CpuDllArguments>
<PeripheralDll></PeripheralDll>
<PeripheralDllArguments></PeripheralDllArguments>
<InitializationFile></InitializationFile>
</SimDlls>
<TargetDlls>
<CpuDll></CpuDll>
<CpuDllArguments></CpuDllArguments>
<PeripheralDll></PeripheralDll>
<PeripheralDllArguments></PeripheralDllArguments>
<InitializationFile></InitializationFile>
<Driver>BIN\UL2CM3.DLL</Driver>
</TargetDlls>
</DebugOption>
<Utilities>
<Flash1>
<UseTargetDll>1</UseTargetDll>
<UseExternalTool>0</UseExternalTool>
<RunIndependent>0</RunIndependent>
<UpdateFlashBeforeDebugging>1</UpdateFlashBeforeDebugging>
<Capability>0</Capability>
<DriverSelection>-1</DriverSelection>
</Flash1>
<Flash2>BIN\UL2CM3.DLL</Flash2>
<Flash3></Flash3>
<Flash4></Flash4>
</Utilities>
<TargetArmAds>
<ArmAdsMisc>
<GenerateListings>0</GenerateListings>
<asHll>1</asHll>
<asAsm>1</asAsm>
<asMacX>1</asMacX>
<asSyms>1</asSyms>
<asFals>1</asFals>
<asDbgD>1</asDbgD>
<asForm>1</asForm>
<ldLst>0</ldLst>
<ldmm>1</ldmm>
<ldXref>1</ldXref>
<BigEnd>0</BigEnd>
<AdsALst>1</AdsALst>
<AdsACrf>1</AdsACrf>
<AdsANop>0</AdsANop>
<AdsANot>0</AdsANot>
<AdsLLst>1</AdsLLst>
<AdsLmap>1</AdsLmap>
<AdsLcgr>1</AdsLcgr>
<AdsLsym>1</AdsLsym>
<AdsLszi>1</AdsLszi>
<AdsLtoi>1</AdsLtoi>
<AdsLsun>1</AdsLsun>
<AdsLven>1</AdsLven>
<AdsLsxf>1</AdsLsxf>
<RvctClst>0</RvctClst>
<GenPPlst>0</GenPPlst>
<AdsCpuType>"Cortex-M3"</AdsCpuType>
<RvctDeviceName></RvctDeviceName>
<mOS>0</mOS>
<uocRom>0</uocRom>
<uocRam>0</uocRam>
<hadIROM>1</hadIROM>
<hadIRAM>1</hadIRAM>
<hadXRAM>0</hadXRAM>
<uocXRam>0</uocXRam>
<RvdsVP>0</RvdsVP>
<hadIRAM2>1</hadIRAM2>
<hadIROM2>0</hadIROM2>
<StupSel>8</StupSel>
<useUlib>0</useUlib>
<EndSel>0</EndSel>
<uLtcg>0</uLtcg>
<RoSelD>3</RoSelD>
<RwSelD>3</RwSelD>
<CodeSel>0</CodeSel>
<OptFeed>0</OptFeed>
<NoZi1>0</NoZi1>
<NoZi2>0</NoZi2>
<NoZi3>0</NoZi3>
<NoZi4>0</NoZi4>
<NoZi5>0</NoZi5>
<Ro1Chk>0</Ro1Chk>
<Ro2Chk>0</Ro2Chk>
<Ro3Chk>0</Ro3Chk>
<Ir1Chk>1</Ir1Chk>
<Ir2Chk>0</Ir2Chk>
<Ra1Chk>0</Ra1Chk>
<Ra2Chk>0</Ra2Chk>
<Ra3Chk>0</Ra3Chk>
<Im1Chk>1</Im1Chk>
<Im2Chk>0</Im2Chk>
<OnChipMemories>
<Ocm1>
<Type>0</Type>
<StartAddress>0x0</StartAddress>
<Size>0x0</Size>
</Ocm1>
<Ocm2>
<Type>0</Type>
<StartAddress>0x0</StartAddress>
<Size>0x0</Size>
</Ocm2>
<Ocm3>
<Type>0</Type>
<StartAddress>0x0</StartAddress>
<Size>0x0</Size>
</Ocm3>
<Ocm4>
<Type>0</Type>
<StartAddress>0x0</StartAddress>
<Size>0x0</Size>
</Ocm4>
<Ocm5>
<Type>0</Type>
<StartAddress>0x0</StartAddress>
<Size>0x0</Size>
</Ocm5>
<Ocm6>
<Type>0</Type>
<StartAddress>0x0</StartAddress>
<Size>0x0</Size>
</Ocm6>
<IRAM>
<Type>0</Type>
<StartAddress>0x10000000</StartAddress>
<Size>0x8000</Size>
</IRAM>
<IROM>
<Type>1</Type>
<StartAddress>0x0</StartAddress>
<Size>0x80000</Size>
</IROM>
<XRAM>
<Type>0</Type>
<StartAddress>0x0</StartAddress>
<Size>0x0</Size>
</XRAM>
<OCR_RVCT1>
<Type>0</Type>
<StartAddress>0x0</StartAddress>
<Size>0x0</Size>
</OCR_RVCT1>
<OCR_RVCT2>
<Type>0</Type>
<StartAddress>0x0</StartAddress>
<Size>0x0</Size>
</OCR_RVCT2>
<OCR_RVCT3>
<Type>0</Type>
<StartAddress>0x0</StartAddress>
<Size>0x0</Size>
</OCR_RVCT3>
<OCR_RVCT4>
<Type>1</Type>
<StartAddress>0x0</StartAddress>
<Size>0x80000</Size>
</OCR_RVCT4>
<OCR_RVCT5>
<Type>0</Type>
<StartAddress>0x0</StartAddress>
<Size>0x0</Size>
</OCR_RVCT5>
<OCR_RVCT6>
<Type>0</Type>
<StartAddress>0x0</StartAddress>
<Size>0x0</Size>
</OCR_RVCT6>
<OCR_RVCT7>
<Type>0</Type>
<StartAddress>0x0</StartAddress>
<Size>0x0</Size>
</OCR_RVCT7>
<OCR_RVCT8>
<Type>0</Type>
<StartAddress>0x0</StartAddress>
<Size>0x0</Size>
</OCR_RVCT8>
<OCR_RVCT9>
<Type>0</Type>
<StartAddress>0x10000000</StartAddress>
<Size>0x8000</Size>
</OCR_RVCT9>
<OCR_RVCT10>
<Type>0</Type>
<StartAddress>0x2007c000</StartAddress>
<Size>0x8000</Size>
</OCR_RVCT10>
</OnChipMemories>
<RvctStartVector></RvctStartVector>
</ArmAdsMisc>
<Cads>
<interw>1</interw>
<Optim>1</Optim>
<oTime>0</oTime>
<SplitLS>0</SplitLS>
<OneElfS>0</OneElfS>
<Strict>0</Strict>
<EnumInt>0</EnumInt>
<PlainCh>0</PlainCh>
<Ropi>0</Ropi>
<Rwpi>0</Rwpi>
<wLevel>0</wLevel>
<uThumb>0</uThumb>
<uSurpInc>0</uSurpInc>
<VariousControls>
<MiscControls></MiscControls>
<Define></Define>
<Undefine></Undefine>
<IncludePath></IncludePath>
</VariousControls>
</Cads>
<Aads>
<interw>1</interw>
<Ropi>0</Ropi>
<Rwpi>0</Rwpi>
<thumb>0</thumb>
<SplitLS>0</SplitLS>
<SwStkChk>0</SwStkChk>
<NoWarn>0</NoWarn>
<uSurpInc>0</uSurpInc>
<VariousControls>
<MiscControls></MiscControls>
<Define></Define>
<Undefine></Undefine>
<IncludePath></IncludePath>
</VariousControls>
</Aads>
<LDads>
<umfTarg>0</umfTarg>
<Ropi>0</Ropi>
<Rwpi>0</Rwpi>
<noStLib>0</noStLib>
<RepFail>1</RepFail>
<useFile>0</useFile>
<TextAddressRange>0x00000000</TextAddressRange>
<DataAddressRange>0x10000000</DataAddressRange>
<ScatterFile></ScatterFile>
<IncludeLibs></IncludeLibs>
<IncludeLibsPath></IncludeLibsPath>
<Misc></Misc>
<LinkerInputFile></LinkerInputFile>
<DisabledWarnings></DisabledWarnings>
</LDads>
</TargetArmAds>
</TargetOption>
<Groups>
<Group>
<GroupName>Source Group 1</GroupName>
<Files>
<File>
<FileName>DATATRANSFER.asm</FileName>
<FileType>2</FileType>
<FilePath>.\DATATRANSFER.asm</FilePath>
</File>
</Files>
</Group>
</Groups>
</Target>
</Targets>
</Project>

View file

@ -1,2 +0,0 @@
Dependencies for Project 'init', Target 'Target 1': (DO NOT MODIFY !)
F (.\DATATRANSFER.asm)(0x6881DFCC)(--cpu Cortex-M3 --pd "__EVAL SETA 1" -g --apcs=interwork -I C:\Keil\ARM\RV31\INC -I C:\Keil\ARM\CMSIS\Include -I C:\Keil\ARM\Inc\NXP\LPC17xx --list "DATATRANSFER.lst" --xref -o "DATATRANSFER.o" --depend "DATATRANSFER.d")

View file

@ -1,249 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<ProjectOpt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="project_opt.xsd">
<SchemaVersion>1.0</SchemaVersion>
<Header>### uVision Project, (C) Keil Software</Header>
<Extensions>
<cExt>*.c</cExt>
<aExt>*.s*; *.src; *.a*</aExt>
<oExt>*.obj</oExt>
<lExt>*.lib</lExt>
<tExt>*.txt; *.h; *.inc</tExt>
<pExt>*.plm</pExt>
<CppX>*.cpp</CppX>
</Extensions>
<DaveTm>
<dwLowDateTime>0</dwLowDateTime>
<dwHighDateTime>0</dwHighDateTime>
</DaveTm>
<Target>
<TargetName>Target 1</TargetName>
<ToolsetNumber>0x4</ToolsetNumber>
<ToolsetName>ARM-ADS</ToolsetName>
<TargetOption>
<CLKADS>12000000</CLKADS>
<OPTTT>
<gFlags>0</gFlags>
<BeepAtEnd>1</BeepAtEnd>
<RunSim>1</RunSim>
<RunTarget>0</RunTarget>
</OPTTT>
<OPTHX>
<HexSelection>1</HexSelection>
<FlashByte>65535</FlashByte>
<HexRangeLowAddress>0</HexRangeLowAddress>
<HexRangeHighAddress>0</HexRangeHighAddress>
<HexOffset>0</HexOffset>
</OPTHX>
<OPTLEX>
<PageWidth>79</PageWidth>
<PageLength>66</PageLength>
<TabStop>8</TabStop>
<ListingPath>.\</ListingPath>
</OPTLEX>
<ListingPage>
<CreateCListing>1</CreateCListing>
<CreateAListing>1</CreateAListing>
<CreateLListing>1</CreateLListing>
<CreateIListing>0</CreateIListing>
<AsmCond>1</AsmCond>
<AsmSymb>1</AsmSymb>
<AsmXref>0</AsmXref>
<CCond>1</CCond>
<CCode>0</CCode>
<CListInc>0</CListInc>
<CSymb>0</CSymb>
<LinkerCodeListing>0</LinkerCodeListing>
</ListingPage>
<OPTXL>
<LMap>1</LMap>
<LComments>1</LComments>
<LGenerateSymbols>1</LGenerateSymbols>
<LLibSym>1</LLibSym>
<LLines>1</LLines>
<LLocSym>1</LLocSym>
<LPubSym>1</LPubSym>
<LXref>0</LXref>
<LExpSel>0</LExpSel>
</OPTXL>
<OPTFL>
<tvExp>1</tvExp>
<tvExpOptDlg>0</tvExpOptDlg>
<IsCurrentTarget>1</IsCurrentTarget>
</OPTFL>
<CpuCode>8</CpuCode>
<Books>
<Book>
<Number>0</Number>
<Title>Data Sheet</Title>
<Path>DATASHTS\PHILIPS\LPC176x_DS.pdf</Path>
</Book>
<Book>
<Number>1</Number>
<Title>User Manual</Title>
<Path>DATASHTS\PHILIPS\LPC17xx_UM.pdf</Path>
</Book>
<Book>
<Number>2</Number>
<Title>Errata Sheet</Title>
<Path>DATASHTS\PHILIPS\LPC1768_ES.pdf</Path>
</Book>
<Book>
<Number>3</Number>
<Title>Technical Reference Manual</Title>
<Path>datashts\arm\cortex_m3\r2p1\DDI0337I_CORTEXM3_R2P1_TRM.PDF</Path>
</Book>
<Book>
<Number>4</Number>
<Title>Generic User Guide</Title>
<Path>datashts\arm\cortex_m3\r2p1\DUI0552A_CORTEX_M3_DGUG.PDF</Path>
</Book>
</Books>
<DllOpt>
<SimDllName>SARMCM3.DLL</SimDllName>
<SimDllArguments>-MPU</SimDllArguments>
<SimDlgDllName>DARMP1.DLL</SimDlgDllName>
<SimDlgDllArguments>-pLPC1768</SimDlgDllArguments>
<TargetDllName>SARMCM3.DLL</TargetDllName>
<TargetDllArguments>-MPU</TargetDllArguments>
<TargetDlgDllName>TARMP1.DLL</TargetDlgDllName>
<TargetDlgDllArguments>-pLPC1768</TargetDlgDllArguments>
</DllOpt>
<DebugOpt>
<uSim>1</uSim>
<uTrg>0</uTrg>
<sLdApp>1</sLdApp>
<sGomain>1</sGomain>
<sRbreak>1</sRbreak>
<sRwatch>1</sRwatch>
<sRmem>1</sRmem>
<sRfunc>1</sRfunc>
<sRbox>1</sRbox>
<tLdApp>1</tLdApp>
<tGomain>0</tGomain>
<tRbreak>1</tRbreak>
<tRwatch>1</tRwatch>
<tRmem>1</tRmem>
<tRfunc>0</tRfunc>
<tRbox>1</tRbox>
<tRtrace>1</tRtrace>
<sRunDeb>0</sRunDeb>
<sLrtime>0</sLrtime>
<nTsel>1</nTsel>
<sDll></sDll>
<sDllPa></sDllPa>
<sDlgDll></sDlgDll>
<sDlgPa></sDlgPa>
<sIfile></sIfile>
<tDll></tDll>
<tDllPa></tDllPa>
<tDlgDll></tDlgDll>
<tDlgPa></tDlgPa>
<tIfile></tIfile>
<pMon>BIN\UL2CM3.DLL</pMon>
</DebugOpt>
<TargetDriverDllRegistry>
<SetRegEntry>
<Number>0</Number>
<Key>DLGDARM</Key>
<Name>(1010=-1,-1,-1,-1,0)(1007=-1,-1,-1,-1,0)(1008=-1,-1,-1,-1,0)(1009=-1,-1,-1,-1,0)(1012=-1,-1,-1,-1,0)(350=-1,-1,-1,-1,0)(250=-1,-1,-1,-1,0)(270=-1,-1,-1,-1,0)(313=-1,-1,-1,-1,0)(291=-1,-1,-1,-1,0)(302=-1,-1,-1,-1,0)(110=-1,-1,-1,-1,0)(113=-1,-1,-1,-1,0)(320=-1,-1,-1,-1,0)(210=-1,-1,-1,-1,0)(330=-1,-1,-1,-1,0)(332=-1,-1,-1,-1,0)(333=-1,-1,-1,-1,0)(334=-1,-1,-1,-1,0)(335=-1,-1,-1,-1,0)(336=-1,-1,-1,-1,0)(345=-1,-1,-1,-1,0)(346=-1,-1,-1,-1,0)(381=-1,-1,-1,-1,0)(382=-1,-1,-1,-1,0)(383=-1,-1,-1,-1,0)(384=-1,-1,-1,-1,0)(197=-1,-1,-1,-1,0)(198=-1,-1,-1,-1,0)(191=-1,-1,-1,-1,0)(192=-1,-1,-1,-1,0)(199=-1,-1,-1,-1,0)(180=-1,-1,-1,-1,0)(261=-1,-1,-1,-1,0)(262=-1,-1,-1,-1,0)(231=-1,-1,-1,-1,0)(232=-1,-1,-1,-1,0)(233=-1,-1,-1,-1,0)(121=-1,-1,-1,-1,0)(122=-1,-1,-1,-1,0)(123=-1,-1,-1,-1,0)(124=-1,-1,-1,-1,0)(170=-1,-1,-1,-1,0)(142=-1,-1,-1,-1,0)(150=-1,-1,-1,-1,0)(400=-1,-1,-1,-1,0)(370=-1,-1,-1,-1,0)(160=-1,-1,-1,-1,0)(280=-1,-1,-1,-1,0)(240=-1,-1,-1,-1,0)</Name>
</SetRegEntry>
<SetRegEntry>
<Number>0</Number>
<Key>ARMDBGFLAGS</Key>
<Name>-T0</Name>
</SetRegEntry>
<SetRegEntry>
<Number>0</Number>
<Key>UL2CM3</Key>
<Name>-O463 -S0 -C0 -FO7 -FD10000000 -FC800 -FN1 -FF0LPC_IAP_512 -FS00 -FL080000)</Name>
</SetRegEntry>
</TargetDriverDllRegistry>
<Breakpoint>
<Bp>
<Number>0</Number>
<Type>0</Type>
<LineNumber>11</LineNumber>
<EnabledFlag>1</EnabledFlag>
<Address>0</Address>
<ByteObject>0</ByteObject>
<HtxType>0</HtxType>
<ManyObjects>0</ManyObjects>
<SizeOfObject>0</SizeOfObject>
<BreakByAccess>0</BreakByAccess>
<BreakIfRCount>0</BreakIfRCount>
<Filename>F:\230953344\ES\Lab1\DATATRANSFER.asm</Filename>
<ExecCommand></ExecCommand>
<Expression></Expression>
</Bp>
</Breakpoint>
<MemoryWindow1>
<Mm>
<WinNumber>1</WinNumber>
<SubType>0</SubType>
<ItemText>0x000000A</ItemText>
</Mm>
</MemoryWindow1>
<DebugFlag>
<trace>0</trace>
<periodic>1</periodic>
<aLwin>1</aLwin>
<aCover>0</aCover>
<aSer1>0</aSer1>
<aSer2>0</aSer2>
<aPa>0</aPa>
<viewmode>1</viewmode>
<vrSel>0</vrSel>
<aSym>0</aSym>
<aTbox>0</aTbox>
<AscS1>0</AscS1>
<AscS2>0</AscS2>
<AscS3>0</AscS3>
<aSer3>0</aSer3>
<eProf>0</eProf>
<aLa>0</aLa>
<aPa1>0</aPa1>
<AscS4>0</AscS4>
<aSer4>0</aSer4>
<StkLoc>0</StkLoc>
<TrcWin>0</TrcWin>
<newCpu>0</newCpu>
<uProt>0</uProt>
</DebugFlag>
<Tracepoint>
<THDelay>0</THDelay>
</Tracepoint>
<LintExecutable></LintExecutable>
<LintConfigFile></LintConfigFile>
</TargetOption>
</Target>
<Group>
<GroupName>Source Group 1</GroupName>
<tvExp>1</tvExp>
<tvExpOptDlg>0</tvExpOptDlg>
<cbSel>0</cbSel>
<RteFlg>0</RteFlg>
<File>
<GroupNumber>1</GroupNumber>
<FileNumber>1</FileNumber>
<FileType>2</FileType>
<tvExp>0</tvExp>
<Focus>0</Focus>
<ColumnNumber>25</ColumnNumber>
<tvExpOptDlg>0</tvExpOptDlg>
<TopLine>1</TopLine>
<CurrentLine>5</CurrentLine>
<bDave2>0</bDave2>
<PathWithFileName>.\DATATRANSFER.asm</PathWithFileName>
<FilenameWithoutPath>DATATRANSFER.asm</FilenameWithoutPath>
<RteFlg>0</RteFlg>
<bShared>0</bShared>
</File>
</Group>
</ProjectOpt>

Binary file not shown.

View file

@ -1,25 +0,0 @@
AREA RESET,DATA,READONLY
EXPORT __Vectors
__Vectors
DCD 0x10001000
DCD Reset_Handler
ALIGN
AREA mycode,CODE,READONLY
ENTRY
EXPORT Reset_Handler
Reset_Handler
LDR R0, =SRC ; gives memory address of SRC array
LDR R1, [R0] ; writes from first location of SRC array
MOV R5, -8;
STOP
B STOP
ALIGN;
SRC DCD 0x12345678, 0xABCDEF55, 0x55
END ;

View file

@ -1 +0,0 @@
LDR and SRC array

View file

@ -1,26 +0,0 @@
AREA RESET, DATA, READONLY
EXPORT __Vectors
__Vectors
DCD 0x10001000
DCD Reset_Handler
ALIGN
AREA mycode,CODE,READONLY
ENTRY
EXPORT Reset_Handler
Reset_Handler
LDR R0, =SRC
LDR R1, =DST
MOV R2,#10
BACK
LDR R3,[R0],#4;
STR R3,[R1],#04;
SUBS R2,#1
BNE BACK
STOP
B STOP
ALIGN
SRC DCD 0x00000032, 0x12345644, 0x00000005, 0x00000098, 0x000000AB, 0x000000CD, 0x00000055, 0x00000032, 0x000000CA, 0x00000045
AREA mydate, DATA, READWRITE
DST DCD 0
END

View file

@ -1,27 +0,0 @@
AREA RESET, DATA, READONLY
EXPORT __Vectors
__Vectors
DCD 0x10001000
DCD Reset_Handler
ALIGN
AREA mycode,CODE,READONLY
ENTRY
EXPORT Reset_Handler
Reset_Handler
LDR R0, =SRC
LDR R1, =DST
MOV R12, #10
Loop
LDR R2, [R0], #4
STR R2, [R1], #4
SUBS R12, R12, #1
BNE Loop
STOP
B STOP
ALIGN
SRC DCD 0x00000032, 0x12345644, 0x00000005, 0x00000098, 0x000000AB, 0x000000CD, 0x00000055, 0x00000032, 0x000000CA, 0x00000045
AREA mydate, DATA, READWRITE
DST DCD 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
END

View file

@ -1,40 +0,0 @@
AREA RESET, DATA, READONLY
EXPORT __Vectors
__Vectors
DCD 0x10001000
DCD Reset_Handler
ALIGN
AREA mycode,CODE,READONLY
ENTRY
EXPORT Reset_Handler
Reset_Handler
LDR R0, =SRC
LDR R1, =DST
LDR R2,[R0]
STR R2,[R1]
LDR R3,[R0,#4]!
STR R3,[R1,#4]!
LDR R4,[R0,#4]!
STR R4,[R1,#4]!
LDR R5,[R0,#4]!
STR R5,[R1,#4]!
LDR R6,[R0,#4]
STR R6,[R1,#4]
LDR R7,[R0,#4]
STR R7,[R1,#4]
LDR R8,[R0,#4]
STR R8,[R1,#4]
LDR R9,[R0],#4
STR R9,[R1],#4
LDR R10,[R0],#4
STR R10,[R1],#4
LDR R11,[R0],#4
STR R11,[R1],#4
STOP
B STOP
ALIGN
SRC DCD 0x00000032, 0x12345644, 0x00000005, 0x00000098, 0x000000AB, 0x000000CD, 0x00000055, 0x00000032, 0x000000CA, 0x00000045
AREA mydate, DATA, READWRITE
DST DCD 0
END

View file

@ -1,40 +0,0 @@
AREA RESET, DATA, READONLY
EXPORT __Vectors
__Vectors
DCD 0x10001000
DCD Reset_Handler
ALIGN
AREA mycode,CODE,READONLY
ENTRY
EXPORT Reset_Handler
Reset_Handler
LDR R0, =SRC
LDR R1, =DST
LDR R2, [R0]
STR R2, [R1]
LDR R3, [R0,#4]!
STR R3, [R1,#4]!
LDR R4, [R0,#4]!
STR R4, [R1,#4]!
LDR R5, [R0,#4]!
STR R5, [R1,#4]!
LDR R6, [R0,#4]!
STR R6, [R1,#4]!
LDR R7, [R0,#4]!
STR R7, [R1,#4]!
LDR R8, [R0,#4]!
STR R8, [R1,#4]!
LDR R9, [R0,#4]!
STR R9, [R1,#4]!
LDR R10, [R0,#4]!
STR R10, [R1,#4]!
LDR R11, [R0,#4]!
STR R11, [R1,#4]!
STOP
B STOP
ALIGN
SRC DCD 0x00000032, 0x12345644, 0x00000005, 0x00000098, 0x000000AB, 0x000000CD, 0x00000055, 0x00000032, 0x000000CA, 0x00000045
AREA mydate, DATA, READWRITE
DST DCD 0
END

Binary file not shown.

View file

@ -1,54 +0,0 @@
# Tool Exploration for Information Security
MS Teams Access Code: `hrtvl3x`
## [Kali Linux](https://www.kali.org/)
Kali Linux is a Debian based operating system maintained by the core Debian team to be used for cybersecurity applications specifically. While general OS installations limit certain hardware/software configurations for certain vectors of usage to prevent exploitation, Kali does no such thing - enabling the user to perform various kinds of operations with modularity. Kali is bundled with various readymade tools that allow automation of penetration testing in various stages. It is therefore used by penetration testing teams (both ethical and unethical) to carry out tests/exploits.
## [Owasp-Zap](https://www.zaproxy.org/)
Made by the Open Wroldwide Security Application Project (OWASP), Zed Attack Proxy (ZAP) is a web application vulnerability scanner designed for both automated and manual use. It acts a proxy server and inspects web traffic - analyzing network requests and related data for vulnerability exposure. It also has code review built in to assist fixing any possible issues before a piece of software is pushed into production.
## [Metasploit](https://www.metasploit.com/)
Designed to be a portable network tool in HD Moore in 2003, Metasploit has grown out to be an entire open source penetration testing framework, alongside its derivative sub projects like the OpCode Database, Shellcode Archive etc. Metasploit has, by itself, grown to be a collective of various tools throughout the decades, including coverage for most major publicly known exploits/CVEs used in the field - including those that were leaked from the NSA/TAO hacks in the late 2010s. It is a go to toolkit for penetration testers to approach security issues in any testing scenario.
## [Burpsuite](https://portswigger.net/burp)
BurpSuite is a tool focused at web exploitation, used by researchers reverse engineering products for APIs. It features detection and exploitation capabilities for vulnerabilities such as Cross Site Scripting (XSS), SQL Injection, Cross Site Request Forgery (CSRF), XML External Entity Injection, Server Side Request Forgery (SSRF) and more. It is used to exploit and map APIs from various applications as well, and can be then used to map them and perform any of the above mentioned exploits.
## [Ettercap](https://www.ettercap-project.org/)
Ettercap is a Man in the Middle (MITM) tool used by security researchers to ensure end to end security of data/action pipelines. It allows users to perform the following tests
- Host Lists through ARP requests sent to any subnet mask as specified by the user.
- Unified Sniffing: Kernel IP forwarding is disabled, user sends a request with a specific MAC address that is same as the attacker's one but with different IPs, so the packet is then return to the attacker instead.
- Bridged Sniffing
- ARP Poisoning
- ICMP redirection (Half Duplex MITM)
- DHCP Spoofing
- Port Stealing
- Character Injection
et cetera
## [Hydra](https://www.kali.org/tools/hydra/)
Hydra is a network login hacking tool built into Kali Linux used to gain unauthorized access to a remote system over various protocols and suites of tools, enabling an analyst to possibly establish/take down proxies, gain RCE, modify system resources (or their allocation and therefore cost). It supports SSL-based platforms as well and is easy to build extensions for to add support for a newer communication protocol.
## [Mosquitto](https://mosquitto.org/)
Mosquitto is an OSS MQTT broker designed for messaging/message passing applications, including message stores (to facilitate later delivery to a dormant user). It uses a PubSub model over TCP (which is a byeffect of its roots in MQTT) based on topics each client is subscribed to via JSON/XML. Mosquitto scanners are used to identify MQTT brokers during a communication stream and mapping them to engineer exploits accordingly.
## [nmap](https://nmap.org/)
NMap (Network Mapper) is a network discovery tool used in security auditing. NMap uses raw IP packets in various ways to map available hosts, services, versions, OSes, firewalls and can do so with scale and for large networks.
## [netcat](http://nmap.org/ncat/)
Netcat is used to read and write data across TCP/UDP connections via stdio and is a reliable backend tool to drive programs or scripts that require text passing usage. Ncat, its successor developed by the NMap team adds support for SSL, SOCK4/5 proxies, IPv6 support and other extended functionality. Due to its low level nature, it is easy to obscure and mask with ease.
## [sqlmap](https://sqlmap.org/)
sqlmap is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers. It supports mosgt major database and database paradigms such as MySQL, PostgreSQL, Microsoft Access etc. It fully supports the following SQL injection techniques: boolean-based blind, time-based blind, error-based, UNION query-based, stacked queries and out-of-band. It can connect via DBMS credentials if required, includes functionality to enumerate users, password hasehs, priveleges, roles, tables, columns etc.
## [sqlninja](https://www.kali.org/tools/sqlninja/)
SQLninja is a SQL server injection and takeover tool targeted to exploit SQL Injection vulnerabilities on a web application that uses Microsoft SQL Server as its back-end. Its main goal is to provide a remote access on the vulnerable DB server, even in a very hostile environment. It supports DB fingerprinting, dagta extraction, Metasploit integration to obtain a graphical access to the remote DB server through a VNC server injection or just to upload Meterpreter, obtain a DNS based or ICMP tunneled shell and bruteforcing of sa passwords too.
## [msfvenom](https://www.rapid7.com/blog/post/2011/05/24/introducing-msfvenom/)
MSFVenom is a fork off the Metasploit Framework merging both `msfpayload` and `msfencode` into one unified tool and framework instance, with a wider variety of I/O file formats and with refined payload generation.
## [Microsoft Threat Modelling Tool](https://learn.microsoft.com/en-us/azure/security/develop/threat-modeling-tool)
The Microsoft Threat Modeling Tool used as a part of the SDL allowing software architects to identify and mitigate any risks as they happen. It follows the STRIDE methodology: STRIDE stands for Spoofing, Tampering, Repudiation, Information disclosure, Denial of service and Elevation of privilege. A user designs their architecutre in STRIDE and marks the boundaries accordingly, and STRIDE gives us a list of all possible threat scenarios that the system could be exposed to by crossreferencing then Microsoft Security Database.
## [PyCharm](https://www.jetbrains.com/pycharm/)
PyCharm is the Jetbrains IDE for Python built for use in complex corporate workflows, with an entire extensive plugin ecosystem around it. It inlcudes PEP8 compliance checks, linters, treesitters etc to make development faster and more secure.

View file

@ -1,127 +0,0 @@
## ptext = plaintext
## ak = additive key
from collections import defaultdict
def add_cipher_en(ptext, ak):
result = ""
for i in range(len(ptext)):
ch = ptext[i]
if 32 <= ord(ch) <= 47:
result += ch
elif 90 >= ord(ch) >= 65:
result += chr((ord(ch) + ak - 65) % 26 + 65)
else:
result += chr((ord(ch) + ak - 97) % 26 + 97)
return result
def add_cipher_de(ctext, ak):
result = ""
for i in range(len(ctext)):
ch = ctext[i]
if 32 <= ord(ch) <= 47:
result += ch
elif 90 >= ord(ch) >= 65:
result += chr((ord(ch) - ak - 65) % 26 + 65)
else:
result += chr((ord(ch) - ak - 97) % 26 + 97)
return result
def mult_cipher_en(ptext, mk):
result = ""
for i in range(len(ptext)):
ch = ptext[i]
if 32 <= ord(ch) <= 47:
result += ch
elif 90 >= ord(ch) >= 65:
result += chr((ord(ch) * mk - 65) % 26 + 65)
else:
result += chr((ord(ch) * mk - 97) % 26 + 97)
return result
def mult_cipher_de(ctext, mk):
result = ""
inverse = pow(mk, -1, 26)
for i in range(len(ctext)):
ch = ctext[i]
if 32 <= ord(ch) <= 47:
result += ch
elif 90 >= ord(ch) >= 65:
result += chr((ord(ch) * inverse - 65) % 26 + 65)
else:
result += chr((ord(ch) * inverse - 97) % 26 + 97)
return result
def affine_en(ptext, ak, mk):
result = ""
for i in range(len(ptext)):
ch = ptext[i]
if 32 <= ord(ch) <= 47:
result += ch
elif 90 >= ord(ch) >= 65:
result += chr((((ord(ch) - 65) * mk) + ak) % 26 + 65)
else:
result += chr((((ord(ch) - 97) * mk) + ak) % 26 + 97)
return result
def affine_de(ctext, ak, mk):
result = ""
inverse = pow(mk, -1, 26)
for i in range(len(ctext)):
ch = ctext[i]
if 32 <= ord(ch) <= 47:
result += ch
elif 90 >= ord(ch) >= 65:
result += chr((((ord(ch) - 65 - ak) * inverse) % 26) + 65)
else:
result += chr((((ord(ch) - 97 - ak) * inverse) % 26) + 97)
return result
def operator(argument,ptext,ak,mk):
match argument:
case '1':
print("Additive Cipher")
print("Plaintext: ", ptext)
print("Additive Key: ", ak)
ctext = add_cipher_en(ptext, ak)
print("Ciphertext: ", ctext)
print("Decrypted Text: ", add_cipher_de(ctext, ak))
case '2':
print("Multiplicative Cipher")
print("Plaintext: ", ptext)
print("Multiplicative Key: ", mk)
ctext = mult_cipher_en(ptext, mk)
print("Ciphertext: ", ctext)
print("Decrypted Text: ", mult_cipher_de(ctext, mk))
case '3':
print("Affine Cipher")
print("Plaintext: ", ptext)
print("Additive Key: ", ak)
print("Multiplicative Key: ", mk)
ctext = affine_en(ptext, ak, mk)
print("Ciphertext: ", ctext)
print("Decrypted Text: ", affine_de(ctext, ak, mk))
case '4':
print("Goodbye")
exit()
case _:
print("Invalid Choice, please try again.")
def main():
ptext = input("Kindly enter your desired plaintext: ")
ak = 20
mk = 15
print("Welcome to the substitution cipher system.")
print("Enter your choice of algorithm")
print("1. Additive Cipher")
print("2. Multiplicative Cipher")
print("3. Affine Cipher")
print("4. Exit")
while True:
op = input("Enter your choice of operation: ")
operator(op, ptext, ak, mk)
if __name__ == '__main__':
main()

View file

@ -1,118 +0,0 @@
def vigenere_en(ptext, vk):
result = ""
ptext = ptext.upper()
vk = vk.upper()
kl = len(vk) ## key length
for i in range(len(ptext)):
ch = ptext[i]
if 32 <= ord(ch) <= 47:
result += ch
elif 65 <= ord(ch) <= 90:
shift = (ord(vk[i % kl]) - ord('A')) % 26
result += chr((ord(ch) - ord('A') + shift) % 26 + ord('A'))
else:
result += ch
return result
def vigenere_de(ctext, vk):
result = ""
ctext = ctext.upper()
vk = vk.upper()
kl = len(vk)
for i in range(len(ctext)):
ch = ctext[i]
if 32 <= ord(ch) <= 47:
result += ch
elif 65 <= ord(ch) <= 90:
shift = (ord(vk[i % kl]) - ord('A')) % 26
result += chr((ord(ch) - ord('A') - shift + 26) % 26 + ord('A'))
else:
result += ch
return result
def autokey_en(ptext, ak):
result = ""
ptext = ptext.upper()
current_key = ak
for i in range(len(ptext)):
ch = ptext[i]
if 32 <= ord(ch) <= 47:
result += ch
elif 65 <= ord(ch) <= 90:
shift = (current_key - ord('A')) % 26
cipher_char = chr((ord(ch) - ord('A') + shift) % 26 + ord('A'))
result += cipher_char
current_key = ord(cipher_char)
else:
result += ch
return result
def autokey_de(ctext, ak):
result = ""
ctext = ctext.upper()
current_key = ak
for i in range(len(ctext)):
ch = ctext[i]
if 32 <= ord(ch) <= 47:
result += ch
elif 65 <= ord(ch) <= 90:
shift = (current_key - ord('A')) % 26
plain_char = chr((ord(ch) - ord('A') - shift + 26) % 26 + ord('A'))
result += plain_char
current_key = ord(plain_char)
else:
result += ch
return result
def operator(argument,ptext,ak,vk):
match argument:
case '1':
print("Vigenere Cipher")
print("Plaintext: ", ptext)
print("Vigenere Key: ", vk)
ctext = vigenere_en(ptext, vk)
print("Ciphertext: ", ctext)
print("Decrypted Text: ", vigenere_de(ctext, vk))
case '2':
print("Autokey Cipher")
print("Plaintext: ", ptext)
print("Auto Key: ", ak)
ctext = autokey_en(ptext, ak)
print("Ciphertext: ", ctext)
print("Decrypted Text: ", autokey_de(ctext, ak))
case '3':
print("Goodbye")
exit()
case _:
print("Invalid Choice, please try again.")
def main():
ptext = input("Kindly enter your desired plaintext: ")
vk = input("Kindly enter the Vigenere Key: ")
ak = int(input("Kindly enter the Autokey: "))
print("Welcome to the Autokey cipher system.")
print("Enter your choice of algorithm")
print("1. Vigenere Cipher")
print("2. Autokey Cipher")
print("3. Exit")
while True:
op = input("Enter your choice of operation: ")
operator(op, ptext, ak, vk)
if __name__ == '__main__':
main()

View file

@ -1,87 +0,0 @@
def generate_playfair_matrix(key):
key = ''.join(sorted(set(key.upper()), key=key.upper().index))
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
matrix = []
for char in key:
if char not in matrix and char != 'J':
matrix.append(char)
for char in alphabet:
if char not in matrix and char != 'J':
matrix.append(char)
playfair_matrix = [matrix[i:i+5] for i in range(0, len(matrix), 5)]
return playfair_matrix
def find_pos(matrix, char):
for row_idx, row in enumerate(matrix):
if char in row:
col_idx = row.index(char)
return row_idx, col_idx
return None
def prepare_text(text):
text = ''.join(filter(str.isalpha, text.upper()))
text = text.replace('J', 'I')
pairs = []
i = 0
while i < len(text):
if i + 1 < len(text) and text[i] != text[i+1]:
pairs.append(text[i:i+2])
i += 2
else:
pairs.append(text[i]+'X')
i += 1
return pairs
def playfair_en(ptext, pfk):
matrix = generate_playfair_matrix(pfk)
ptext_pairs = prepare_text(ptext)
ctext = []
for pair in ptext_pairs:
r1, c1 = find_pos(matrix, pair[0])
r2, c2 = find_pos(matrix, pair[1])
if r1 == r2:
ctext.append(matrix[r1][(c1 + 1) % 5] + matrix[r2][(c2 + 1) % 5])
elif c1 == c2:
ctext.append(matrix[(r1 + 1) % 5][c1] + matrix[(r2 + 1) % 5][c2])
else:
ctext.append(matrix[r1][c2] + matrix[r2][c1])
return ''.join(ctext)
def playfair_de(ctext, pfk):
matrix = generate_playfair_matrix(pfk)
ctext_pairs = prepare_text(ctext)
ptext = []
for pair in ctext_pairs:
r1, c1 = find_pos(matrix, pair[0])
r2, c2 = find_pos(matrix, pair[1])
if r1 == r2:
ptext.append(matrix[r1][(c1 - 1) % 5] + matrix[r2][(c2 - 1) % 5])
elif c1 == c2:
ptext.append(matrix[(r1 - 1) % 5][c1] + matrix[(r2 - 1) % 5][c2])
else:
ptext.append(matrix[r1][c2] + matrix[r2][c1])
return ''.join(ptext)
def main():
ptext = input("Kindly enter your desired plaintext: ")
pfk = input("Kindly enter the Playfair Key: ")
print("Welcome to the Playfair cipher system.")
print("Plaintext: ", ptext)
print("Playfair Key: ", pfk)
ctext = playfair_en(ptext, pfk)
print("Ciphertext: ", ctext)
decrypted_text = playfair_de(ctext, pfk)
print("Decrypted Text: ", decrypted_text)
if __name__ == '__main__':
main()

View file

@ -1,18 +0,0 @@
def hill_en(ptext,hk):
def hill_de(ptext,hk):
def main():
ptext = input("Kindly enter your desired plaintext: ")
hk = input("Kindly enter the Hill Key: ")
print("Welcome to the Hill cipher.")
print("Plaintext: ", ptext)
print("Hill Key: ", hk)
ctext = hill_en(ptext, hk)
print("Ciphertext: ", ctext)
decrypted_text = hill_de(ctext, hk)
print("Decrypted Text: ", decrypted_text)
if __name__ == '__main__':
main()

View file

View file

@ -1,7 +0,0 @@
2025-08-12 - Synopsis Submission
2025-09-02 - Program Check [7M] / Record Submission [7M] (Upto Lab 4)
2025-09-23 - Lab Midsem [20M] (Upto Lab 6)
2025-10-14 - Project Progress Check [10]/ Second Record Submission [7M] (Upto Lab 8)
2025-10-28 - Lab Endsem
2025-10-2X - Lab Quiz [9] (Date yet to be finalised)
2025-11-11 - Project Submission

Binary file not shown.

View file

@ -1,50 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
// Page Replacement: FIFO & Optimal (Minimal Code for Paper)
int main() {
int nf, np, i, j, k, pf, hit, idx, max_f, vic; // nf=frames, np=pages, pf=faults, idx=fifo_idx, max_f=max_future, vic=victim
int *rs, *f; // rs=ref_string, f=frames
printf("F N:"); scanf("%d%d", &nf, &np); // Frames, NumPages
rs = malloc(np * sizeof(int));
f = malloc(nf * sizeof(int));
if(!rs || !f) return 1; // Basic alloc check
printf("RS:"); for(i=0; i<np; i++) scanf("%d", &rs[i]); // Ref String
// FIFO
puts("FIFO"); pf=0; idx=0;
for(k=0; k<nf; k++) f[k]=-1; // Init frames
for(i=0; i<np; i++){ // Iterate ref string
hit=0; for(k=0; k<nf; k++) if(f[k]==rs[i]) {hit=1; break;} // Check hit
if(!hit){ // Page Fault
pf++; f[idx]=rs[i]; idx=(idx+1)%nf; // Replace using FIFO index
}
}
printf("F:%d\n", pf); // Print Faults
// Optimal
puts("OPT"); pf=0;
for(k=0; k<nf; k++) f[k]=-1; // Re-init frames
for(i=0; i<np; i++){ // Iterate ref string
hit=0; for(k=0; k<nf; k++) if(f[k]==rs[i]) {hit=1; break;} // Check hit
if(!hit){ // Page Fault
pf++; int empty=-1; for(k=0; k<nf; k++) if(f[k]==-1) {empty=k; break;} // Find empty frame
if(empty!=-1) f[empty]=rs[i]; // Use empty frame if available
else { // No empty frames, find victim
vic=0; max_f=-1; // Victim index, max future distance
for(k=0; k<nf; k++){ // Check each current frame 'f[k]'
int fut=-1; // Index of next use for f[k]
for(j=i+1; j<np; j++) if(f[k]==rs[j]) {fut=j; break;} // Look ahead
if(fut==-1) {vic=k; break;} // f[k] not used again? Best victim. Stop search.
if(fut>max_f) {max_f=fut; vic=k;} // f[k] used later than current max? Update victim.
}
f[vic]=rs[i]; // Replace victim frame
}
}
}
printf("F:%d\n", pf); // Print Faults
free(rs); free(f); // Free memory
return 0;
}

Binary file not shown.

View file

@ -1,78 +0,0 @@
#include <stdio.h>
#include <stdlib.h> // For malloc, free
// C program for LRU Page Replacement Simulation
// Optimized for minimal code size (e.g., for writing on paper)
int main() {
int nf, np, i, j, pg, idx, lru, pf = 0, time = 0, min_t;
// nf=num frames, np=num pages, pf=page faults, time=logical clock
// idx=found index, lru=least recently used index, pg=current page
// Input frame count (nf) and page reference string length (np)
printf("Frames Pages:"); scanf("%d%d", &nf, &np);
// Dynamic Allocation
int *f = malloc(nf * sizeof(int)); // f: frames array
int *c = malloc(nf * sizeof(int)); // c: counter/lru time array
int *p = malloc(np * sizeof(int)); // p: page reference string array
// Input page reference string
printf("Pages:");
for(i=0; i<np; ) scanf("%d", p+i++); // Read pages into p
// Initialize frames to -1 (empty)
for(i=0; i<nf; i++) f[i]=-1; // Can also use for(i=nf;i--;)f[i]=-1;
// --- LRU Algorithm ---
for(i=0; i<np; i++) { // Iterate through page reference string
pg = p[i]; // Current page
idx = -1; // Reset found index
// 1. Search if page 'pg' is already in frames 'f'
for(j=0; j<nf; j++) {
if(f[j] == pg) {
idx = j; // Page found at index j
break;
}
}
if(idx != -1) { // 2a. Page Hit
c[idx] = ++time; // Update last used time for the hit page
} else { // 2b. Page Fault
pf++; // Increment page fault counter
lru = 0; // Index to replace (default to 0)
min_t = 0x7FFFFFFF; // Initialize minimum time to max int
// 3. Find replacement slot: first empty (-1) or LRU
for(j=0; j<nf; j++) {
if(f[j] == -1) { // Found an empty frame
lru = j;
break; // Use the first empty frame
}
if(c[j] < min_t) { // Track frame with the smallest time (LRU)
min_t = c[j];
lru = j;
}
}
// 'lru' now holds index of empty slot or the least recently used page
// 4. Replace frame and update its time
f[lru] = pg;
c[lru] = ++time;
}
// Optional: print frame state after each step (for debugging)
// printf(" (%d):",pg); for(j=0; j<nf; j++)printf(" %d", f[j]==-1?-1:f[j]); puts("");
}
// --- End Algorithm ---
// Output total page faults
printf("Faults: %d\n", pf);
// Free dynamically allocated memory
free(f);
free(c);
free(p);
return 0; // End of program
}

View file

@ -1,198 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <limits.h> // For INT_MAX in optimal
// Function to check if a page is present in frames
int isPresent(int page, int *frames, int num_frames) {
for (int i = 0; i < num_frames; i++) {
if (frames[i] == page) {
return 1; // Present
}
}
return 0; // Not present
}
// Function to print the current state of frames (for debugging/visualization)
void printFrames(int *frames, int num_frames) {
printf("Frames: ");
for (int i = 0; i < num_frames; i++) {
if (frames[i] == -1) {
printf("[ ] ");
} else {
printf("[%d] ", frames[i]);
}
}
printf("\n");
}
// FIFO Page Replacement Simulation
int simulateFIFO(int *ref_string, int num_refs, int num_frames) {
int *frames = (int *)malloc(num_frames * sizeof(int));
if (frames == NULL) {
perror("Failed to allocate memory for frames");
exit(EXIT_FAILURE);
}
for (int i = 0; i < num_frames; i++) {
frames[i] = -1; // Initialize frames as empty (-1 indicates empty)
}
int page_faults = 0;
int frame_index = 0; // Points to the next frame to be replaced (FIFO queue head)
printf("\n--- FIFO Simulation ---\n");
for (int i = 0; i < num_refs; i++) {
int current_page = ref_string[i];
printf("Ref: %d -> ", current_page);
if (!isPresent(current_page, frames, num_frames)) {
page_faults++;
frames[frame_index] = current_page;
frame_index = (frame_index + 1) % num_frames; // Move to next frame in circular fashion
printf("Fault! ");
printFrames(frames, num_frames);
} else {
printf("Hit. ");
printFrames(frames, num_frames);
}
}
free(frames);
return page_faults;
}
// Function to find the optimal page to replace
int findOptimalVictim(int *frames, int num_frames, int *ref_string, int num_refs, int current_index) {
int victim_frame = -1;
int farthest_use = -1; // Index of the farthest future use
for (int i = 0; i < num_frames; i++) {
int page_in_frame = frames[i];
int next_use = INT_MAX; // Assume page is never used again initially
// Look for the next occurrence of this page in the reference string
for (int j = current_index + 1; j < num_refs; j++) {
if (ref_string[j] == page_in_frame) {
next_use = j;
break; // Found the *next* use
}
}
// If this page is never used again, it's the best victim
if (next_use == INT_MAX) {
return i; // Return the index of the frame holding this page
}
// Otherwise, track the page whose next use is farthest away
if (next_use > farthest_use) {
farthest_use = next_use;
victim_frame = i; // This frame holds the current best candidate for victim
}
}
// Should always find a victim if frames are full, defaults to first if logic error/all used soon
return (victim_frame == -1) ? 0 : victim_frame;
}
// Optimal Page Replacement Simulation
int simulateOptimal(int *ref_string, int num_refs, int num_frames) {
int *frames = (int *)malloc(num_frames * sizeof(int));
if (frames == NULL) {
perror("Failed to allocate memory for frames");
exit(EXIT_FAILURE);
}
for (int i = 0; i < num_frames; i++) {
frames[i] = -1; // Initialize frames as empty
}
int page_faults = 0;
int current_frame_count = 0;
printf("\n--- Optimal Simulation ---\n");
for (int i = 0; i < num_refs; i++) {
int current_page = ref_string[i];
printf("Ref: %d -> ", current_page);
if (!isPresent(current_page, frames, num_frames)) {
page_faults++;
printf("Fault! ");
// Check if there are empty frames first
if (current_frame_count < num_frames) {
frames[current_frame_count] = current_page;
current_frame_count++;
} else {
// Frames are full, need to find the optimal victim
int victim_index = findOptimalVictim(frames, num_frames, ref_string, num_refs, i);
frames[victim_index] = current_page; // Replace victim
}
printFrames(frames, num_frames);
} else {
printf("Hit. ");
printFrames(frames, num_frames);
}
}
free(frames);
return page_faults;
}
int main() {
int num_frames;
int num_refs;
int *ref_string;
// Get number of frames
printf("Enter the number of page frames: ");
scanf("%d", &num_frames);
if (num_frames <= 0) {
printf("Number of frames must be positive.\n");
return 1;
}
// Get number of page references
printf("Enter the number of page references in the sequence: ");
scanf("%d", &num_refs);
if (num_refs <= 0) {
printf("Number of references must be positive.\n");
return 1;
}
// Allocate memory for reference string
ref_string = (int *)malloc(num_refs * sizeof(int));
if (ref_string == NULL) {
perror("Failed to allocate memory for reference string");
return 1;
}
// Get the reference string
printf("Enter the page reference sequence (e.g., 7 0 1 2 0 ...):\n");
for (int i = 0; i < num_refs; i++) {
if (scanf("%d", &ref_string[i]) != 1) {
printf("Invalid input for reference sequence.\n");
free(ref_string);
return 1;
}
if (ref_string[i] < 0) {
printf("Page numbers cannot be negative.\n");
free(ref_string);
return 1;
}
}
// --- Run Simulations ---
int fifo_faults = simulateFIFO(ref_string, num_refs, num_frames);
int optimal_faults = simulateOptimal(ref_string, num_refs, num_frames);
// --- Print Results ---
printf("\n--- Results ---\n");
printf("Reference String Length: %d\n", num_refs);
printf("Number of Frames: %d\n", num_frames);
printf("FIFO Page Faults: %d\n", fifo_faults);
printf("Optimal Page Faults: %d\n", optimal_faults);
// --- Cleanup ---
free(ref_string);
return 0;
}

View file

@ -1,169 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <limits.h> // For INT_MAX
// Structure to represent a frame and its last used time
typedef struct {
int page_number;
int last_used_time;
} Frame;
// Function to find if a page exists in frames and return its index
// Also updates the last_used_time if found
int find_page(Frame frames[], int n_frames, int page, int current_time) {
for (int i = 0; i < n_frames; i++) {
if (frames[i].page_number == page) {
frames[i].last_used_time = current_time; // Update time on hit
return i; // Page found (Hit)
}
}
return -1; // Page not found (Fault)
}
// Function to find the index of the Least Recently Used (LRU) page
int find_lru_index(Frame frames[], int n_frames) {
int min_time = INT_MAX;
int lru_index = 0;
for (int i = 0; i < n_frames; i++) {
// Frame must contain a valid page (not -1)
if (frames[i].page_number != -1 && frames[i].last_used_time < min_time) {
min_time = frames[i].last_used_time;
lru_index = i;
}
}
return lru_index;
}
// Function to print the current state of frames
void print_frames(Frame frames[], int n_frames) {
printf("[");
for (int i = 0; i < n_frames; i++) {
if (frames[i].page_number == -1) {
printf(" - ");
} else {
printf(" %d ", frames[i].page_number);
}
}
printf("]\n");
}
int main() {
int n_frames, n_pages;
int *pages = NULL; // Reference string
Frame *frames = NULL; // Frames in memory
int page_faults = 0;
int page_hits = 0;
int current_time = 0; // Counter to track usage time
int frame_idx = 0; // Index for filling empty frames initially
// 1. Get Inputs
printf("Enter the number of frames: ");
if (scanf("%d", &n_frames) != 1 || n_frames <= 0) {
fprintf(stderr, "Error: Invalid number of frames.\n");
return 1;
}
printf("Enter the number of pages in the reference string: ");
if (scanf("%d", &n_pages) != 1 || n_pages <= 0) {
fprintf(stderr, "Error: Invalid number of pages.\n");
return 1;
}
// 2. Allocate Memory
pages = (int *)malloc(n_pages * sizeof(int));
if (pages == NULL) {
perror("Failed to allocate memory for pages");
return 1;
}
frames = (Frame *)malloc(n_frames * sizeof(Frame));
if (frames == NULL) {
perror("Failed to allocate memory for frames");
free(pages); // Clean up already allocated memory
return 1;
}
printf("Enter the page reference string (space-separated %d integers):\n", n_pages);
for (int i = 0; i < n_pages; i++) {
if (scanf("%d", &pages[i]) != 1) {
fprintf(stderr, "Error reading page reference string.\n");
free(pages);
free(frames);
return 1;
}
}
// 3. Initialize Frames
for (int i = 0; i < n_frames; i++) {
frames[i].page_number = -1; // -1 indicates empty frame
frames[i].last_used_time = -1; // Initialize time
}
printf("\n--- LRU Simulation Start ---\n");
printf("Frames: %d | Reference String Length: %d\n\n", n_frames, n_pages);
// 4. Process Page References
for (int i = 0; i < n_pages; i++) {
current_time++; // Increment time step for each reference
int current_page = pages[i];
printf("Ref: %d -> ", current_page);
int found_index = find_page(frames, n_frames, current_page, current_time);
if (found_index != -1) {
// Page Hit
page_hits++;
printf("Hit ");
} else {
// Page Fault
page_faults++;
printf("Fault ");
// Find a place for the new page
int replace_index = -1;
// Check for an empty frame first
for(int k=0; k < n_frames; k++){
if(frames[k].page_number == -1){
replace_index = k;
break;
}
}
if (replace_index != -1) {
// Use the empty frame
frames[replace_index].page_number = current_page;
frames[replace_index].last_used_time = current_time;
printf("(loaded into empty frame %d) ", replace_index);
} else {
// No empty frames, find LRU page to replace
replace_index = find_lru_index(frames, n_frames);
printf("(replaced P%d in frame %d) ", frames[replace_index].page_number, replace_index);
frames[replace_index].page_number = current_page;
frames[replace_index].last_used_time = current_time;
}
}
print_frames(frames, n_frames); // Show frame status after each step
}
// 5. Output Results
printf("\n--- LRU Simulation End ---\n");
printf("Total Page References: %d\n", n_pages);
printf("Total Page Hits: %d\n", page_hits);
printf("Total Page Faults: %d\n", page_faults);
if (n_pages > 0) {
printf("Hit Rate: %.2f%%\n", (double)page_hits / n_pages * 100.0);
printf("Fault Rate: %.2f%%\n", (double)page_faults / n_pages * 100.0);
} else {
printf("Hit Rate: N/A\n");
printf("Fault Rate: N/A\n");
}
// 6. Free Memory
free(pages);
free(frames);
return 0;
}

View file

@ -1,176 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// Function to check if a page exists in frames
bool isPagePresent(int* frames, int num_frames, int page) {
for (int i = 0; i < num_frames; i++) {
if (frames[i] == page) {
return true;
}
}
return false;
}
// FIFO Page Replacement Algorithm
void fifo(int* reference_string, int num_pages, int num_frames) {
int* frames = (int*)malloc(num_frames * sizeof(int));
int page_faults = 0;
int frame_index = 0;
// Initialize frames with -1 (indicating empty)
for (int i = 0; i < num_frames; i++) {
frames[i] = -1;
}
printf("\nFIFO Page Replacement Algorithm:\n");
printf("Reference String: ");
for (int i = 0; i < num_pages; i++) {
printf("%d ", reference_string[i]);
}
printf("\n\n");
for (int i = 0; i < num_pages; i++) {
printf("Page %d: ", reference_string[i]);
// Check if page already exists in frames
if (!isPagePresent(frames, num_frames, reference_string[i])) {
// Replace page at current frame_index
frames[frame_index] = reference_string[i];
frame_index = (frame_index + 1) % num_frames;
page_faults++;
printf("Page Fault! Frames: ");
} else {
printf("No Page Fault. Frames: ");
}
// Print current state of frames
for (int j = 0; j < num_frames; j++) {
if (frames[j] == -1) {
printf("[ ] ");
} else {
printf("[%d] ", frames[j]);
}
}
printf("\n");
}
printf("\nTotal Page Faults (FIFO): %d\n", page_faults);
free(frames);
}
// Function to find index of page that will be used farthest in future
int findOptimalPage(int* reference_string, int* frames, int num_frames, int num_pages, int current_position) {
int farthest = -1;
int index = -1;
for (int i = 0; i < num_frames; i++) {
int j;
for (j = current_position + 1; j < num_pages; j++) {
if (frames[i] == reference_string[j]) {
if (j > farthest) {
farthest = j;
index = i;
}
break;
}
}
// If page is never used in future
if (j == num_pages) {
return i;
}
}
// If all pages will be used in future, return the one used farthest
return (index == -1) ? 0 : index;
}
// Optimal Page Replacement Algorithm
void optimal(int* reference_string, int num_pages, int num_frames) {
int* frames = (int*)malloc(num_frames * sizeof(int));
int page_faults = 0;
// Initialize frames with -1 (indicating empty)
for (int i = 0; i < num_frames; i++) {
frames[i] = -1;
}
printf("\nOptimal Page Replacement Algorithm:\n");
printf("Reference String: ");
for (int i = 0; i < num_pages; i++) {
printf("%d ", reference_string[i]);
}
printf("\n\n");
for (int i = 0; i < num_pages; i++) {
printf("Page %d: ", reference_string[i]);
// Check if page already exists in frames
if (!isPagePresent(frames, num_frames, reference_string[i])) {
int free_frame = -1;
// Check if there's an empty frame
for (int j = 0; j < num_frames; j++) {
if (frames[j] == -1) {
free_frame = j;
break;
}
}
if (free_frame != -1) {
// If empty frame exists, use it
frames[free_frame] = reference_string[i];
} else {
// Find optimal page to replace
int replace_index = findOptimalPage(reference_string, frames, num_frames, num_pages, i);
frames[replace_index] = reference_string[i];
}
page_faults++;
printf("Page Fault! Frames: ");
} else {
printf("No Page Fault. Frames: ");
}
// Print current state of frames
for (int j = 0; j < num_frames; j++) {
if (frames[j] == -1) {
printf("[ ] ");
} else {
printf("[%d] ", frames[j]);
}
}
printf("\n");
}
printf("\nTotal Page Faults (Optimal): %d\n", page_faults);
free(frames);
}
int main() {
int num_pages, num_frames;
printf("Enter number of frames: ");
scanf("%d", &num_frames);
printf("Enter number of pages in reference string: ");
scanf("%d", &num_pages);
int* reference_string = (int*)malloc(num_pages * sizeof(int));
printf("Enter the reference string (page numbers):\n");
for (int i = 0; i < num_pages; i++) {
scanf("%d", &reference_string[i]);
}
// Run FIFO algorithm
fifo(reference_string, num_pages, num_frames);
// Run Optimal algorithm
optimal(reference_string, num_pages, num_frames);
free(reference_string);
return 0;
}

View file

@ -1,201 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 100
// Function for SSTF (Shortest Seek Time First)
void sstf(int arr[], int n, int head) {
int visited[MAX] = {0}, total_seek = 0, current = head;
printf("\nSSTF Sequence:\n%d ", current);
for (int count = 0; count < n; count++) {
int index = -1, minDist = 1e9;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
int dist = abs(arr[i] - current);
if (dist < minDist) {
minDist = dist;
index = i;
}
}
}
visited[index] = 1;
total_seek += minDist;
current = arr[index];
printf("-> %d ", current);
}
printf("\nTotal Seek Time: %d\n", total_seek);
}
// Helper function: Bubble sort in ascending order
void sortAsc(int arr[], int n) {
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Helper function: Bubble sort in descending order
void sortDesc(int arr[], int
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)
if (arr[i] < arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Function for SCAN (Elevator Algorithm)
// Assumes movement is towards the left first, then reverses.
void scan(int arr[], int n, int head, int disk_size) {
int left[MAX], right[MAX], l = 0, r = 0;
for (int i = 0; i < n; i++) {
if (arr[i] < head)
left[l++] = arr[i];
else
right[r++] = arr[i];
}
sortDesc(left, l);
sortAsc(right, r);
int total_seek = 0, current = head;
printf("\nSCAN Sequence:\n%d ", current);
// Service left side (moving toward 0)
for (int i = 0; i < l; i++) {
total_seek += abs(current - left[i]);
current = left[i];
printf("-> %d ", current);
}
// If not already at 0, move to 0
if (current != 0) {
total_seek += current;
current = 0;
printf("-> %d ", current);
}
// Then service right side (moving right)
for (int i = 0; i < r; i++) {
total_seek += abs(right[i] - current);
current = right[i];
printf("-> %d ", current);
}
printf("\nTotal Seek Time: %d\n", total_seek);
}
// Function for C-SCAN (Circular SCAN)
// Assumes movement to the right; after reaching the end, the head jumps to 0.
void cscan(int arr[], int n, int head, int disk_size) {
int left[MAX], right[MAX], l = 0, r = 0;
for (int i = 0; i < n; i++) {
if (arr[i] < head)
left[l++] = arr[i];
else
right[r++] = arr[i];
}
sortAsc(left, l);
sortAsc(right, r);
int total_seek = 0, current = head;
printf("\nC-SCAN Sequence:\n%d ", current);
// Service requests to the right
for (int i = 0; i < r; i++) {
total_seek += abs(right[i] - current);
current = right[i];
printf("-> %d ", current);
}
// Go to the end if not reached
if (current != disk_size - 1) {
total_seek += abs(disk_size - 1 - current);
current = disk_size - 1;
printf("-> %d ", current);
}
// Jump to beginning (simulate wrap-around)
total_seek += (disk_size - 1);
current = 0;
printf("-> %d ", current);
// Service the left side
for (int i = 0; i < l; i++) {
total_seek += abs(left[i] - current);
current = left[i];
printf("-> %d ", current);
}
printf("\nTotal Seek Time: %d\n", total_seek);
}
// Function for C-LOOK
// Assumes movement to the right; after the furthest request, it jumps to the smallest request.
void clook(int arr[], int n, int head) {
int left[MAX], right[MAX], l = 0, r = 0;
for (int i = 0; i < n; i++) {
if (arr[i] < head)
left[l++] = arr[i];
else
right[r++] = arr[i];
}
sortAsc(left, l);
sortAsc(right, r);
int total_seek = 0, current = head;
printf("\nC-LOOK Sequence:\n%d ", current);
// Service the right side
for (int i = 0; i < r; i++) {
total_seek += abs(right[i] - current);
current = right[i];
printf("-> %d ", current);
}
// Jump to the leftmost request if any exist on the left
if (l > 0) {
total_seek += abs(current - left[0]);
current = left[0];
printf("-> %d ", current);
for (int i = 1; i < l; i++) {
total_seek += abs(left[i] - current);
current = left[i];
printf("-> %d ", current);
}
}
printf("\nTotal Seek Time: %d\n", total_seek);
}
int main() {
int choice, n, head, disk_size;
int arr[MAX];
printf("Menu:\n");
printf("1. SSTF\n");
printf("2. SCAN\n");
printf("3. C-SCAN\n");
printf("4. C-LOOK\n");
printf("Enter your choice: ");
scanf("%d", &choice);
printf("Enter number of requests: ");
scanf("%d", &n);
printf("Enter the request queue (space separated): ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter initial head position: ");
scanf("%d", &head);
if (ce == 2 || choice == 3) { // SCAN and C-SCAN require the disk size
printf("Enter disk size: ");
scanf("%d", &disk_size);
}
switch (choice) {
case 1:
sstf(arr, n, head);
break;
case 2:
scan(arr, n, head, disk_size);
break;
case 3:
cscan(arr, n, head, disk_size);
break;
case 4:
clook(arr, n, head);
break;
default:
printf("Invalid choice!\n");
}
return 0;
}

View file

@ -1,234 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
void sstf(int requests[], int n, int head) {
int total_seek = 0;
int completed = 0;
int visited[100] = {0};
int current = head;
printf("\nSSTF Disk Scheduling\n");
printf("Seek Sequence: %d", head);
while (completed < n) {
int min_distance = INT_MAX;
int min_index = -1;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
int distance = abs(requests[i] - current);
if (distance < min_distance) {
min_distance = distance;
min_index = i;
}
}
}
visited[min_index] = 1;
current = requests[min_index];
total_seek += min_distance;
completed++;
printf(" -> %d", current);
}
printf("\nTotal Seek Time: %d\n", total_seek);
}
void scan(int requests[], int n, int head, int disk_size) {
int total_seek = 0;
int direction = 1; // 1 for moving right, 0 for moving left
int current = head;
printf("\nSCAN Disk Scheduling\n");
printf("Seek Sequence: %d", head);
// Sort requests
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (requests[j] > requests[j + 1]) {
int temp = requests[j];
requests[j] = requests[j + 1];
requests[j + 1] = temp;
}
}
}
// Find position of head in sorted array
int index;
for (index = 0; index < n; index++) {
if (requests[index] >= head)
break;
}
// Move right
for (int i = index; i < n; i++) {
current = requests[i];
printf(" -> %d", current);
total_seek += abs(current - head);
head = current;
}
// Move to the end of disk
printf(" -> %d", disk_size - 1);
total_seek += abs(disk_size - 1 - head);
head = disk_size - 1;
// Move left
for (int i = index - 1; i >= 0; i--) {
current = requests[i];
printf(" -> %d", current);
total_seek += abs(current - head);
head = current;
}
printf("\nTotal Seek Time: %d\n", total_seek);
}
void cscan(int requests[], int n, int head, int disk_size) {
int total_seek = 0;
int current = head;
printf("\nC-SCAN Disk Scheduling\n");
printf("Seek Sequence: %d", head);
// Sort requests
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (requests[j] > requests[j + 1]) {
int temp = requests[j];
requests[j] = requests[j + 1];
requests[j + 1] = temp;
}
}
}
// Find position of head in sorted array
int index;
for (index = 0; index < n; index++) {
if (requests[index] >= head)
break;
}
// Move right
for (int i = index; i < n; i++) {
current = requests[i];
printf(" -> %d", current);
total_seek += abs(current - head);
head = current;
}
// Move to the end of disk
printf(" -> %d", disk_size - 1);
total_seek += abs(disk_size - 1 - head);
// Move to the beginning
printf(" -> 0");
total_seek += disk_size - 1;
head = 0;
// Move right again
for (int i = 0; i < index; i++) {
current = requests[i];
printf(" -> %d", current);
total_seek += abs(current - head);
head = current;
}
printf("\nTotal Seek Time: %d\n", total_seek);
}
void clook(int requests[], int n, int head) {
int total_seek = 0;
int current = head;
printf("\nC-LOOK Disk Scheduling\n");
printf("Seek Sequence: %d", head);
// Sort requests
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (requests[j] > requests[j + 1]) {
int temp = requests[j];
requests[j] = requests[j + 1];
requests[j + 1] = temp;
}
}
}
// Find position of head in sorted array
int index;
for (index = 0; index < n; index++) {
if (requests[index] >= head)
break;
}
// Move right
for (int i = index; i < n; i++) {
current = requests[i];
printf(" -> %d", current);
total_seek += abs(current - head);
head = current;
}
// Move to first request
for (int i = 0; i < index; i++) {
current = requests[i];
printf(" -> %d", current);
total_seek += abs(current - head);
head = current;
}
printf("\nTotal Seek Time: %d\n", total_seek);
}
int main() {
int requests[100], n, head, disk_size, choice;
printf("Enter the number of disk requests: ");
scanf("%d", &n);
printf("Enter the disk requests: ");
for (int i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}
printf("Enter the initial head position: ");
scanf("%d", &head);
printf("Enter the disk size (0 to size-1): ");
scanf("%d", &disk_size);
do {
printf("\n\nDisk Scheduling Algorithms\n");
printf("1. SSTF (Shortest Seek Time First)\n");
printf("2. SCAN\n");
printf("3. C-SCAN\n");
printf("4. C-LOOK\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
sstf(requests, n, head);
break;
case 2:
scan(requests, n, head, disk_size);
break;
case 3:
cscan(requests, n, head, disk_size);
break;
case 4:
clook(requests, n, head);
break;
case 5:
printf("Exiting program...\n");
break;
default:
printf("Invalid choice!\n");
}
} while (choice != 5);
return 0;
}

View file

View file

@ -1,153 +0,0 @@
#include <stdio.h>
// Define Task structure (simplified for memorization)
typedef struct {
int id; // Task ID
int period; // Period (also deadline for simplicity)
int execution_time; // Worst-case execution time (WCET)
// --- Simulation State ---
int remaining_execution; // Remaining execution time for current instance
int absolute_deadline; // Absolute deadline for current instance
int time_to_arrival; // Time until the next instance arrives/is released
} Task;
// --- Global Variables ---
// Define the tasks for the simulation (Example Set)
// Format: {id, Period, ExecutionTime, 0, 0, 0} <-- Initial state values
Task tasks[] = {
{1, 5, 2, 0, 0, 0}, // Task 1: Period=5, Exec Time=2
{2, 8, 3, 0, 0, 0} // Task 2: Period=8, Exec Time=3
// Add more tasks here if needed
};
// Calculate number of tasks automatically
int num_tasks = sizeof(tasks) / sizeof(Task);
// Set simulation duration (e.g., Hyperperiod or a fixed time)
// LCM(5, 8) = 40
int simulation_time = 40;
// --- Rate Monotonic (RM) Simulation ---
void simulate_rm() {
printf("--- Rate Monotonic Scheduling ---\n");
// Reset task states for the simulation run
for (int i = 0; i < num_tasks; i++) {
tasks[i].remaining_execution = 0;
tasks[i].absolute_deadline = 0;
tasks[i].time_to_arrival = 0; // All tasks start at time 0
}
// Main simulation loop
for (int time = 0; time < simulation_time; time++) {
// 1. Check for task arrivals (release time)
for (int i = 0; i < num_tasks; i++) {
if (tasks[i].time_to_arrival == 0) {
// Check if the previous instance of this task missed its deadline
if (tasks[i].remaining_execution > 0) {
printf("!!! Time %d: Task %d MISSED DEADLINE !!!\n", time, tasks[i].id);
// Simple handling: Continue with the new instance, old one is lost
}
// Release new instance of the task
tasks[i].remaining_execution = tasks[i].execution_time;
tasks[i].absolute_deadline = time + tasks[i].period; // Deadline = Period
tasks[i].time_to_arrival = tasks[i].period; // Set timer for the *next* arrival
}
tasks[i].time_to_arrival--; // Decrement time until the next arrival for all tasks
}
// 2. Select highest priority task to run (RM: Shortest Period has highest priority)
int task_to_run = -1; // -1 indicates CPU Idle
int highest_priority = 10000; // Initialize with a low priority (large period)
for (int i = 0; i < num_tasks; i++) {
// Check if task is ready (has arrived and needs execution)
if (tasks[i].remaining_execution > 0) {
// RM priority check: Lower period value means higher priority
if (tasks[i].period < highest_priority) {
highest_priority = tasks[i].period;
task_to_run = i; // Select this task
}
}
}
// 3. Execute the selected task (or remain idle)
if (task_to_run != -1) {
// Task selected to run
printf("Time %d: Task %d running\n", time, tasks[task_to_run].id);
tasks[task_to_run].remaining_execution--; // Execute for one time unit
// Optional: Check if task just finished
// if (tasks[task_to_run].remaining_execution == 0) {
// printf("Time %d: Task %d finished\n", time + 1, tasks[task_to_run].id);
// }
} else {
// No task ready to run
printf("Time %d: CPU Idle\n", time);
}
}
printf("--- RM Simulation Complete ---\n");
}
// --- Earliest Deadline First (EDF) Simulation ---
void simulate_edf() {
printf("\n--- Earliest Deadline First Scheduling ---\n");
// Reset task states
for (int i = 0; i < num_tasks; i++) {
tasks[i].remaining_execution = 0;
tasks[i].absolute_deadline = 0;
tasks[i].time_to_arrival = 0;
}
// Main simulation loop
for (int time = 0; time < simulation_time; time++) {
// 1. Check for task arrivals (same as RM)
for (int i = 0; i < num_tasks; i++) {
if (tasks[i].time_to_arrival == 0) {
if (tasks[i].remaining_execution > 0) {
printf("!!! Time %d: Task %d MISSED DEADLINE !!!\n", time, tasks[i].id);
}
tasks[i].remaining_execution = tasks[i].execution_time;
tasks[i].absolute_deadline = time + tasks[i].period;
tasks[i].time_to_arrival = tasks[i].period;
}
tasks[i].time_to_arrival--;
}
// 2. Select highest priority task to run (EDF: Earliest Absolute Deadline has highest priority)
int task_to_run = -1;
int earliest_deadline = 10000; // Initialize with a late deadline
for (int i = 0; i < num_tasks; i++) {
// Check if task is ready
if (tasks[i].remaining_execution > 0) {
// EDF priority check: Lower deadline value means higher priority (earlier deadline)
if (tasks[i].absolute_deadline < earliest_deadline) {
earliest_deadline = tasks[i].absolute_deadline;
task_to_run = i; // Select this task
}
}
}
// 3. Execute the selected task (same as RM)
if (task_to_run != -1) {
printf("Time %d: Task %d running\n", time, tasks[task_to_run].id);
tasks[task_to_run].remaining_execution--;
// Optional: Check finish
// if (tasks[task_to_run].remaining_execution == 0) {
// printf("Time %d: Task %d finished\n", time + 1, tasks[task_to_run].id);
// }
} else {
printf("Time %d: CPU Idle\n", time);
}
}
printf("--- EDF Simulation Complete ---\n");
}
// --- Main Function ---
int main() {
// Run Rate Monotonic simulation
simulate_rm();
// Run Earliest Deadline First simulation
simulate_edf();
return 0; // Indicate successful execution
}

Binary file not shown.

View file

@ -6,100 +6,106 @@
#include <semaphore.h>
#include <unistd.h>
#define NR 3 // NUM_READERS
#define NW 2 // NUM_WRITERS
#define NUM_READERS 3
#define NUM_WRITERS 2
// shared data structure - simple integer
int sd = 0; // shared_data
int shared_data = 0;
// sync variables
pthread_mutex_t m; // mutex for rc protection
sem_t w; // semaphore for writer access control
int rc = 0; // read_count: tracks active readers
pthread_mutex_t mutex; // mutex for read_count protection
sem_t wrt; // semaphore for writer access control
int read_count = 0; // tracks active readers
void* r(void* arg) { // reader
void* reader(void* arg) {
int id = *((int*)arg);
while (1) {
// read delay sim
sleep(1);
// critical section entry
pthread_mutex_lock(&m);
rc++;
if (rc == 1) {
pthread_mutex_lock(&mutex);
read_count++;
if (read_count == 1) {
// first reader blocks writers
sem_wait(&w);
sem_wait(&wrt);
}
pthread_mutex_unlock(&m);
pthread_mutex_unlock(&mutex);
// critical section
printf("Reader %d is reading sd = %d\n", id, sd);
printf("Reader %d is reading shared_data = %d\n", id, shared_data);
sleep(2); // read time sim
// critical section exit
pthread_mutex_lock(&m);
rc--;
if (rc == 0) {
pthread_mutex_lock(&mutex);
read_count--;
if (read_count == 0) {
// last reader unblocks writers
sem_post(&w);
sem_post(&wrt);
}
pthread_mutex_unlock(&m);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void* w_func(void* arg) { // writer
void* writer(void* arg) {
int id = *((int*)arg);
while (1) {
// write delay sim
sleep(3);
// critical section entry
sem_wait(&w); // exclusive access control
sem_wait(&wrt); // exclusive access control
// critical section
sd++; // shared_data modification
printf("Writer %d is writing: sd becomes %d\n", id, sd);
shared_data += 1;
printf("Writer %d is writing: shared_data becomes %d\n", id, shared_data);
sleep(2); // write time sim
// critical section exit
sem_post(&w);
sem_post(&wrt);
}
pthread_exit(NULL);
}
int main(void) {
pthread_t rts[NR], wts[NW]; // reader/writer threads
int rids[NR], wids[NW]; // reader/writer ids
pthread_t readers[NUM_READERS], writers[NUM_WRITERS];
int reader_ids[NUM_READERS], writer_ids[NUM_WRITERS];
int i;
// sync init
pthread_mutex_init(&m, NULL);
sem_init(&w, 0, 1); // binary semaphore init
pthread_mutex_init(&mutex, NULL);
sem_init(&wrt, 0, 1); // binary semaphore init
// reader thread creation
for (i = 0; i < NR; i++) {
rids[i] = i + 1;
pthread_create(&rts[i], NULL, r, &rids[i]);
for (i = 0; i < NUM_READERS; i++) {
reader_ids[i] = i + 1;
if (pthread_create(&readers[i], NULL, reader, &reader_ids[i]) != 0) {
perror("Failed to create reader thread");
exit(EXIT_FAILURE);
}
}
// writer thread creation
for (i = 0; i < NW; i++) {
wids[i] = i + 1;
pthread_create(&wts[i], NULL, w_func, &wids[i]);
for (i = 0; i < NUM_WRITERS; i++) {
writer_ids[i] = i + 1;
if (pthread_create(&writers[i], NULL, writer, &writer_ids[i]) != 0) {
perror("Failed to create writer thread");
exit(EXIT_FAILURE);
}
}
// thread joining
for (i = 0; i < NR; i++) {
pthread_join(rts[i], NULL);
for (i = 0; i < NUM_READERS; i++) {
pthread_join(readers[i], NULL);
}
for (i = 0; i < NW; i++) {
pthread_join(wts[i], NULL);
for (i = 0; i < NUM_WRITERS; i++) {
pthread_join(writers[i], NULL);
}
// cleanup
pthread_mutex_destroy(&m);
sem_destroy(&w);
pthread_mutex_destroy(&mutex);
sem_destroy(&wrt);
return 0;
}

Binary file not shown.

View file

@ -1,95 +0,0 @@
#include <stdio.h>
// C program for Banker's Algorithm (Safety & Resource Request)
// Optimized for minimal code size (e.g., for writing on paper)
int main() {
int p, r, i, j, k, pid, req_pid = -1; // p=procs, r=res; req_pid: -1=initial, >=0 processing req
printf("P R:"); scanf("%d%d", &p, &r); // Input num processes and resources
int av[r], max[p][r], al[p][r], nd[p][r], req[r]; // av=avail, al=alloc, nd=need
int w[r], fin[p], seq[p]; // w=work, fin=finish, seq=safe sequence
// Input available, max, allocation matrices
printf("Av:"); for(j=0; j<r; j++) scanf("%d", &av[j]);
printf("Max:\n"); for(i=0; i<p; i++) for(j=0; j<r; j++) scanf("%d", &max[i][j]);
printf("Alloc:\n"); for(i=0; i<p; i++) for(j=0; j<r; j++) scanf("%d", &al[i][j]);
// Calculate need matrix: need = max - alloc
for(i=0; i<p; i++) for(j=0; j<r; j++) nd[i][j] = max[i][j] - al[i][j];
S:; // Safety Check Algorithm Label
int s_idx = 0, c = 0, safe = 0; // s_idx=seq index, c=count finished, safe=flag
for(j=0; j<r; j++) w[j] = av[j]; // work = avail
for(i=0; i<p; i++) fin[i] = 0; // finish[p] = {false}
// Find sequence using safety algorithm logic
while(c < p) { // Loop until all processes are finished or deadlock
int found = 0; // Flag to check if a process was found in this pass
for(i=0; i<p; i++) { // Iterate through processes
if(!fin[i]) { // If process i not finished
int possible = 1; // Check if need <= work
for(j=0; j<r; j++) if(nd[i][j] > w[j]) { possible = 0; break; }
if(possible) { // If need <= work
for(k=0; k<r; k++) w[k] += al[i][k]; // work = work + alloc
fin[i] = 1; seq[s_idx++] = i; c++; found = 1; // Mark finished, add to seq
}
}
}
if(!found) break; // If no process found in a full pass, break (unsafe state)
}
if(c == p) safe = 1; // If all processes finished, state is safe
// --- End Safety Check ---
// Handle result based on phase (initial check or request check)
if(req_pid == -1) { // Phase 1: Initial State Check
if(safe) {
printf("SAFE. Seq:"); for(i=0; i<p; i++) printf(" P%d", seq[i]); puts("");
} else { puts("UNSAFE"); goto end; } // If unsafe initially, exit
// Phase 2: Resource Request
printf("PID Req:"); scanf("%d", &pid); req_pid = pid; // Get requesting proc ID
printf("Req:"); for(j=0; j<r; j++) scanf("%d", &req[j]); // Get request vector
// Check 1: Request <= Need
for(j=0; j<r; j++) if(req[j] > nd[pid][j]) { puts("Err:Req>Need"); goto end; }
// Check 2: Request <= Available
for(j=0; j<r; j++) if(req[j] > av[j]) { puts("Wait:Req>Avail"); goto end; }
// Tentatively allocate resources
for(j=0; j<r; j++) { av[j]-=req[j]; al[pid][j]+=req[j]; nd[pid][j]-=req[j]; }
puts("Checking req safety...");
goto S; // Re-run safety check on the new state
} else { // Phase 3: Post-Request Safety Check Result
if(safe) { // Request is granted if new state is safe
printf("Req OK. Seq:"); for(i=0; i<p; i++) printf(" P%d", seq[i]); puts("");
} else { // Request denied if new state is unsafe
puts("Req DENIED (unsafe)");
// Rollback state to before tentative allocation
pid = req_pid; // Restore pid for rollback
for(j=0; j<r; j++) { av[j]+=req[j]; al[pid][j]-=req[j]; nd[pid][j]+=req[j]; }
}
// No further action needed after handling the single request
}
end: return 0; // End of program
}
/*
```
P R: 5 3
Av: 3 3 2
Max:
7 5 3
3 2 2
9 0 2
2 2 2
4 3 3
Alloc:
0 1 0
2 0 0
3 0 2
2 1 1
0 0 2
```
*/

Binary file not shown.

View file

@ -1,125 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
// Dynamic Storage Allocation: First Fit & Best Fit
// Optimized for minimal code size (e.g., for writing on paper)
// Block structure: s=start, z=size, p=process_id (0 if free)
struct B {int s, z, p;} *b;
int nb = 0, cap = 4, mem_sz; // num_blocks, capacity, total_memory_size
// insb: insert block at index idx, maintain order by start address 's'
void insb(int idx, int s, int z, int p) {
if (nb >= cap) {
cap *= 2;
b = realloc(b, cap * sizeof(struct B));
// Note: Real-world code checks realloc failure. Skipped for brevity.
}
for (int k = nb; k > idx; k--) b[k] = b[k-1]; // Shift right
b[idx] = (struct B){s, z, p};
nb++;
}
// rmb: remove block at index idx
void rmb(int idx) {
for (int k = idx; k < nb - 1; k++) b[k] = b[k+1]; // Shift left
nb--;
}
// pb: print current blocks state
void pb() {
printf("Mem:[");
// Print each block: start:size! (allocated) or start:size (free)
for(int i=0; i<nb; i++) printf(" %d:%d%s", b[i].s, b[i].z, b[i].p ? "!" : "");
printf(" ]\n");
}
// ff: First Fit allocation
void ff(int pid, int sz) {
int f = -1; // found index
for (int i = 0; i < nb; i++) { // Find first free block large enough
if (!b[i].p && b[i].z >= sz) { f = i; break; }
}
if (f != -1) { // Block found
if (b[f].z > sz) { // Need to split block
// Insert new free block for the remainder after the allocated part
insb(f + 1, b[f].s + sz, b[f].z - sz, 0);
b[f].z = sz; // Adjust size of the now-allocated block
}
b[f].p = pid; // Mark block as allocated to pid
printf("FF OK P%d->%d@%d\n", pid, sz, b[f].s);
} else printf("FF Fail P%d(%d)\n", pid, sz); // Allocation failed
pb(); // Show memory state
}
// bf: Best Fit allocation
void bf(int pid, int sz) {
int bi = -1, min_z = mem_sz + 1; // best_index, min_suitable_size
for (int i = 0; i < nb; i++) { // Find smallest free block large enough
if (!b[i].p && b[i].z >= sz && b[i].z < min_z) {
min_z = b[i].z; // Update best size found
bi = i; // Update best index found
}
}
if (bi != -1) { // Best fit block found
if (b[bi].z > sz) { // Need to split block
// Insert new free block for the remainder
insb(bi + 1, b[bi].s + sz, b[bi].z - sz, 0);
b[bi].z = sz; // Adjust size of the allocated block
}
b[bi].p = pid; // Mark block allocated
printf("BF OK P%d->%d@%d\n", pid, sz, b[bi].s);
} else printf("BF Fail P%d(%d)\n", pid, sz); // Allocation failed
pb(); // Show memory state
}
// de: Deallocate block associated with pid
void de(int pid) {
int f = -1; // found index
for (int i = 0; i < nb; i++) if (b[i].p == pid) { f = i; break; } // Find block by pid
if (f != -1) { // Block found
printf("De OK P%d@%d(%d)\n", pid, b[f].s, b[f].z);
b[f].p = 0; // Mark block as free
// Try merging with the *next* block if it exists and is free
if (f + 1 < nb && !b[f+1].p) {
b[f].z += b[f+1].z; // Absorb next block's size
rmb(f + 1); // Remove the next block entry
}
// Try merging with the *previous* block if it exists and is free
if (f > 0 && !b[f-1].p) {
b[f-1].z += b[f].z; // Add current block's size to previous
rmb(f); // Remove the current block entry (now merged)
// f = f-1; // If index 'f' were needed after merge, adjust it
}
pb(); // Show memory state
} else printf("De Fail P%d\n", pid); // Deallocation failed (pid not found)
}
// Main driver loop
int main() {
printf("MemSz:"); scanf("%d", &mem_sz); // Get total memory size
b = malloc(cap * sizeof(struct B)); // Allocate initial block array
if (!b) return 1; // Handle malloc failure
b[0] = (struct B){0, mem_sz, 0}; // Create the first block (all memory, free)
nb = 1;
pb(); // Show initial state
int choice, pid, sz;
printf("1:FF 2:BF 3:Dealloc 0:Exit\n");
// Loop until user enters 0
while(scanf("%d", &choice) == 1 && choice) {
if (choice == 1 || choice == 2) { // Allocate request
printf("PID Sz:"); scanf("%d%d", &pid, &sz);
if (choice == 1) ff(pid, sz); else bf(pid, sz);
} else if (choice == 3) { // Deallocate request
printf("PID:"); scanf("%d", &pid);
de(pid);
} else printf("?\n"); // Invalid choice
printf("1:FF 2:BF 3:Dealloc 0:Exit\n"); // Prompt again
}
free(b); // Free the block array memory
return 0;
}

View file

@ -1,81 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#define BLOCKS 4
#define REQUESTS 5
// Memory configuration
int memory[BLOCKS] = {100, 50, 25, 10};
int allocated[BLOCKS] = {0, 0, 0, 0};
// Helper: Reset allocation state
void resetAllocation() {
for(int i = 0; i < BLOCKS; i++) {
allocated[i] = 0;
}
}
// Print memory status
void printMemory() {
printf("\nMemory Status:\n");
for(int i = 0; i < BLOCKS; i++) {
printf("[Size: %d, %s] -> ", memory[i],
allocated[i] ? "Allocated" : "Free");
}
printf("NULL\n\n");
}
// First Fit allocation
void firstFit(int size) {
for(int i = 0; i < BLOCKS; i++) {
if (!allocated[i] && memory[i] >= size) {
allocated[i] = 1;
printf("Allocated %d bytes using First Fit\n", size);
return;
}
}
printf("First Fit: No suitable block found for %d bytes\n", size);
}
// Best Fit allocation
void bestFit(int size) {
int best = -1;
int bestSize = 999999;
for(int i = 0; i < BLOCKS; i++) {
if(!allocated[i] && memory[i] >= size && memory[i] < bestSize) {
bestSize = memory[i];
best = i;
}
}
if(best != -1) {
allocated[best] = 1;
printf("Allocated %d bytes using Best Fit\n", size);
} else {
printf("Best Fit: No suitable block found for %d bytes\n", size);
}
}
// Main function: run allocation sequence
int main() {
int requests[REQUESTS] = {15, 35, 60, 10, 5};
printf("=== FIRST FIT ===\n");
printMemory();
for(int i = 0; i < REQUESTS; i++) {
firstFit(requests[i]);
printMemory();
}
resetAllocation();
printf("=== BEST FIT ===\n");
printMemory();
for(int i = 0; i < REQUESTS; i++) {
bestFit(requests[i]);
printMemory();
}
return 0;
}

View file

@ -1,272 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <limits.h> // For INT_MAX
// Structure for a memory block
typedef struct Block {
int id; // Block ID (optional, can use address for uniqueness)
int size; // Size of the block
int allocated; // 0 if free, 1 if allocated
int process_id; // ID of process allocated to this block (-1 if free)
struct Block *next; // Pointer to the next block in the list
struct Block *prev; // Pointer to the previous block in the list (for potential merging)
} Block;
// Global head of the memory block linked list
Block *memory_head = NULL;
// Function to create a new block node
Block* create_block(int id, int size, int allocated, int process_id) {
Block *new_block = (Block*)malloc(sizeof(Block));
if (!new_block) {
perror("Failed to allocate memory for block");
exit(EXIT_FAILURE);
}
new_block->id = id;
new_block->size = size;
new_block->allocated = allocated;
new_block->process_id = process_id;
new_block->next = NULL;
new_block->prev = NULL;
return new_block;
}
// Function to initialize the memory list with one large free block
void initialize_memory(int total_size) {
if (memory_head != NULL) {
// Simple cleanup for re-initialization (more robust needed for general use)
Block *current = memory_head;
Block *next_node;
while(current != NULL) {
next_node = current->next;
free(current);
current = next_node;
}
memory_head = NULL; // Reset head
}
memory_head = create_block(0, total_size, 0, -1); // ID 0, size, free, no process
}
// Function to display the current state of memory blocks
void display_memory() {
Block *current = memory_head;
printf("Memory Blocks:\n");
printf("----------------------------------------------------\n");
printf("| ID | Size | Status | Process ID |\n");
printf("----------------------------------------------------\n");
while (current != NULL) {
printf("| %-2d | %-9d | %-9s | %-10d |\n",
current->id,
current->size,
current->allocated ? "Allocated" : "Free",
current->allocated ? current->process_id : -1);
current = current->next;
}
printf("----------------------------------------------------\n\n");
}
// Function to allocate memory using First Fit strategy
int allocate_first_fit(int process_id, int required_size) {
Block *current = memory_head;
Block *best_block = NULL;
// Find the first free block that is large enough
while (current != NULL) {
if (!current->allocated && current->size >= required_size) {
best_block = current;
break; // First fit found
}
current = current->next;
}
// If a suitable block is found
if (best_block != NULL) {
// Check if splitting is necessary (and worthwhile, e.g., remaining > 0)
if (best_block->size > required_size) {
// Create a new block for the remaining free space
int remaining_size = best_block->size - required_size;
// For simplicity, assigning next available ID - needs better management in real system
int new_block_id = best_block->id + 1; // simplistic ID assignment
Block *new_free_block = create_block(new_block_id, remaining_size, 0, -1);
// Update the allocated block
best_block->size = required_size;
best_block->allocated = 1;
best_block->process_id = process_id;
// Insert the new free block into the list
new_free_block->next = best_block->next;
new_free_block->prev = best_block;
if (best_block->next != NULL) {
best_block->next->prev = new_free_block;
}
best_block->next = new_free_block;
// Renumber subsequent block IDs (basic approach)
Block* temp = new_free_block->next;
int current_id = new_block_id + 1;
while (temp != NULL) {
temp->id = current_id++;
temp = temp->next;
}
} else { // Exact fit or minimal leftover space (allocate the whole block)
best_block->allocated = 1;
best_block->process_id = process_id;
}
printf("Process %d allocated %d units using First Fit in Block %d.\n", process_id, required_size, best_block->id);
return 1; // Allocation successful
} else {
printf("Process %d (size %d) could not be allocated using First Fit.\n", process_id, required_size);
return 0; // Allocation failed
}
}
// Function to allocate memory using Best Fit strategy
int allocate_best_fit(int process_id, int required_size) {
Block *current = memory_head;
Block *best_block = NULL;
int min_waste = INT_MAX;
// Find the smallest free block that is large enough
while (current != NULL) {
if (!current->allocated && current->size >= required_size) {
int waste = current->size - required_size;
if (waste < min_waste) {
min_waste = waste;
best_block = current;
}
}
current = current->next;
}
// If a suitable block is found
if (best_block != NULL) {
// Check if splitting is necessary (and worthwhile, e.g., remaining > 0)
if (best_block->size > required_size) {
// Create a new block for the remaining free space
int remaining_size = best_block->size - required_size;
int new_block_id = best_block->id + 1; // simplistic ID assignment
Block *new_free_block = create_block(new_block_id, remaining_size, 0, -1);
// Update the allocated block
best_block->size = required_size;
best_block->allocated = 1;
best_block->process_id = process_id;
// Insert the new free block into the list
new_free_block->next = best_block->next;
new_free_block->prev = best_block;
if (best_block->next != NULL) {
best_block->next->prev = new_free_block;
}
best_block->next = new_free_block;
// Renumber subsequent block IDs (basic approach)
Block* temp = new_free_block->next;
int current_id = new_block_id + 1;
while (temp != NULL) {
temp->id = current_id++;
temp = temp->next;
}
} else { // Exact fit (allocate the whole block)
best_block->allocated = 1;
best_block->process_id = process_id;
}
printf("Process %d allocated %d units using Best Fit in Block %d.\n", process_id, required_size, best_block->id);
return 1; // Allocation successful
} else {
printf("Process %d (size %d) could not be allocated using Best Fit.\n", process_id, required_size);
return 0; // Allocation failed
}
}
// Function to free all allocated memory for the linked list
void cleanup_memory() {
Block *current = memory_head;
Block *next_node;
while (current != NULL) {
next_node = current->next;
free(current);
current = next_node;
}
memory_head = NULL;
}
int main() {
int total_memory;
int num_processes;
int *process_sizes = NULL; // Dynamically allocated array for process sizes
int i;
// --- Input ---
printf("Enter the total size of memory: ");
scanf("%d", &total_memory);
if (total_memory <= 0) {
printf("Invalid memory size.\n");
return 1;
}
printf("Enter the number of processes: ");
scanf("%d", &num_processes);
if (num_processes <= 0) {
printf("Invalid number of processes.\n");
return 1;
}
// Dynamically allocate array for process sizes
process_sizes = (int*)malloc(num_processes * sizeof(int));
if (!process_sizes) {
perror("Failed to allocate memory for process sizes");
return 1;
}
printf("Enter the size required for each process:\n");
for (i = 0; i < num_processes; i++) {
printf("Process %d size: ", i + 1);
scanf("%d", &process_sizes[i]);
if (process_sizes[i] <= 0) {
printf("Invalid process size. Please enter a positive value.\n");
free(process_sizes);
return 1;
}
}
printf("\n");
// --- First Fit Simulation ---
printf("--- First Fit Allocation ---\n");
initialize_memory(total_memory);
printf("Initial Memory State:\n");
display_memory();
for (i = 0; i < num_processes; i++) {
allocate_first_fit(i + 1, process_sizes[i]); // Process IDs starting from 1
display_memory(); // Show state after each allocation attempt
}
printf("Final Memory State after First Fit:\n");
display_memory();
// --- Best Fit Simulation ---
printf("\n--- Best Fit Allocation ---\n");
initialize_memory(total_memory); // Re-initialize memory for a fresh start
printf("Initial Memory State:\n");
display_memory();
for (i = 0; i < num_processes; i++) {
allocate_best_fit(i + 1, process_sizes[i]); // Process IDs starting from 1
display_memory(); // Show state after each allocation attempt
}
printf("Final Memory State after Best Fit:\n");
display_memory();
// --- Cleanup ---
free(process_sizes); // Free the dynamically allocated process sizes array
cleanup_memory(); // Free the memory blocks linked list
return 0;
}

View file

@ -1,6 +1,8 @@
if [[ $# -lt 3 ]]; then
echo "Usage: $0 <filename1> <filename2>"
exit 1
read -p "Enter a number: " num
if [[ $num -gt 10 ]]; then
echo "Number is greater than 10"
elif [[ $num -eq 10 ]]; then
echo "Number is exactly 10"
else
echo "Number is less than 10"
fi
if

View file

@ -1,46 +0,0 @@
#!/bin/bash
# Ask for the directory
echo "Enter directory path:"
read dir
while true; do
echo ""
echo "Menu:"
echo "1. Convert .txt files to .py in $dir"
echo "2. List ownership properties (ls -l) of all files in $dir"
echo "3. Count .sh files and subdirectories in $dir"
echo "4. Exit"
echo -n "Choose an option: "
read option
case $option in
1)
for file in "$dir"/*.txt; do
if [ -f "$file" ]; then
new="${file%.txt}.py"
mv "$file" "$new"
echo "Renamed: $file -> $new"
fi
done
;;
2)
ls -l "$dir"
;;
3)
sh_count=$(ls -1 "$dir"/*.sh 2>/dev/null | wc -l)
dir_count=$(ls -d "$dir"/*/ 2>/dev/null | wc -w)
echo ".sh file count: $sh_count"
echo "Subdirectory count: $dir_count"
;;
4)
echo "Exiting..."
break
;;
*)
echo "Invalid option. Please try again."
;;
esac
done
echo "Bye!"

View file

@ -1,121 +0,0 @@
#include <stdio.h>
#include <pthread.h>
#include <limits.h>
#define MAX_PROC 10
#define MAX_REF 100
#define MAX_FRAMES 10
typedef struct {
int id; // Process ID
int frames; // Number of frames for this process
int n; // Number of page references
int ref[MAX_REF]; // Array of page references
int faults; // Page faults counter
} Process;
Process procs[MAX_PROC];
int proc_count = 0;
void *simulateOptimal(void *arg) {
Process *p = (Process *)arg;
int frameArr[MAX_FRAMES];
int i, j;
// Initialize frames as empty (-1)
for (i = 0; i < p->frames; i++) {
frameArr[i] = -1;
}
p->faults = 0;
// Process each page reference
for (i = 0; i < p->n; i++) {
int page = p->ref[i];
int found = 0;
// Check if page is already in a frame
for (j = 0; j < p->frames; j++) {
if (frameArr[j] == page) {
found = 1;
break;
}
}
if (found)
continue;
// Page fault occurs
p->faults++;
// Look for an empty frame (-1)
int empty = -1;
for (j = 0; j < p->frames; j++) {
if (frameArr[j] == -1) {
empty = j;
break;
}
}
if (empty != -1) {
frameArr[empty] = page;
continue;
}
// No empty frame; choose a victim using Optimal algorithm:
int replace = 0, farthest = -1;
for (j = 0; j < p->frames; j++) {
int k, nextUse = INT_MAX;
for (k = i + 1; k < p->n; k++) {
if (frameArr[j] == p->ref[k]) {
nextUse = k;
break;
}
}
if (nextUse > farthest) {
farthest = nextUse;
replace = j;
}
}
frameArr[replace] = page;
}
printf("Process %d: Faults = %d\n", p->id, p->faults);
return NULL;
}
int main() {
int i, j;
pthread_t threads[MAX_PROC];
// Input the number of processes
printf("Enter number of processes (max %d): ", MAX_PROC);
scanf("%d", &proc_count);
if (proc_count > MAX_PROC) proc_count = MAX_PROC;
// Input process details
for (i = 0; i < proc_count; i++) {
procs[i].id = i + 1;
printf("\nProcess %d:\n", procs[i].id);
printf("Enter number of frames (max %d): ", MAX_FRAMES);
scanf("%d", &procs[i].frames);
if (procs[i].frames > MAX_FRAMES) procs[i].frames = MAX_FRAMES;
printf("Enter number of page references (max %d): ", MAX_REF);
scanf("%d", &procs[i].n);
if (procs[i].n > MAX_REF) procs[i].n = MAX_REF;
printf("Enter %d page references (space separated): ", procs[i].n);
for (j = 0; j < procs[i].n; j++) {
scanf("%d", &procs[i].ref[j]);
}
}
// Create a thread for each process simulation
for (i = 0; i < proc_count; i++) {
pthread_create(&threads[i], NULL, simulateOptimal, &procs[i]);
}
int totalFaults = 0;
// Wait for all threads to complete
for (i = 0; i < proc_count; i++) {
pthread_join(threads[i], NULL);
totalFaults += procs[i].faults;
}
// Calculate and display average faults
printf("\nAverage Page Faults: %.2f\n", (float)totalFaults / proc_count);
return 0;
}