1 /* amigaos.c uses only amigaos APIs,
2 * as opposed to amigaio.c which mixes amigaos and perl APIs */
13 #if defined(__CLIB2__)
16 #if defined(__NEWLIB__)
17 # include <amiga_platform.h>
27 #include <proto/dos.h>
28 #include <proto/exec.h>
29 #include <proto/utility.h>
33 struct UtilityIFace *IUtility = NULL;
35 /***************************************************************************/
37 struct Interface *OpenInterface(CONST_STRPTR libname, uint32 libver)
39 struct Library *base = IExec->OpenLibrary(libname, libver);
40 struct Interface *iface = IExec->GetInterface(base, "main", 1, NULL);
43 // We should probably post some kind of error message here.
45 IExec->CloseLibrary(base);
51 /***************************************************************************/
53 void CloseInterface(struct Interface *iface)
57 struct Library *base = iface->Data.LibBase;
58 IExec->DropInterface(iface);
59 IExec->CloseLibrary(base);
63 BOOL __unlink_retries = FALSE;
65 void ___makeenviron() __attribute__((constructor));
66 void ___freeenviron() __attribute__((destructor));
68 void ___openinterfaces() __attribute__((constructor));
69 void ___closeinterfaces() __attribute__((destructor));
71 void ___openinterfaces()
74 IDOS = (struct DOSIFace *)OpenInterface("dos.library", 53);
77 (struct UtilityIFace *)OpenInterface("utility.library", 53);
80 void ___closeinterfaces()
82 CloseInterface((struct Interface *)IDOS);
83 CloseInterface((struct Interface *)IUtility);
85 int VARARGS68K araddebug(UBYTE *fmt, ...);
86 int VARARGS68K adebug(UBYTE *fmt, ...);
88 #define __USE_RUNCOMMAND__
90 char **myenviron = NULL;
91 char **origenviron = NULL;
93 static void createvars(char **envp);
105 int __myrc(__attribute__((unused))char *arg)
107 struct Task *thisTask = IExec->FindTask(0);
108 struct args *myargs = (struct args *)thisTask->tc_UserData;
110 createvars(myargs->envp);
111 // adebug("%s %ld %s \n",__FUNCTION__,__LINE__,myargs->command);
112 myargs->result = IDOS->RunCommand(myargs->seglist, myargs->stack,
113 myargs->command, myargs->length);
118 BPTR seglist, int stack, char *command, int length, char **envp)
121 struct Task *thisTask = IExec->FindTask(0);
122 struct Process *proc;
124 // adebug("%s %ld %s\n",__FUNCTION__,__LINE__,command?command:"NULL");
126 myargs.seglist = seglist;
127 myargs.stack = stack;
128 myargs.command = command;
129 myargs.length = length;
133 if ((proc = IDOS->CreateNewProcTags(
134 NP_Entry, __myrc, NP_Child, TRUE, NP_Input, IDOS->Input(),
135 NP_Output, IDOS->Output(), NP_Error, IDOS->ErrorOutput(),
136 NP_CloseInput, FALSE, NP_CloseOutput, FALSE, NP_CloseError,
137 FALSE, NP_CopyVars, FALSE,
139 // NP_StackSize, ((struct Process
140 // *)myargs.parent)->pr_StackSize,
141 NP_Cli, TRUE, NP_UserData, (int)&myargs,
142 NP_NotifyOnDeathSigTask, thisTask, TAG_DONE)))
145 IExec->Wait(SIGF_CHILD);
147 return myargs.result;
150 char *mystrdup(const char *s)
155 size = strlen(s) + 1;
157 if ((result = (char *)IExec->AllocVecTags(size, TAG_DONE)))
159 memmove(result, s, size);
164 static unsigned int pipenum = 0;
166 int pipe(int filedes[2])
168 char pipe_name[1024];
170 // adebug("%s %ld \n",__FUNCTION__,__LINE__);
172 sprintf(pipe_name, "/T/%x.%08lx", pipenum++, IUtility->GetUniqueID());
174 sprintf(pipe_name, "/PIPE/%x%08lx/4096/0", pipenum++,
175 IUtility->GetUniqueID());
178 /* printf("pipe: %s \n", pipe_name);*/
180 filedes[1] = open(pipe_name, O_WRONLY | O_CREAT);
181 filedes[0] = open(pipe_name, O_RDONLY);
182 if (filedes[0] == -1 || filedes[1] == -1)
184 if (filedes[0] != -1)
186 if (filedes[1] != -1)
190 /* printf("filedes %d %d\n", filedes[0],
191 * filedes[1]);fflush(stdout);*/
198 fprintf(stderr, "Can not bloody fork\n");
203 int wait(__attribute__((unused))int *status)
205 fprintf(stderr, "No wait try waitpid instead\n");
210 char *convert_path_a2u(const char *filename)
212 struct NameTranslationInfo nti;
219 __translate_amiga_to_unix_path_name(&filename, &nti);
221 return mystrdup(filename);
223 char *convert_path_u2a(const char *filename)
225 struct NameTranslationInfo nti;
232 if (strcmp(filename, "/dev/tty") == 0)
234 return mystrdup("CONSOLE:");
238 __translate_unix_to_amiga_path_name(&filename, &nti);
240 return mystrdup(filename);
243 static struct SignalSemaphore environ_sema;
245 void amigaos4_init_environ_sema()
247 IExec->InitSemaphore(&environ_sema);
250 void amigaos4_obtain_environ()
252 IExec->ObtainSemaphore(&environ_sema);
255 void amigaos4_release_environ()
257 IExec->ReleaseSemaphore(&environ_sema);
260 static void createvars(char **envp)
264 /* Set a local var to indicate to any subsequent sh that it is
266 * the top level shell and so should only inherit local amigaos
268 IDOS->SetVar("ABCSH_IMPORT_LOCAL", "TRUE", 5, GVF_LOCAL_ONLY);
270 amigaos4_obtain_environ();
274 while ((envp != NULL) && (*envp != NULL))
279 if ((len = strlen(*envp)))
281 if ((var = (char *)IExec->AllocVecTags(len + 1, AVT_ClearWithValue,0,TAG_DONE)))
285 val = strchr(var, '=');
302 amigaos4_release_environ();
313 int myexecvp(bool isperlthread, const char *filename, char *argv[])
316 //%s\n",__FUNCTION__,__LINE__,filename?filename:"NULL");
317 /* if there's a slash or a colon consider filename a path and skip
321 char *pathpart = NULL;
322 if ((strchr(filename, '/') == NULL) && (strchr(filename, ':') == NULL))
329 if (!(path = getenv("PATH")))
331 path = ".:/bin:/usr/bin:/c";
334 len = strlen(filename) + 1;
335 name = (char *)IExec->AllocVecTags(strlen(path) + len, AVT_ClearWithValue,0,AVT_Type,MEMF_SHARED,TAG_DONE);
336 pathpart = (char *)IExec->AllocVecTags(strlen(path) + 1, AVT_ClearWithValue,0,AVT_Type,MEMF_SHARED,TAG_DONE);
342 if (!(p = strchr(path, ':')))
344 p = strchr(path, '\0');
347 memcpy(pathpart, path, p - path);
348 pathpart[p - path] = '\0';
349 if (!(strlen(pathpart) == 0))
351 sprintf(name, "%s/%s", pathpart, filename);
354 sprintf(name, "%s", filename);
356 if ((stat(name, &st) == 0) && (S_ISREG(st.st_mode)))
358 /* we stated it and it's a regular file */
365 while (*p++ != '\0');
368 res = myexecve(isperlthread, filename, argv, myenviron);
372 IExec->FreeVec((APTR)name);
377 IExec->FreeVec((APTR)pathpart);
383 int myexecv(bool isperlthread, const char *path, char *argv[])
385 return myexecve(isperlthread, path, argv, myenviron);
388 int myexecl(bool isperlthread, const char *path, ...)
391 char *argv[1024]; /* 1024 enough? let's hope so! */
393 // adebug("%s %ld\n",__FUNCTION__,__LINE__);
400 argv[i] = va_arg(va, char *);
402 while (argv[i++] != NULL);
405 return myexecve(isperlthread, path, argv, myenviron);
410 fprintf(stderr, "Pause not implemented\n");
416 uint32 size_env(struct Hook *hook, __attribute__((unused))APTR userdata, struct ScanVarsMsg *message)
418 if (strlen(message->sv_GDir) <= 4)
420 hook->h_Data = (APTR)(((uint32)hook->h_Data) + 1);
425 uint32 copy_env(struct Hook *hook, __attribute__((unused))APTR userdata, struct ScanVarsMsg *message)
427 if (strlen(message->sv_GDir) <= 4)
429 char **env = (char **)hook->h_Data;
431 strlen(message->sv_Name) + 1 + message->sv_VarLen + 1 + 1;
432 char *buffer = (char *)IExec->AllocVecTags((uint32)size,AVT_ClearWithValue,0,TAG_DONE);
435 snprintf(buffer, size - 1, "%s=%s", message->sv_Name,
445 void ___makeenviron()
447 struct Hook *hook = (struct Hook *)IExec->AllocSysObjectTags(ASOT_HOOK,TAG_DONE);
454 struct DOSIFace *myIDOS =
455 (struct DOSIFace *)OpenInterface("dos.library", 53);
459 if (myIDOS->GetVar("ABCSH_IMPORT_LOCAL", varbuf, 8,
462 flags = GVF_LOCAL_ONLY;
466 flags = GVF_GLOBAL_ONLY;
469 hook->h_Entry = size_env;
472 myIDOS->ScanVars(hook, flags, 0);
473 size = ((uint32)hook->h_Data) + 1;
475 myenviron = (char **)IExec->AllocVecTags(size *
477 AVT_ClearWithValue,0,TAG_DONE);
478 origenviron = myenviron;
481 IExec->FreeSysObject(ASOT_HOOK,hook);
482 CloseInterface((struct Interface *)myIDOS);
485 hook->h_Entry = copy_env;
486 hook->h_Data = myenviron;
488 myIDOS->ScanVars(hook, flags, 0);
489 IExec->FreeSysObject(ASOT_HOOK,hook);
490 CloseInterface((struct Interface *)myIDOS);
495 void ___freeenviron()
498 /* perl might change environ, it puts it back except for ctrl-c */
499 /* so restore our own copy here */
500 struct DOSIFace *myIDOS =
501 (struct DOSIFace *)OpenInterface("dos.library", 53);
504 myenviron = origenviron;
508 for (i = myenviron; *i != NULL; i++)
512 IExec->FreeVec(myenviron);
515 CloseInterface((struct Interface *)myIDOS);
519 /* reimplementation of popen, clib2's doesn't do all we want */
523 struct Task *thisTask = IExec->FindTask(0);
525 char *command = (char *)thisTask->tc_UserData;
530 argv[2] = command ? command : NULL;
533 // adebug("%s %ld %s\n",__FUNCTION__,__LINE__,command?command:"NULL");
535 /* We need to give this to sh via execvp, execvp expects filename,
539 myexecvp(FALSE, argv[0], (char **)argv);
541 IExec->FreeVec(command);
548 FILE *amigaos_popen(const char *cmd, const char *mode)
557 struct Process *proc = NULL;
558 struct Task *thisTask = IExec->FindTask(0);
560 /* First we need to check the mode
561 * We can only have unidirectional pipes
563 // adebug("%s %ld cmd %s mode %s \n",__FUNCTION__,__LINE__,cmd,
578 /* Make a unique pipe name
579 * we need a unix one and an amigaos version (of the same pipe!)
580 * as were linking with libunix.
583 sprintf(pipe_name, "%x%08lx/4096/0", pipenum++,
584 IUtility->GetUniqueID());
585 sprintf(unix_pipe, "/PIPE/%s", pipe_name);
586 sprintf(ami_pipe, "PIPE:%s", pipe_name);
588 /* Now we open the AmigaOs filehandles that we will pass to our
594 /* A read mode pipe: Output from pipe input from Output() or NIL:*/
595 /* First attempt to DUP Output() */
596 input = IDOS->DupFileHandle(IDOS->Output());
599 input = IDOS->Open("NIL:", MODE_READWRITE);
603 output = IDOS->Open(ami_pipe, MODE_NEWFILE);
605 result = fopen(unix_pipe, mode);
609 /* Open the write end first! */
611 result = fopen(unix_pipe, mode);
613 input = IDOS->Open(ami_pipe, MODE_OLDFILE);
616 output = IDOS->DupFileHandle(IDOS->Input());
619 output = IDOS->Open("NIL:", MODE_READWRITE);
623 if ((input == 0) || (output == 0) || (result == NULL))
625 /* Ouch stream opening failed */
639 /* We have our streams now start our new process
640 * We're using a new process so that execve can modify the environment
641 * with messing things up for the shell that launched perl
642 * Copy cmd before we launch the subprocess as perl seems to waste
643 * no time in overwriting it! The subprocess will free the copy.
646 if ((cmd_copy = mystrdup(cmd)))
649 // %s\n",__FUNCTION__,__LINE__,cmd_copy?cmd_copy:"NULL");
650 proc = IDOS->CreateNewProcTags(
651 NP_Entry, popen_child, NP_Child, TRUE, NP_StackSize,
652 ((struct Process *)thisTask)->pr_StackSize, NP_Input, input,
653 NP_Output, output, NP_Error, IDOS->ErrorOutput(),
654 NP_CloseError, FALSE, NP_Cli, TRUE, NP_Name,
655 "Perl: popen process", NP_UserData, (int)cmd_copy,
660 /* New Process Failed to start
668 IExec->FreeVec(cmd_copy);
676 /* Our new process is running and will close it streams etc
677 * once its done. All we need to is open the pipe via stdio
683 /* Workaround for clib2 fstat */
685 #define S_IFCHR 0x0020000
688 #define SET_FLAG(u, v) ((void)((u) |= (v)))
690 int afstat(int fd, struct stat *statb)
696 /* In the first instance pass it to fstat */
697 // adebug("fd %ld ad %ld\n",fd,amigaos_get_file(fd));
699 if ((result = fstat(fd, statb) >= 0))
702 /* Now we've got a file descriptor but we failed to stat it */
703 /* Could be a nil: or could be a std#? */
705 /* if get_default_file fails we had a dud fd so return failure */
706 #if !defined(__CLIB2__)
708 fh = amigaos_get_file(fd);
710 /* if nil: return failure*/
714 /* Now compare with our process Input() Output() etc */
715 /* if these were regular files sockets or pipes we had already
717 /* so we can guess they a character special console.... I hope */
719 struct ExamineData *data;
723 data = IDOS->ExamineObjectTags(EX_FileHandleInput, fh, TAG_END);
727 IUtility->Strlcpy(name, data->Name, sizeof(name));
729 IDOS->FreeDosObject(DOS_EXAMINEDATA, data);
732 // adebug("ad %ld '%s'\n",amigaos_get_file(fd),name);
735 if (fh == IDOS->Input())
738 SET_FLAG(mode, S_IRUSR);
739 SET_FLAG(mode, S_IRGRP);
740 SET_FLAG(mode, S_IROTH);
742 else if (fh == IDOS->Output() || fh == IDOS->ErrorOutput())
745 SET_FLAG(mode, S_IWUSR);
746 SET_FLAG(mode, S_IWGRP);
747 SET_FLAG(mode, S_IWOTH);
751 /* we got a filehandle not handle by fstat or the above */
752 /* most likely it's NIL: but lets check */
753 struct ExamineData *exd = NULL;
754 if ((exd = IDOS->ExamineObjectTags(EX_FileHandleInput, fh,
759 (20060920)) // Ugh yes I know nasty.....
763 IDOS->FreeDosObject(DOS_EXAMINEDATA, exd);
766 /* yep we got NIL: */
767 SET_FLAG(mode, S_IRUSR);
768 SET_FLAG(mode, S_IRGRP);
769 SET_FLAG(mode, S_IROTH);
770 SET_FLAG(mode, S_IWUSR);
771 SET_FLAG(mode, S_IWGRP);
772 SET_FLAG(mode, S_IWOTH);
777 "unhandled filehandle in afstat()\n");
783 memset(statb, 0, sizeof(statb));
785 statb->st_mode = mode;
791 BPTR amigaos_get_file(int fd)
793 BPTR fh = (BPTR)NULL;
794 if (!(fh = _get_osfhandle(fd)))
805 fh = IDOS->ErrorOutput();
814 /*########################################################################*/
816 #define LOCK_START 0xFFFFFFFFFFFFFFFELL
817 #define LOCK_LENGTH 1LL
819 // No wait forever option so lets wait for a loooong time.
820 #define TIMEOUT 0x7FFFFFFF
822 int amigaos_flock(int fd, int oper)
827 if (!(fh = amigaos_get_file(fd)))
837 if (IDOS->LockRecord(fh, LOCK_START, LOCK_LENGTH,
838 REC_SHARED | RECF_DOS_METHOD_ONLY,
847 if (IDOS->LockRecord(fh, LOCK_START, LOCK_LENGTH,
848 REC_EXCLUSIVE | RECF_DOS_METHOD_ONLY,
855 case LOCK_SH | LOCK_NB:
857 if (IDOS->LockRecord(fh, LOCK_START, LOCK_LENGTH,
858 REC_SHARED_IMMED | RECF_DOS_METHOD_ONLY,
869 case LOCK_EX | LOCK_NB:
871 if (IDOS->LockRecord(fh, LOCK_START, LOCK_LENGTH,
872 REC_EXCLUSIVE_IMMED | RECF_DOS_METHOD_ONLY,
885 if (IDOS->UnLockRecord(fh, LOCK_START, LOCK_LENGTH))