1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#if HAVE_CONFIG_H
33#  include <config.h>
34#endif
35
36#include "private/cpu.h"
37#include <stdlib.h>
38#include <stdio.h>
39
40#if defined FLAC__CPU_IA32
41# include <signal.h>
42#elif defined FLAC__CPU_PPC
43# if !defined FLAC__NO_ASM
44#  if defined FLAC__SYS_DARWIN
45#   include <sys/sysctl.h>
46#   include <mach/mach.h>
47#   include <mach/mach_host.h>
48#   include <mach/host_info.h>
49#   include <mach/machine.h>
50#   ifndef CPU_SUBTYPE_POWERPC_970
51#    define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
52#   endif
53#  else /* FLAC__SYS_DARWIN */
54
55#   include <signal.h>
56#   include <setjmp.h>
57
58static sigjmp_buf jmpbuf;
59static volatile sig_atomic_t canjump = 0;
60
61static void sigill_handler (int sig)
62{
63	if (!canjump) {
64		signal (sig, SIG_DFL);
65		raise (sig);
66	}
67	canjump = 0;
68	siglongjmp (jmpbuf, 1);
69}
70#  endif /* FLAC__SYS_DARWIN */
71# endif /* FLAC__NO_ASM */
72#endif /* FLAC__CPU_PPC */
73
74#if defined (__NetBSD__) || defined(__OpenBSD__)
75#include <sys/param.h>
76#include <sys/sysctl.h>
77#include <machine/cpu.h>
78#endif
79
80#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
81#include <sys/types.h>
82#include <sys/sysctl.h>
83#endif
84
85#if defined(__APPLE__)
86/* how to get sysctlbyname()? */
87#endif
88
89/* these are flags in EDX of CPUID AX=00000001 */
90static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
91static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
92static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
93static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
94static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
95/* these are flags in ECX of CPUID AX=00000001 */
96static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
97static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
98/* these are flags in EDX of CPUID AX=80000001 */
99static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
100static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
101static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
102
103
104/*
105 * Extra stuff needed for detection of OS support for SSE on IA-32
106 */
107#if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
108# if defined(__linux__)
109/*
110 * If the OS doesn't support SSE, we will get here with a SIGILL.  We
111 * modify the return address to jump over the offending SSE instruction
112 * and also the operation following it that indicates the instruction
113 * executed successfully.  In this way we use no global variables and
114 * stay thread-safe.
115 *
116 * 3 + 3 + 6:
117 *   3 bytes for "xorps xmm0,xmm0"
118 *   3 bytes for estimate of how long the follwing "inc var" instruction is
119 *   6 bytes extra in case our estimate is wrong
120 * 12 bytes puts us in the NOP "landing zone"
121 */
122#  undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
123#  ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
124	static void sigill_handler_sse_os(int signal, struct sigcontext sc)
125	{
126		(void)signal;
127		sc.eip += 3 + 3 + 6;
128	}
129#  else
130#   include <sys/ucontext.h>
131	static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
132	{
133		(void)signal, (void)si;
134		((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
135	}
136#  endif
137# elif defined(_MSC_VER)
138#  include <windows.h>
139#  undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
140#  ifdef USE_TRY_CATCH_FLAVOR
141#  else
142	LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
143	{
144		if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
145			ep->ContextRecord->Eip += 3 + 3 + 6;
146			return EXCEPTION_CONTINUE_EXECUTION;
147		}
148		return EXCEPTION_CONTINUE_SEARCH;
149	}
150#  endif
151# endif
152#endif
153
154
155void FLAC__cpu_info(FLAC__CPUInfo *info)
156{
157/*
158 * IA32-specific
159 */
160#ifdef FLAC__CPU_IA32
161	info->type = FLAC__CPUINFO_TYPE_IA32;
162#if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
163	info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
164	info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
165	info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
166	info->data.ia32.cmov = false;
167	info->data.ia32.mmx = false;
168	info->data.ia32.fxsr = false;
169	info->data.ia32.sse = false;
170	info->data.ia32.sse2 = false;
171	info->data.ia32.sse3 = false;
172	info->data.ia32.ssse3 = false;
173	info->data.ia32._3dnow = false;
174	info->data.ia32.ext3dnow = false;
175	info->data.ia32.extmmx = false;
176	if(info->data.ia32.cpuid) {
177		/* http://www.sandpile.org/ia32/cpuid.htm */
178		FLAC__uint32 flags_edx, flags_ecx;
179		FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
180		info->data.ia32.cmov  = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
181		info->data.ia32.mmx   = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX  )? true : false;
182		info->data.ia32.fxsr  = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
183		info->data.ia32.sse   = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE  )? true : false;
184		info->data.ia32.sse2  = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
185		info->data.ia32.sse3  = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
186		info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
187
188#ifdef FLAC__USE_3DNOW
189		flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
190		info->data.ia32._3dnow   = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW   )? true : false;
191		info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
192		info->data.ia32.extmmx   = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX  )? true : false;
193#else
194		info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
195#endif
196
197#ifdef DEBUG
198		fprintf(stderr, "CPU info (IA-32):\n");
199		fprintf(stderr, "  CPUID ...... %c\n", info->data.ia32.cpuid   ? 'Y' : 'n');
200		fprintf(stderr, "  BSWAP ...... %c\n", info->data.ia32.bswap   ? 'Y' : 'n');
201		fprintf(stderr, "  CMOV ....... %c\n", info->data.ia32.cmov    ? 'Y' : 'n');
202		fprintf(stderr, "  MMX ........ %c\n", info->data.ia32.mmx     ? 'Y' : 'n');
203		fprintf(stderr, "  FXSR ....... %c\n", info->data.ia32.fxsr    ? 'Y' : 'n');
204		fprintf(stderr, "  SSE ........ %c\n", info->data.ia32.sse     ? 'Y' : 'n');
205		fprintf(stderr, "  SSE2 ....... %c\n", info->data.ia32.sse2    ? 'Y' : 'n');
206		fprintf(stderr, "  SSE3 ....... %c\n", info->data.ia32.sse3    ? 'Y' : 'n');
207		fprintf(stderr, "  SSSE3 ...... %c\n", info->data.ia32.ssse3   ? 'Y' : 'n');
208		fprintf(stderr, "  3DNow! ..... %c\n", info->data.ia32._3dnow  ? 'Y' : 'n');
209		fprintf(stderr, "  3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
210		fprintf(stderr, "  3DNow!-MMX . %c\n", info->data.ia32.extmmx  ? 'Y' : 'n');
211#endif
212
213		/*
214		 * now have to check for OS support of SSE/SSE2
215		 */
216		if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
217#if defined FLAC__NO_SSE_OS
218			/* assume user knows better than us; turn it off */
219			info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
220#elif defined FLAC__SSE_OS
221			/* assume user knows better than us; leave as detected above */
222#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
223			int sse = 0;
224			size_t len;
225			/* at least one of these must work: */
226			len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
227			len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse"   , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
228			if(!sse)
229				info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
230#elif defined(__NetBSD__) || defined (__OpenBSD__)
231# if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
232			int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
233			size_t len = sizeof(val);
234			if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
235				info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
236			else { /* double-check SSE2 */
237				mib[1] = CPU_SSE2;
238				len = sizeof(val);
239				if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
240					info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
241			}
242# else
243			info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
244# endif
245#elif defined(__linux__)
246			int sse = 0;
247			struct sigaction sigill_save;
248#ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
249			if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
250#else
251			struct sigaction sigill_sse;
252			sigill_sse.sa_sigaction = sigill_handler_sse_os;
253			__sigemptyset(&sigill_sse.sa_mask);
254			sigill_sse.sa_flags = SA_SIGINFO | SA_RESETHAND; /* SA_RESETHAND just in case our SIGILL return jump breaks, so we don't get stuck in a loop */
255			if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
256#endif
257			{
258				/* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
259				/* see sigill_handler_sse_os() for an explanation of the following: */
260				asm volatile (
261					"xorl %0,%0\n\t"          /* for some reason, still need to do this to clear 'sse' var */
262					"xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
263					"incl %0\n\t"             /* SIGILL handler will jump over this */
264					/* landing zone */
265					"nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
266					"nop\n\t"
267					"nop\n\t"
268					"nop\n\t"
269					"nop\n\t"
270					"nop\n\t"
271					"nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
272					"nop\n\t"
273					"nop"     /* SIGILL jump lands here if "inc" is 1 byte */
274					: "=r"(sse)
275					: "r"(sse)
276				);
277
278				sigaction(SIGILL, &sigill_save, NULL);
279			}
280
281			if(!sse)
282				info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
283#elif defined(_MSC_VER)
284# ifdef USE_TRY_CATCH_FLAVOR
285			_try {
286				__asm {
287#  if _MSC_VER <= 1200
288					/* VC6 assembler doesn't know SSE, have to emit bytecode instead */
289					_emit 0x0F
290					_emit 0x57
291					_emit 0xC0
292#  else
293					xorps xmm0,xmm0
294#  endif
295				}
296			}
297			_except(EXCEPTION_EXECUTE_HANDLER) {
298				if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
299					info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
300			}
301# else
302			int sse = 0;
303			LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
304			/* see GCC version above for explanation */
305			/*  http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
306			/*  http://www.codeproject.com/cpp/gccasm.asp */
307			/*  http://www.hick.org/~mmiller/msvc_inline_asm.html */
308			__asm {
309#  if _MSC_VER <= 1200
310				/* VC6 assembler doesn't know SSE, have to emit bytecode instead */
311				_emit 0x0F
312				_emit 0x57
313				_emit 0xC0
314#  else
315				xorps xmm0,xmm0
316#  endif
317				inc sse
318				nop
319				nop
320				nop
321				nop
322				nop
323				nop
324				nop
325				nop
326				nop
327			}
328			SetUnhandledExceptionFilter(save);
329			if(!sse)
330				info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
331# endif
332#else
333			/* no way to test, disable to be safe */
334			info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
335#endif
336#ifdef DEBUG
337		fprintf(stderr, "  SSE OS sup . %c\n", info->data.ia32.sse     ? 'Y' : 'n');
338#endif
339
340		}
341	}
342#else
343	info->use_asm = false;
344#endif
345
346/*
347 * PPC-specific
348 */
349#elif defined FLAC__CPU_PPC
350	info->type = FLAC__CPUINFO_TYPE_PPC;
351# if !defined FLAC__NO_ASM
352	info->use_asm = true;
353#  ifdef FLAC__USE_ALTIVEC
354#   if defined FLAC__SYS_DARWIN
355	{
356		int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
357		size_t len = sizeof(val);
358		info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
359	}
360	{
361		host_basic_info_data_t hostInfo;
362		mach_msg_type_number_t infoCount;
363
364		infoCount = HOST_BASIC_INFO_COUNT;
365		host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
366
367		info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
368	}
369#   else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
370	{
371		/* no Darwin, do it the brute-force way */
372		/* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
373		info->data.ppc.altivec = 0;
374		info->data.ppc.ppc64 = 0;
375
376		signal (SIGILL, sigill_handler);
377		canjump = 0;
378		if (!sigsetjmp (jmpbuf, 1)) {
379			canjump = 1;
380
381			asm volatile (
382				"mtspr 256, %0\n\t"
383				"vand %%v0, %%v0, %%v0"
384				:
385				: "r" (-1)
386			);
387
388			info->data.ppc.altivec = 1;
389		}
390		canjump = 0;
391		if (!sigsetjmp (jmpbuf, 1)) {
392			int x = 0;
393			canjump = 1;
394
395			/* PPC64 hardware implements the cntlzd instruction */
396			asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
397
398			info->data.ppc.ppc64 = 1;
399		}
400		signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
401	}
402#   endif
403#  else /* !FLAC__USE_ALTIVEC */
404	info->data.ppc.altivec = 0;
405	info->data.ppc.ppc64 = 0;
406#  endif
407# else
408	info->use_asm = false;
409# endif
410
411/*
412 * unknown CPI
413 */
414#else
415	info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
416	info->use_asm = false;
417#endif
418}
419