I'm porting platform driver code to a PCIe variant and I don't understand why I'm not getting a /dev/ entry to show up. The platform driver code that has been modified:
static dev_t first;
static struct class * class;
ATTRIBUTE_GROUPS(my);
static int __init my_pci_init(void)
{
int ret;
/* Create a class entry in sysfs */
if ((class = class_create(THIS_MODULE, "test_driver")) == NULL) {
pr_err("Couldn't create 'struct class' structure.");
ret = -ENODEV;
goto exit;
}
class->dev_groups = my_groups;
/* Create the /dev/ file system entry */
/* return value ignored: there's a 'struct class' to 'struct device' mapping */
if (device_create(class, NULL, first, NULL, KBUILD_MODNAME) == NULL) {
pr_err("Couldn't create entry in '/dev/' file system.");
ret = -ENODEV;
goto exit;
} else {
pr_info("Created a /dev/ entry.");
}
if ((ret = pci_register_driver(&pci_driver)) < 0) {
pr_err("Couldn't register pci driver.");
}
exit:
if (ret < 0) {
my_pci_exit();
pr_err(" ret = %d", ret);
}
return ret;
}
module_init(my_pci_init);
If the module name is 'cz_tdm', I was hoping the above code would create an entry /dev/cz_tdm. At least it did when I was compiling this as a platform driver.
The driver enumerates just fine, an output of lspci shows that the driver was loaded and perusing the sysfs shows that all my attributes in /sys/devices/virtual/... are where I'd expect them to be.
What gives?
Whoops.
Because it's not supposed too. An overzealous deletion of code ripped out this necessary element:
/* Add the char device to the system. */
cdev_init(&cdev, &fops);
if ((ret = cdev_add(&cdev, first, DEV_MINOR_NUMBER_COUNT)) < 0) {
pr_err("Couldn't add device to system: %d", ret);
ret = -ENODEV;
goto exit;
}
Related
Developing UEFI Based application for enabling pre-boot authentication using
Feitian Auto ePass 2003 FIPS USB Token. I'm still in the initial stage of the development process.
Now I'm able to fetch Manufacturer, Product Code of the token by using UsbIo->UsbGetDeviceDescriptor protocol. But when I try to find serial number it's throwing an error.
Is there any other way to find the serial number of the USB Token? Please help me on this..
This is my sample code for finding serial number
EFI_USB_DEVICE_DESCRIPTOR DevDesc;
EFI_USB_INTERFACE_DESCRIPTOR InterfaceDescriptor;
EFI_USB_ENDPOINT_DESCRIPTOR EndpointDescriptor;
EFI_USB_CONFIG_DESCRIPTOR ConfigDescriptor;
EFI_USB_IO_PROTOCOL *UsbIo;
EFI_STATUS Status;
EFI_HANDLE *HandleBuffer = NULL;
BOOLEAN LangFound;
UINTN HandleCount;
UINT8 EndpointNumber;
CHAR16* ManufacturerString = NULL;
CHAR16* ProductString = NULL;
CHAR16* SerialNumber = NULL;
UINT16* LangIDTable;
UINT16 TableSize;
INTN Index;
int index;
unsigned char* device_descriptor, * ccid_descriptor;
EFI_USB_DEVICE_REQUEST DevReq;
UINT32 Status_uint;
Status = gBS->LocateHandleBuffer( ByProtocol,
&gEfiUsbIoProtocolGuid,
NULL,
&HandleCount,
&HandleBuffer );
if (EFI_ERROR(Status)) {
Print(L"ERROR: LocateHandleBuffer.\n");
goto ErrorExit;
}
UINT8 usbIndex;
for (usbIndex = 0; usbIndex < HandleCount; usbIndex++) {
Status = gBS->HandleProtocol( HandleBuffer[usbIndex],
&gEfiUsbIoProtocolGuid,
(VOID**)&UsbIo );
if (EFI_ERROR(Status)) {
Print(L"ERROR: Open UsbIo.\n");
goto ErrorExit;
}
Status = UsbIo->UsbGetDeviceDescriptor( UsbIo, &DevDesc );
if (EFI_ERROR(Status)) {
Print(L"ERROR: UsbGetDeviceDescriptor.\n");
goto ErrorExit;
}
Status = UsbIo->UsbGetConfigDescriptor( UsbIo, &ConfigDescriptor );
if (EFI_ERROR (Status))
{
Print(L"UsbGetConfigDescriptor %d", Status);
goto ErrorExit;
}
Status = UsbIo->UsbGetInterfaceDescriptor( UsbIo, &InterfaceDescriptor );
if (EFI_ERROR (Status)) {
Print(L"ERROR: UsbGetInterfaceDescriptor.\n");
goto ErrorExit;
}
if (InterfaceDescriptor.InterfaceClass != CLASS_CCID) {
continue;
}
Print(L":::::::::::::::::::::: CCID ::::::::::::::::::::::\n");
//
// Get all supported languages.
//
TableSize = 0;
LangIDTable = NULL;
Status = UsbIo->UsbGetSupportedLanguages(UsbIo, &LangIDTable, &TableSize);
if (EFI_ERROR(Status)) {
Print(L"ERROR: UsbGetSupportedLanguages.\n");
return Status;
}
/* Get Manufacturer string */
for (Index = 0; Index < TableSize / sizeof(LangIDTable[0]); Index++) {
ManufacturerString = NULL;
Status = UsbIo->UsbGetStringDescriptor(UsbIo,
LangIDTable[Index],
DevDesc.StrManufacturer,
&ManufacturerString);
if (EFI_ERROR(Status) || (ManufacturerString == NULL)) {
continue;
}
Print(L"StrManufacturer ::%s\n", ManufacturerString);
FreePool(ManufacturerString);
break;
}
/* Get Product string */
for (Index = 0; Index < TableSize / sizeof(LangIDTable[0]); Index++) {
ProductString = NULL;
Status = UsbIo->UsbGetStringDescriptor(UsbIo,
LangIDTable[Index],
DevDesc.StrProduct,
&ProductString);
if (EFI_ERROR(Status) || (ProductString == NULL)) {
continue;
}
Print(L"StrProduct ::%s\n", ProductString);
FreePool(ProductString);
break;
}
/* Get Serial string */
for (Index = 0; Index < TableSize / sizeof(LangIDTable[0]); Index++) {
SerialNumber = NULL;
Status = UsbIo->UsbGetStringDescriptor(UsbIo,
LangIDTable[Index],
DevDesc.StrSerialNumber,
&SerialNumber);
if (EFI_ERROR(Status) || (SerialNumber == NULL)) {
Print(L"Error in finding SerialNumber \n");
continue;
}
Print(L"SerialNumber :: %s\n", SerialNumber);
FreePool(SerialNumber);
break;
}
Print(L"usbIndex ::%d\n", usbIndex);
Print(L"IdVendor ::%d\n", DevDesc.IdVendor);
Print(L"IdProduct ::%d\n", DevDesc.IdProduct);
}
Print(L"\n");
FreePool(HandleBuffer);
return Status;
From what I have read, the Feitian Technologies ePass2003 uses an Infineon M7893 or SLE 78CUFX5000PH (M7893-B) security chip.
As you have found out, the serial number for the ePass2003 is not stored in the USB device descriptor but in the security chip.
To obtain chip global data such as OEM information, algorithm support, FIPS mode indicator, RAM size and serial number, the GetData primitive is used. See the M7893 programming guide. if you can obtain access to it.
The driver for ePass2003 in OpenSC is called “epass2003”. The source code is currently available at https://github.com/OpenSC/OpenSC/blob/master/src/libopensc/card-epass2003.c. It has dependencies on OpenSSL and ASN.1 and some non-EDK2 headers, but these are easily worked around.
If all you are looking for is the serial number, it should be fairly easy to write a UEFI application (or driver) to get that information either by studying how the OpenSC ePass2003 driver does it (hint - look at epass2003_get_serialnr or studying the ePass2003 SDK which is available for free from Feitain and elsewhere.
The UEFI 2.5 specification released in April 2015 detailed 2 protocols relating to smart cards, i.e. Smart Card Reader and Smart Card Edge.
typedef struct _EFI_SMART_CARD_READER_PROTOCOL {
EFI_SMART_CARD_READER_CONNECT SCardConnect;
EFI_SMART_CARD_READER_DISCONNECT SCardDisconnect;
EFI_SMART_CARD_READER_STATUS SCardStatus;
EFI_SMART_CARD_READER_TRANSMIT SCardTransmit;
EFI_SMART_CARD_READER_CONTROL SCardControl;
EFI_SMART_CARD_READER_GET_ATTRIB SCardGetAttrib;
} EFI_SMART_CARD_READER_PROTOCOL;
typedef struct _EFI_SMART_CARD_EDGE_PROTOCOL {
EFI_SMART_CARD_EDGE_GET_CONTEXT GetContext;
EFI_SMART_CARD_EDGE_CONNECT Connect;
EFI_SMART_CARD_EDGE_DISCONNECT Disconnect;
EFI_SMART_CARD_EDGE_GET_CSN GetCsn;
EFI_SMART_CARD_EDGE_GET_READER_NAME GetReaderName;
EFI_SMART_CARD_EDGE_VERIFY_PIN VerifyPin;
EFI_SMART_CARD_EDGE_GET_PIN_REMAINING GetPinRemaining;
EFI_SMART_CARD_EDGE_GET_DATA GetData;
EFI_SMART_CARD_EDGE_GET_CREDENTIAL GetCredential;
EFI_SMART_CARD_EDGE_SIGN_DATA SignData;
EFI_SMART_CARD_EDGE_DECRYPT_DATA DecryptData;
EFI_SMART_CARD_EDGE_BUILD_DH_AGREEMENT BuildDHAgreement;
} EFI_SMART_CARD_EDGE_PROTOCOL;
EDK2 does not contain a sample implementation at present. However, you may be interested in the GPL2-licensed sample implementation by Ludovic Rousseau which is available at https://github.com/LudovicRousseau/edk2/tree/SmartCard. The implementation code, which is circa 5 years old and which I have not tested, is at MdeModulePkg/Library/SmartCardReader. Read his blog (https://ludovicrousseau.blogspot.com/) also as he provides useful sample applications also.
I struggle with Intel XL710 card using DPDK to make it compute RSS hash using only SRC IPV4 or DST IPV4 on per port basis.
The card has 4 10GE ports and RSS config is global for them whatever i do. I tried to set SRC/DST IPV4 fields in PCTYPE and the configuration applied last only takes action.
So the behavior i want to achieve.
Let's say i have upstream packet arrived on port 0:
SRC: 10.10.10.1 and DST:10.10.10.2
And reply downstream packet arrived on port 1:
SRC: 10.10.10.2 and DST:10.10.10.1
I want port 0 (which in our case is upstream) on the card to compute RSS hash based on SRC address 10.10.10.1 and for, port 1 (which is downstream) to compute the hash using DST address which in our case also will be 10.10.10.1. So the idea is to distribute packets between RX queues in a way that only SRC/DST address respectively affects this distribution.
I'm not bound specifically to RSS. Whatever tech will do if it allows to achieve this.
The configuration i used:
void setFilter(uint16_t portId, uint32_t value){
//Value = RTE_ETH_FLOW_NONFRAG_IPV4_TCP in that case
struct rte_eth_hash_filter_info info;
uint32_t ftype, idx, offset;
int ret;
if (rte_eth_dev_filter_supported(portId,
RTE_ETH_FILTER_HASH) < 0) {
printf("RTE_ETH_FILTER_HASH not supported on port %d\n",
portId);
return;
}
memset(&info, 0, sizeof(info));
info.info_type = RTE_ETH_HASH_FILTER_GLOBAL_CONFIG;
info.info.global_conf.hash_func =
RTE_ETH_HASH_FUNCTION_DEFAULT;
ftype = value;
idx = ftype / UINT64_BIT;
offset = ftype % UINT64_BIT;
info.info.global_conf.valid_bit_mask[idx] |= (1ULL << offset);
info.info.global_conf.sym_hash_enable_mask[idx] |=
(1ULL << offset);
ret = rte_eth_dev_filter_ctrl(portId, RTE_ETH_FILTER_HASH,
RTE_ETH_FILTER_SET, &info);
if (ret < 0)
printf("Cannot set global hash configurations by port %d\n",
portId);
else
printf("Global hash configurations have been set "
"succcessfully by port %d\n", portId);
}
void setPctypeRss(uint16_t portId, uint16_t fieldIdx) {
/* Note that AVF_FILTER_PCTYPE_NONF_IPV4_TCP is define for
* Virtual Function. Defines are the same for Physical Functions
*/
int ret = -ENOTSUP;
enum rte_pmd_i40e_inset_type inset_type = INSET_HASH;
struct rte_pmd_i40e_inset inset;
ret = rte_pmd_i40e_inset_get(portId, AVF_FILTER_PCTYPE_NONF_IPV4_TCP,
&inset, inset_type);
if (ret) {
printf("Failed to get input set.\n");
return;
}
memset(&inset, 0, sizeof(inset));
ret = rte_pmd_i40e_inset_set(portId, AVF_FILTER_PCTYPE_NONF_IPV4_TCP,
&inset, inset_type);
if (ret) {
printf("Failed to CLEAR input set.\n");
return;
}
else
{
printf("Successfull cleared input set\n");
}
ret = rte_pmd_i40e_inset_get(portId, AVF_FILTER_PCTYPE_NONF_IPV4_TCP,
&inset, inset_type);
if (ret) {
printf("Failed to get input set.\n");
return;
}
ret = rte_pmd_i40e_inset_field_set(&inset.inset, fieldIdx);
if (ret) {
printf("Failed to configure input set field.\n");
return;
}
ret = rte_pmd_i40e_inset_set(portId, AVF_FILTER_PCTYPE_NONF_IPV4_TCP,
&inset, inset_type);
if (ret) {
printf("Failed to set input set.\n");
return;
}
if (ret == -ENOTSUP)
printf("Function not supported\n");
}
IMO it is worth trying a bit simpler solution. We can simply use rte_eth_dev_configure():
https://doc.dpdk.org/api/rte__ethdev_8h.html#a1a7d3a20b102fee222541fda50fd87bd
And just set eth_conf.rss_conf.rss_hf to ETH_RSS_IP as described here:
https://doc.dpdk.org/api/structrte__eth__rss__conf.html#ad70f17882a835e5d4e38c64a9f872fdc
There are few examples in DPDK using this functionality. and most of them work fine ;)
I want to get 2 programs to communicate, one (server) would store datas, and the other (client) would just access it.
I'll have to use a linked list to store datas because it won't stop storing, and then I was wondering if I could access to the whole linked list if only the first node is shared in memory.
What I mean is… are we allowed to access from the client program to the memory pointed by a shared pointer?
Sorry it seems obvious that we can not, so should I store my linked list into the shared memory, or do you think that would be awkward?
Because if I do so, I'll have to declare a shared memory for every node right?
So, to add shared memory to both programs I need the same keys, but I don't know how many keys there will be, and I can't just store it for both programs, unless I would have had already a linked list…
so I used a very very VERY awkward method that I don't even know if it works right, but I wish you can tell, which is to use ftok that is supposed to take an (url,pid) and return a key. So I assumed it would send the exact same key if I used the same url and pid, using a fake pid starting from 0 that I would increment for every element I add to the linked list… what do you think about it? Any other way to do it which would seem less… crap?
typedef struct s_shared_elem
{
char c;
struct s_shared_elem* next;
struct s_shared_elem* previous;
}shared_elem;
typedef struct s_shared_list
{
s_shared_elem* first;
s_shared_elem* last;
}shared_list;
int forthekey = 0;
char* url="/home/toor/Projet_cgi/";
shared_elem* shared_malloc(int pid, const char* url)
{
shared_elem* shm;
int shmid;
int key=ftok(url,pid);
if((shmid=shmget(key,1,IPC_CREAT | 0666)) < 0)
{
perror("shmget");
exit(1);
}
if ((shm = shmat(shmid,NULL,0)) == (shared_elem*)-1)
{
perror("shmat");
exit(1);
}
return shm;
}
void Init_shared_list(shared_list* liste)
{
liste->first = NULL;
liste->last = NULL;
}
void Add_elem(shared_list* liste)
{
shared_elem* new = shared_malloc(pid,url);
new->next = NULL;
new->previous = liste->last;
if(liste->first == NULL)
{
liste->first = new;
liste->last = new;
}
else
{
liste->last->next = new;
liste->last = new;
}
forthekey++;
}
void shared_free(shared_elem* todelete,int pid, const char* url)
{
shared_elem* shm;
int shmid;
int key=ftok(url,pid);
if((shmid=shmget(key,1,IPC_CREAT | 0666)) < 0)
{
perror("shmget");
exit(1);
}
shmdt(todelete);
shmctl(shmid,IPC_RMID,NULL);
forthekey--;
}
void Delete_list(shared_list* liste)
{
while(liste->last != liste->first)
{
shared_elem* tmp=liste->last;
liste->last=liste->last->previous;
Shared_free(tmp,pid,url);
}
Shared_free(liste->first,pid,url);
}
In share memory you can insert a whole linked list. It is useful in many cases. You do not need to create a linked list of share memory (e.g. using previous key, next key ). All you need to copy each node of linked list to the shared memory.
for example .....
process2.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
int main(int argc, char *argv[])
{
int shmid,i;
node *data;
if ((shmid = shmget(10, SHM_SIZE, 0644 | IPC_CREAT)) == -1) {
perror("shmget");
exit(1);
}
data = (node *)shmat(shmid, (void *)0, 0); // node is linked list
for(i=0;i<2;i++)
printf("%d\n",(data++)->item_code);
if (shmdt(data) == -1) {
perror("shmdt");
exit(1);
}
return 0;
}
process1.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
int main(int argc, char *argv[])
{
node *SELL=NULL; // node is linked list (structure) SELL is header
insert(&SELL,"Soap",1,12.5,10);
insert(&SELL,"Pen",2,20.75,8);
display(SELL);
int shmid,i;
node *data;
if ((shmid = shmget(10, 2*sizeof(node), 0644 | IPC_CREAT)) == -1) {
perror("shmget");
exit(1);
}
data = (node *) shmat(shmid, (void *)0, 0);
for(i=0;i<2;i++)
{
*(data++)=*SELL;
SELL=SELL->next;
}
getchar();
if (shmdt(data) == -1) {
perror("shmdt");
exit(1);
}
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
Run process1.c 1st then run process2.c
am trying to create a link in windows 7 that has an icon. I am using the JNA library for this. I am having trouble with the call to CoCreateInstance. It returns error. First I am not sure if the GUID for IShellLink is the correct ( I am not a windows programer). Below is my code so far. Once I get the pointer to an IShellLink I would need to fill the paramaters for the link (target,icon, description, etc). I am modeling this call from the C code below found at this link (http://www.codeproject.com/Articles/11467/How-to-create-short-cuts-link-files). I know I could use mklink command for this but it does have an option to add an icon and description.
private void createLink(){
Pointer reserved = null; //Must be null
int dwCoInit = 0;
HRESULT oleInitResult = Ole32.INSTANCE.CoInitializeEx(reserved,dwCoInit);
if(oleInitResult.equals(W32Errors.S_OK)){
GUID rclsid = Ole32Util.getGUIDFromString("{e82a2d71-5b2f-43a0-97b8-81be15854de8}"); //Shell object
GUID riid = Ole32Util.getGUIDFromString("{000214EE-0000-0000-C000-000000000046}"); //CLSID of the IShellLink object
PointerByReference ppv = new PointerByReference();
HRESULT oleCreateResult = Ole32.INSTANCE.CoCreateInstance(rclsid,null,ObjBase.CLSCTX_INPROC,riid,ppv);
if(oleCreateResult.equals(W32Errors.S_OK)){
}else{
System.out.println("Failed to create link error "+oleCreateResult.intValue());
}
}
Ole32.INSTANCE.CoUninitialize();
}
###################### C++ Sample code
/*
--------------------------------------------------------------------------------
Description: Creates the actual 'lnk' file (assumes COM has been initialized).
Parameters: pszTargetfile - File name of the link's target, must be a non-empty string.
pszTargetargs - Command line arguments passed to link's target, may be an empty string.
pszLinkfile - File name of the actual link file, must be a non-empty string.
pszDescription - Description of the linked item. If this is an empty string the description is not set.
iShowmode - ShowWindow() constant for the link's target. Use one of:
1 (SW_SHOWNORMAL) = Normal window.
3 (SW_SHOWMAXIMIZED) = Maximized.
7 (SW_SHOWMINNOACTIVE) = Minimized.
If this is zero the showmode is not set.
pszCurdir - Working directory of the active link. If this is an empty string the directory is not set.
pszIconfile - File name of the icon file used for the link. If this is an empty string the icon is not set.
iIconindex - Index of the icon in the icon file. If this is < 0 the icon is not set.
Returns: HRESULT value >= 0 for success, < 0 for failure.
--------------------------------------------------------------------------------
*/
static HRESULT CreateShortCut(LPSTR pszTargetfile, LPSTR pszTargetargs, LPSTR pszLinkfile, LPSTR pszDescription,
int iShowmode, LPSTR pszCurdir, LPSTR pszIconfile, int iIconindex) {
HRESULT hRes; /* Returned COM result code */
IShellLink* pShellLink; /* IShellLink object pointer */
IPersistFile* pPersistFile; /* IPersistFile object pointer */
WORD wszLinkfile[MAX_PATH]; /* pszLinkfile as Unicode string */
int iWideCharsWritten; /* Number of wide characters written */
hRes = E_INVALIDARG;
if (
(pszTargetfile != NULL) && (strlen(pszTargetfile) > 0) &&
(pszTargetargs != NULL) &&
(pszLinkfile != NULL) && (strlen(pszLinkfile) > 0) &&
(pszDescription != NULL) &&
(iShowmode >= 0) &&
(pszCurdir != NULL) &&
(pszIconfile != NULL) &&
(iIconindex >= 0)
) {
hRes = CoCreateInstance(&CLSID_ShellLink, /* pre-defined CLSID of the IShellLink object */
NULL, /* pointer to parent interface if part of aggregate */
CLSCTX_INPROC_SERVER, /* caller and called code are in same process */
&IID_IShellLink, /* pre-defined interface of the IShellLink object */
&pShellLink); /* Returns a pointer to the IShellLink object */
if (SUCCEEDED(hRes))
{
/* Set the fields in the IShellLink object */
hRes = pShellLink->lpVtbl->SetPath(pShellLink, pszTargetfile);
hRes = pShellLink->lpVtbl->SetArguments(pShellLink, pszTargetargs);
if (strlen(pszDescription) > 0)
{
hRes = pShellLink->lpVtbl->SetDescription(pShellLink, pszDescription);
}
if (iShowmode > 0)
{
hRes = pShellLink->lpVtbl->SetShowCmd(pShellLink, iShowmode);
}
if (strlen(pszCurdir) > 0)
{
hRes = pShellLink->lpVtbl->SetWorkingDirectory(pShellLink, pszCurdir);
}
if (strlen(pszIconfile) > 0 && iIconindex >= 0)
{
hRes = pShellLink->lpVtbl->SetIconLocation(pShellLink, pszIconfile, iIconindex);
}
/* Use the IPersistFile object to save the shell link */
hRes = pShellLink->lpVtbl->QueryInterface(pShellLink, /* existing IShellLink object */
&IID_IPersistFile, /* pre-defined interface of the IPersistFile object */
&pPersistFile); /* returns a pointer to the IPersistFile object */
if (SUCCEEDED(hRes))
{
iWideCharsWritten = MultiByteToWideChar(CP_ACP, 0, pszLinkfile, -1, wszLinkfile, MAX_PATH);
hRes = pPersistFile->lpVtbl->Save(pPersistFile, wszLinkfile, TRUE);
pPersistFile->lpVtbl->Release(pPersistFile);
}
pShellLink->lpVtbl->Release(pShellLink);
}
}
return (hRes);
}
It turn out to be very simple. So If you hit this page you probably will save couple days by following this instructions:
Generate the mappings for the shell32.dll per instructions in the com4j site:
http://com4j.java.net/tutorial.html
Then just call the following to create the icons. It is very simple once you know.
IWshShell3 shellLink = ClassFactory.createWshShell();
Com4jObject obj = shellLink.createShortcut(linkPath.getAbsolutePath());
IWshShortcut link = obj.queryInterface(IWshShortcut.class);
link.workingDirectory(desktopPath.getAbsolutePath());
link.description("My Link");
link.arguments(" Hello ");
link.iconLocation(iconPath.getAbsolutePath());
link.targetPath(javawsPath.getAbsolutePath());
link.setName("Test Link");
link.save();
I have fixed the called to CoCreateInstance by changing the GUID. Below is the code and it returns OK. But now that I got the pointer I am not sure how to set the parameters I need (link name, target name, desc, icon). Anybody has any suggestions?
GUID rclsid = Ole32Util.getGUIDFromString("{00021401-0000-0000-C000-000000000046}"); //CLSID_ShellLink
if (W32Errors.FAILED(hr.intValue())) {
Ole32.INSTANCE.CoUninitialize();
throw new Exception("Shell Object GUID failed.");
}
GUID riid = Ole32Util.getGUIDFromString("{000214EE-0000-0000-C000-000000000046}"); //CLSID of the IShellLink object
PointerByReference ppv = new PointerByReference();
hr = Ole32.INSTANCE.CoCreateInstance(rclsid,null,WTypes.CLSCTX_LOCAL_SERVER,riid,ppv);
if(hr.equals(W32Errors.S_OK)){
Pointer type = ppv.getValue();
}else{
System.out.println("Failed to create link error "+hr.intValue());
}
I'm learning libev however the code is so hard to understand, so I choose to learn libevent first whose code is relatively clearer. But I encounter a problem when try the example (http://www.wangafu.net/~nickm/libevent-book/01_intro.html).
How is the code event_add(state->write_event, NULL) in do_read() make do_write() function invoked?
/* For sockaddr_in */
#include <netinet/in.h>
/* For socket functions */
#include <sys/socket.h>
/* For fcntl */
#include <fcntl.h>
#include <event2/event.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define MAX_LINE 16384
void do_read(evutil_socket_t fd, short events, void *arg);
void do_write(evutil_socket_t fd, short events, void *arg);
char
rot13_char(char c)
{
return c;
/* We don't want to use isalpha here; setting the locale would change
* which characters are considered alphabetical. */
if ((c >= 'a' && c <= 'm') || (c >= 'A' && c <= 'M'))
return c + 13;
else if ((c >= 'n' && c <= 'z') || (c >= 'N' && c <= 'Z'))
return c - 13;
else
return c;
}
struct fd_state {
char buffer[MAX_LINE];
size_t buffer_used;
size_t n_written;
size_t write_upto;
struct event *read_event;
struct event *write_event;
};
struct fd_state *
alloc_fd_state(struct event_base *base, evutil_socket_t fd)
{
struct fd_state *state = malloc(sizeof(struct fd_state));
if (!state)
return NULL;
state->read_event = event_new(base, fd, EV_READ|EV_PERSIST, do_read, state);
if (!state->read_event) {
free(state);
return NULL;
}
state->write_event =
event_new(base, fd, EV_WRITE|EV_PERSIST, do_write, state);
if (!state->write_event) {
event_free(state->read_event);
free(state);
return NULL;
}
state->buffer_used = state->n_written = state->write_upto = 0;
assert(state->write_event);
return state;
}
void
free_fd_state(struct fd_state *state)
{
event_free(state->read_event);
event_free(state->write_event);
free(state);
}
void
do_read(evutil_socket_t fd, short events, void *arg)
{
struct fd_state *state = arg;
char buf[1024];
int i;
ssize_t result;
while (1) {
assert(state->write_event);
result = recv(fd, buf, sizeof(buf), 0);
if (result <= 0)
break;
for (i=0; i < result; ++i) {
if (state->buffer_used < sizeof(state->buffer))
state->buffer[state->buffer_used++] = rot13_char(buf[i]);
if (buf[i] == '\n') {
assert(state->write_event);
**event_add(state->write_event, NULL);**
state->write_upto = state->buffer_used;
}
}
}
if (result == 0) {
free_fd_state(state);
} else if (result < 0) {
if (errno == EAGAIN) // XXXX use evutil macro
return;
perror("recv");
free_fd_state(state);
}
}
void
**do_write(evutil_socket_t fd, short events, void *arg)**
{
struct fd_state *state = arg;
while (state->n_written < state->write_upto) {
ssize_t result = send(fd, state->buffer + state->n_written,
state->write_upto - state->n_written, 0);
if (result < 0) {
if (errno == EAGAIN) // XXX use evutil macro
return;
free_fd_state(state);
return;
}
assert(result != 0);
state->n_written += result;
}
if (state->n_written == state->buffer_used)
state->n_written = state->write_upto = state->buffer_used = 1;
event_del(state->write_event);
}
void
do_accept(evutil_socket_t listener, short event, void *arg)
{
struct event_base *base = arg;
struct sockaddr_storage ss;
socklen_t slen = sizeof(ss);
int fd = accept(listener, (struct sockaddr*)&ss, &slen);
if (fd < 0) { // XXXX eagain??
perror("accept");
} else if (fd > FD_SETSIZE) {
close(fd); // XXX replace all closes with EVUTIL_CLOSESOCKET */
} else {
struct fd_state *state;
evutil_make_socket_nonblocking(fd);
state = alloc_fd_state(base, fd);
assert(state); /*XXX err*/
assert(state->write_event);
event_add(state->read_event, NULL);
}
}
void
run(void)
{
evutil_socket_t listener;
struct sockaddr_in sin;
struct event_base *base;
struct event *listener_event;
base = event_base_new();
if (!base)
return; /*XXXerr*/
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = 0;
sin.sin_port = htons(40713);
listener = socket(AF_INET, SOCK_STREAM, 0);
evutil_make_socket_nonblocking(listener);
#ifndef WIN32
{
int one = 1;
setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
}
#endif
if (bind(listener, (struct sockaddr*)&sin, sizeof(sin)) < 0) {
perror("bind");
return;
}
if (listen(listener, 16)<0) {
perror("listen");
return;
}
listener_event = event_new(base, listener, EV_READ|EV_PERSIST, do_accept, (void*)base);
/*XXX check it */
event_add(listener_event, NULL);
event_base_dispatch(base);
}
int
main(int c, char **v)
{
setvbuf(stdout, NULL, _IONBF, 0);
run();
return 0;
}
I'm not sure if I'm answering the same question you asked - I understand it as:
How does calling event_add(state->write_event, NULL) in do_read() lead to do_write() being invoked?
The key to figuring this out is understanding what the do_read() function is actually doing. do_read() is a callback function associated with a socket which has data to be read: this is set up with allocate_fd_state():
struct fd_state *
alloc_fd_state(struct event_base *base, evutil_socket_t fd)
{
/*
* Allocate a new fd_state structure, which will hold our read and write events
* /
struct fd_state *state = malloc(sizeof(struct fd_state));
[...]
/*
* Initialize a read event on the given file descriptor: associate the event with
* the given base, and set up the do_read callback to be invoked whenever
* data is available to be read on the file descriptor.
* /
state->read_event = event_new(base, fd, EV_READ|EV_PERSIST, do_read, state);
[...]
/*
* Set up another event on the same file descriptor and base, which invoked the
* do_write callback anytime the file descriptor is ready to be written to.
*/
state->write_event =
event_new(base, fd, EV_WRITE|EV_PERSIST, do_write, state);
[...]
return state;
}
At this point, though, neither of these events have been event_add()'ed to the event_base base. The instructions for what to do are all written out, but no one is looking at them. So how does anything get read? state->read_event is event_add()'ed to the base after an incoming connection is made. Look at do_accept():
void
do_accept(evutil_socket_t listener, short event, void *arg)
{
[ ... accept a new connection and give it a file descriptor fd ... ]
/*
* If the file descriptor is invalid, close it.
*/
if (fd < 0) { // XXXX eagain??
perror("accept");
} else if (fd > FD_SETSIZE) {
close(fd); // XXX replace all closes with EVUTIL_CLOSESOCKET */
/*
* Otherwise, if the connection was successfully accepted...
*/
} else {
[ ... allocate a new fd_state structure, and make the file descriptor non-blocking ...]
/*
* Here's where the magic happens. The read_event created back in alloc_fd_state()
* is finally added to the base associated with it.
*/
event_add(state->read_event, NULL);
}
}
So right after accepting a new connection, the program tells libevent to wait until there's data available on the connection, and then run the do_read() callback. At this point, it's still impossible for do_write() to be called. It needs to be event_add()'ed. This happens in do_read():
void
do_read(evutil_socket_t fd, short events, void *arg)
{
/* Create a temporary buffer to receive some data */
char buf[1024];
while (1) {
[ ... Receive the data, copying it into buf ... ]
[ ... if there is no more data to receive, or there was an error, exit this loop... ]
[ ... else, result = number of bytes received ... ]
for (i=0; i < result; ++i) {
[ ... if there's room in the buffer, copy in the rot13() encoded
version of the received data ... ]
/*
* Boom, headshot. If we've reached the end of the incoming data
* (assumed to be a newline), then ...
*/
if (buf[i] == '\n') {
[...]
/*
* Have libevent start monitoring the write_event, which calls do_write
* as soon as the file descriptor is ready to be written to.
*/
event_add(state->write_event, NULL);
[...]
}
}
}
[...]
}
So, after reading in some data from a file descriptor, the program starts waiting until
the file descriptor is ready to be written to, and then invokes do_write(). Program
flow looks like this:
[ set up an event_base and start waiting for events ]
[ if someone tries to connect ]
[ accept the connection ]
[ ... wait until there is data to read on the connection ... ]
[ read in data from the connection until there is no more left ]
[ ....wait until the connection is ready to be written to ... ]
[ write out our rot13() encoded response ]
I hope that a) that was the correct interpretation of your question, and b) this was a helpful answer.